| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551 |
- package com.izouma.nineth;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.serializer.SerializerFeature;
- import com.github.kevinsawicki.http.HttpRequest;
- import com.google.common.base.Splitter;
- import com.izouma.nineth.config.Constants;
- import com.izouma.nineth.domain.BaseEntity;
- import com.izouma.nineth.domain.BlindBoxItem;
- import com.izouma.nineth.domain.User;
- import com.izouma.nineth.dto.PageQuery;
- import com.izouma.nineth.service.IdentityAuthService;
- import com.izouma.nineth.utils.AESEncryptUtil;
- import com.izouma.nineth.utils.TokenUtils;
- import com.izouma.nineth.web.BaseController;
- import io.ipfs.api.IPFS;
- import io.ipfs.api.MerkleNode;
- import io.ipfs.api.NamedStreamable;
- import io.ipfs.multihash.Multihash;
- import io.jsonwebtoken.Claims;
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.SignatureAlgorithm;
- import lombok.SneakyThrows;
- import net.coobird.thumbnailator.Thumbnails;
- import org.apache.commons.codec.EncoderException;
- import org.apache.commons.codec.net.URLCodec;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.lang3.RandomStringUtils;
- import org.apache.commons.lang3.RandomUtils;
- import org.apache.commons.lang3.Range;
- import org.apache.commons.text.CaseUtils;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.utils.URLEncodedUtils;
- import org.apache.poi.util.TempFile;
- import org.bouncycastle.util.encoders.Base64;
- import org.bytedeco.javacv.FFmpegFrameGrabber;
- import org.bytedeco.javacv.Frame;
- import org.bytedeco.javacv.Java2DFrameConverter;
- import org.junit.Test;
- import org.libjpegturbo.turbojpeg.processor.api.ImageProcessException;
- import org.libjpegturbo.turbojpeg.processor.api.ImageProcessInfo;
- import org.libjpegturbo.turbojpeg.processor.api.ImageProcessor;
- import org.libjpegturbo.turbojpeg.processor.impl.ImageProcessorImpl;
- import org.libjpegturbo.turbojpeg.processor.utils.ImageProcessorUtils;
- import org.pngquant.PngQuant;
- import org.reflections.ReflectionUtils;
- import org.reflections.Reflections;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.util.FileCopyUtils;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import javax.imageio.ImageIO;
- import java.awt.*;
- import java.awt.font.FontRenderContext;
- import java.awt.geom.AffineTransform;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.math.RoundingMode;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.security.NoSuchAlgorithmException;
- import java.util.List;
- import java.util.*;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ForkJoinPool;
- import java.util.regex.Pattern;
- import java.util.stream.IntStream;
- import static java.nio.file.StandardOpenOption.CREATE;
- import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
- public class CommonTest {
- @Test
- public void getGenericsClass() {
- List<User> data = new ArrayList<>();
- data.add(new User());
- System.out.println(data.get(0).getClass().getSimpleName());
- System.out.println(data.getClass());
- Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".domain");
- Set<Class<? extends BaseEntity>> allClasses = reflections.getSubTypesOf(BaseEntity.class);
- for (Class<? extends BaseEntity> allClass : allClasses) {
- System.out.println(allClass.getName());
- }
- }
- @Test
- public void getapis() {
- List<Map<String, String>> entities = new ArrayList<>();
- Reflections classReflections = new Reflections(this.getClass().getPackage().getName());
- Set<Class<? extends BaseController>> controllers = classReflections.getSubTypesOf(BaseController.class);
- Set<Class<? extends BaseController>> list = ReflectionUtils
- .getAll(controllers, ReflectionUtils.withAnnotation(RestController.class));
- System.out.println(list);
- for (Class<? extends BaseController> aClass : list) {
- RequestMapping requestMapping = aClass.getAnnotation(RequestMapping.class);
- String baseUrl = requestMapping.value()[0];
- for (Method method : ReflectionUtils.getMethods(aClass, ReflectionUtils.withAnnotation(GetMapping.class))) {
- GetMapping getMapping = method.getAnnotation(GetMapping.class);
- System.out.println(getMapping.value()[0]);
- }
- for (Method method : ReflectionUtils
- .getMethods(aClass, ReflectionUtils.withAnnotation(PostMapping.class))) {
- PostMapping postMapping = method.getAnnotation(PostMapping.class);
- System.out.println(postMapping.value()[0]);
- }
- }
- }
- @Test
- public void testCaseUtils() {
- System.out.println(CaseUtils.toCamelCase("test_Model", true, '_'));
- }
- @Test
- public void testMeasureText() throws IOException, FontFormatException {
- AffineTransform affinetransform = new AffineTransform();
- FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
- Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass()
- .getResourceAsStream("/font/SourceHanSansCN-Normal.ttf"));
- System.out.println((int) (font.deriveFont(14f).getStringBounds("aaa", frc).getWidth()));
- }
- @Test
- public void testIdNoRegexp() {
- boolean b = Pattern
- .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");
- System.out.println(b);
- }
- @Test
- public void tesSms() throws IOException {
- Reflections reflections = new Reflections(this.getClass().getPackage().getName() + ".enums");
- Set<Class<? extends Enum>> entitySet = reflections.getSubTypesOf(Enum.class);
- StringBuilder idxJs = new StringBuilder();
- for (Class<? extends Enum> entity : entitySet) {
- idxJs.append("import ").append(entity.getSimpleName()).append(" from \"./").append(entity.getSimpleName())
- .append("\";\n");
- StringBuilder str = new StringBuilder("export default {\n");
- for (Enum enumConstant : entity.getEnumConstants()) {
- str.append(" ").append(enumConstant.name()).append(": \"").append(enumConstant.name())
- .append("\",\n");
- }
- str.append("}");
- Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", entity
- .getSimpleName() + ".js"), str.toString()
- .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
- Files.write(Paths.get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", entity
- .getSimpleName() + ".js"), str.toString()
- .getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
- }
- idxJs.append("export default {\n");
- for (Class<? extends Enum> entity : entitySet) {
- idxJs.append(" ").append(entity.getSimpleName()).append(": ").append(entity.getSimpleName())
- .append(",\n");
- }
- idxJs.append("}");
- System.out.println(idxJs.toString());
- Files.write(Paths
- .get(System.getProperty("user.dir"), "src", "main", "vue", "src", "constants", "index.js"), idxJs
- .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
- Files.write(Paths
- .get(System.getProperty("user.dir"), "src", "main", "zmj_mp", "src", "constants", "index.js"), idxJs
- .toString().getBytes(StandardCharsets.UTF_8), CREATE, TRUNCATE_EXISTING);
- }
- @Test
- public void gen() {
- System.out.println(RandomStringUtils.randomAlphabetic(32));
- }
- @Test
- public void password() {
- String password = new BCryptPasswordEncoder().encode("123456");
- System.out.println(password);
- }
- @SneakyThrows
- @Test
- public void pngquant() {
- PngQuant pngQuant = new PngQuant();
- ImageIO.write(pngQuant
- .getRemapped(ImageIO.read(new File("/Users/drew/Downloads/2021-11-01-18-07-04JCDfFxKb.HEIC"))),
- "jpg", new File("/Users/drew/Downloads/111.jpg"));
- }
- @SneakyThrows
- @Test
- public void mozjpeg() {
- File out = TempFile.createTempFile("kljasdlkhfasldg", ".jpg");
- ImageProcessor processor = new ImageProcessorImpl();
- ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
- new File("/Users/drew/Downloads/2020-09-08-17-07-21zwBhaHeQ.jpg"),
- out, 75));
- FileCopyUtils.copy(out, new File("/Users/drew/Desktop/111.jpg"));
- System.out.println(out);
- }
- @Test
- public void thumbnailator() throws IOException, ImageProcessException {
- Thumbnails.of(new File("/Users/drew/Downloads/2021-11-01-17-47-55zMwbSlgJ.jpeg"))
- .size(3000, 3000)
- .outputFormat("jpg")
- .toFile("/Users/drew/Desktop/1.jpg");
- PngQuant pngQuant = new PngQuant();
- ImageIO.write(pngQuant
- .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.jpg"))),
- "jpg", new File("/Users/drew/Desktop/2.jpg"));
- ImageProcessor processor = new ImageProcessorImpl();
- ImageProcessInfo processInfo = ImageProcessInfo.fromMap(ImageProcessorUtils.compressImage(processor,
- new File("/Users/drew/Desktop/1.jpg"),
- new File("/Users/drew/Desktop/3.jpg"), 75));
- }
- @Test
- public void base64() {
- System.out.println(Base64.decode("e6e6vQJYhGmIkcA1pfnsipTovp10wJ"));
- }
- @Test
- public void resolveUrl() {
- try {
- System.out.println(new URLCodec().encode("http://www.baidu.com"));
- } catch (EncoderException e) {
- e.printStackTrace();
- }
- }
- @Test
- public void testIPFS() throws IOException {
- IPFS ipfs = new IPFS("121.40.132.44", 5001);
- HttpRequest request = HttpRequest.get("https://awesomeadmin.oss-cn-hangzhou.aliyuncs.com/image/2021-10-21-16-44-52kZqxuwhH.gif");
- File file = File.createTempFile("ipfs", ".tmp");
- request.receive(file);
- NamedStreamable.FileWrapper file1 = new NamedStreamable.FileWrapper(file);
- MerkleNode put = ipfs.add(file1).get(0);
- Multihash multihash = ipfs.pin.add(put.hash).get(0);
- System.out.println(put.hash.toBase58());
- System.out.println(multihash.toBase58());
- }
- @Test
- public void testWin() {
- List<BlindBoxItem> items = new ArrayList<>();
- items.add(BlindBoxItem.builder()
- .name("普通1")
- .total(100)
- .stock(100)
- .build());
- items.add(BlindBoxItem.builder()
- .name("普通2")
- .total(100)
- .stock(100)
- .build());
- items.add(BlindBoxItem.builder()
- .name("稀有1")
- .total(5)
- .stock(5)
- .rare(true)
- .build());
- items.add(BlindBoxItem.builder()
- .name("稀有2")
- .total(5)
- .stock(5)
- .rare(true)
- .build());
- for (int k = 0; k < items.stream().mapToInt(BlindBoxItem::getTotal).sum(); k++) {
- Map<BlindBoxItem, Range<Integer>> randomRange = new HashMap<>();
- int c = 0, sum = 0;
- for (BlindBoxItem item : items) {
- randomRange.put(item, Range.between(c, c + item.getStock()));
- c += item.getStock();
- sum += item.getStock();
- }
- boolean win = false;
- int retry = 0;
- BlindBoxItem winItem = null;
- while (winItem == null) {
- int rand = RandomUtils.nextInt(0, sum + 1);
- for (Map.Entry<BlindBoxItem, Range<Integer>> entry : randomRange.entrySet()) {
- BlindBoxItem item = entry.getKey();
- Range<Integer> range = entry.getValue();
- if (rand >= range.getMinimum() && rand < range.getMaximum()) {
- int total = items.stream().filter(i -> !i.isRare())
- .mapToInt(BlindBoxItem::getTotal).sum();
- int stock = items.stream().filter(i -> !i.isRare())
- .mapToInt(BlindBoxItem::getStock).sum();
- if (item.isRare()) {
- double nRate = stock / (double) total;
- double rRate = (item.getStock() - 1) / (double) item.getTotal();
- if (Math.abs(nRate - rRate) < (1 / (double) item.getTotal()) || retry > 1 || rRate == 0) {
- if (!(nRate > 0.1 && item.getStock() == 1)) {
- winItem = item;
- }
- } else {
- retry++;
- }
- } else {
- double nRate = (stock - 1) / (double) total;
- double rRate = item.getStock() / (double) item.getTotal();
- if (Math.abs(nRate - rRate) < 0.2 || retry > 1 || nRate == 0) {
- winItem = item;
- } else {
- retry++;
- }
- }
- }
- }
- }
- winItem.setStock(winItem.getStock() - 1);
- System.out.println(winItem.getName() + (winItem.isRare() ? "\t+++" : ""));
- }
- }
- @Test
- public void testGrabFrame() throws IOException {
- FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber("/Users/drew/Downloads/video1627914878375.mp4");
- frameGrabber.start();
- Java2DFrameConverter aa = new Java2DFrameConverter();
- int length = frameGrabber.getLengthInVideoFrames();
- Frame frame = null;
- int i = 0;
- while (frame == null && i < length) {
- frame = frameGrabber.grabKeyFrame();
- i++;
- }
- Objects.requireNonNull(frame);
- BufferedImage thumbBi = aa.convert(frame);
- ImageIO.write(thumbBi, "jpg", new File("/Users/drew/Desktop/1.jpg"));
- }
- @Test
- public void testQuality() throws IOException {
- Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
- .size(1000, 1000)
- .outputFormat("jpg")
- .outputQuality(1)
- .toFile("/Users/drew/Desktop/1.jpg");
- Thumbnails.of("/Users/drew/Desktop/2021-11-04-11-28-36VAOoasUd.jpeg")
- .size(1000, 1000)
- .outputFormat("jpg")
- .outputQuality(0.6)
- .toFile("/Users/drew/Desktop/2.jpg");
- }
- @Test
- public void testJwt() {
- String token = Jwts.builder()
- .setClaims(new HashMap<>())
- .setSubject("15077886171")
- .setIssuedAt(new Date())
- .setExpiration(new Date(new Date().getTime() + 10 * 60 * 1000)) //10min
- .signWith(SignatureAlgorithm.HS512, Constants.SMS_TOKEN_SECRET)
- .compact();
- System.out.println(token);
- Claims claims = Jwts.parser()
- .setSigningKey(Constants.SMS_TOKEN_SECRET)
- .parseClaimsJws(token)
- .getBody();
- System.out.println(claims.getSubject());
- System.out.println(claims.getExpiration());
- }
- @Test
- public void testReplace() {
- System.out.println("15077886171".replaceAll("(?<=.{3}).*(?=.{4})", "**"));
- }
- @Test
- public void sfsdf() {
- System.out.println(BigDecimal.valueOf(11111110.5).setScale(2, RoundingMode.HALF_UP).toPlainString());
- }
- @Test
- public void random256() throws NoSuchAlgorithmException {
- String tokenId = TokenUtils.genTokenId();
- System.out.println(tokenId);
- System.out.println(new BigInteger(tokenId, 16));
- }
- @Test
- public void dd() throws IOException {
- String[] arr1 = FileUtils.readFileToString(new File("/Users/drew/Desktop/未命名文件夹 2/111")).split("\n");
- List<String> arr2 = Arrays.asList(FileUtils.readFileToString(new File("/Users/drew/Desktop/未命名文件夹 2/222"))
- .split("\n"));
- for (String s : arr1) {
- if (!arr2.contains(s)) {
- System.out.println(s);
- }
- }
- }
- @Test
- public void jj() {
- final int parallelism = 4;
- ForkJoinPool forkJoinPool = null;
- try {
- forkJoinPool = new ForkJoinPool(parallelism);
- forkJoinPool.submit(() ->
- // Parallel task here, for example
- IntStream.range(1, 1_000_000).parallel()
- .forEach(i -> {
- })
- );
- } finally {
- if (forkJoinPool != null) {
- forkJoinPool.shutdown();
- }
- }
- }
- @Test
- public void testnewSingleThreadScheduledExecutor() throws InterruptedException {
- ExecutorService service = Executors.newFixedThreadPool(10);
- final int[] c = {0};
- for (int i = 0; i < 1000; i++) {
- service.submit(new Runnable() {
- @SneakyThrows
- @Override
- public void run() {
- Thread.sleep(300);
- System.out.println(++c[0]);
- }
- });
- }
- Thread.sleep(20000);
- }
- @Test
- public void testaes() throws Exception {
- String encrypted = "ccd97379f001d47895eb4293144b74f28de4fcf5b56daf4ce73d2db34f381984b2c2260f821593968e387dccdc11713a5b558a571b17aaae3e9e91a0b9dc576e";
- String qs = AESEncryptUtil.decrypt(encrypted);
- System.out.println(qs);
- List<NameValuePair> list = URLEncodedUtils.parse(qs, StandardCharsets.UTF_8);
- System.out.println(JSON.toJSONString(list, SerializerFeature.PrettyFormat));
- final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(qs);
- System.out.println(map);
- }
- @Test
- public void aasdf() {
- System.out.println(new BCryptPasswordEncoder().matches("123456", "$2a$10$hYKQk3SKDqpK2QPDFqGdLekKWFcHs8rvou0hV4TxFy.ylL8PTBo5a"));
- }
- @Test
- public void testBCrypt() {
- BCryptPasswordEncoder encoder1 = new BCryptPasswordEncoder(4);
- BCryptPasswordEncoder encoder2 = new BCryptPasswordEncoder(4);
- String pwd = "$2a$10$oAWnGIHR2Cvc0BsMN7YCtOjvXsBLBygYxiVG3E1fuUmhM3sEOYhQe";
- System.out.println(encoder1.matches("123456", pwd));
- System.out.println(encoder2.matches("123456", pwd));
- System.out.println(encoder1.matches("1234561", pwd));
- System.out.println(encoder2.matches("1234561", pwd));
- long encode1 = 0;
- long match1 = 0;
- for (int i = 0; i < 10; i++) {
- long t = System.currentTimeMillis();
- encoder1.encode("123456");
- encode1 += System.currentTimeMillis() - t;
- t = System.currentTimeMillis();
- encoder1.matches("123456", pwd);
- match1 += System.currentTimeMillis() - t;
- }
- System.out.println("avg encode = " + encode1 / 10 + "ms");
- System.out.println("avg match = " + match1 / 10 + "ms");
- long encode2 = 0;
- long match2 = 0;
- for (int i = 0; i < 10; i++) {
- long t = System.currentTimeMillis();
- encoder2.encode("123456");
- encode2 += System.currentTimeMillis() - t;
- t = System.currentTimeMillis();
- encoder2.matches("123456", pwd);
- match2 += System.currentTimeMillis() - t;
- }
- System.out.println("avg encode = " + encode2 / 10 + "ms");
- System.out.println("avg match = " + match2 / 10 + "ms");
- }
- @Test
- public void testParseToken() {
- long t1 = 0;
- long t2 = 0;
- for (int i = 0; i < 1000; i++) {
- long t = System.currentTimeMillis();
- String token = Jwts.builder()
- .setClaims(new HashMap<>())
- .setSubject("a" + i)
- .setIssuedAt(new Date())
- .setExpiration(new Date(new Date().getTime() + 10000000))
- .signWith(SignatureAlgorithm.HS256, "123456")
- .compact();
- t1 += System.currentTimeMillis() - t;
- System.out.println(token);
- t = System.currentTimeMillis();
- Claims claims = Jwts.parser()
- .setSigningKey("123456")
- .parseClaimsJws(token)
- .getBody();
- System.out.println(claims.getSubject());
- t2 += System.currentTimeMillis() - t;
- }
- System.out.println(t1);
- System.out.println(t2);
- System.out.println(t1 / 1000);
- System.out.println(t2 / 1000);
- }
- @Test
- public void testHashCode() {
- long t = System.currentTimeMillis();
- new PageQuery().hashCode();
- System.out.println(System.currentTimeMillis() - t);
- }
- @Test
- public void testAuth() {
- IdentityAuthService.validate ("班祥佳", "17025596046", "45213119921012413X");
- }
- }
|