刘光辉
15 小时以前 34981c30a78e8bbd7791131059a9210f9928b62c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package jnpf.dmsPermission;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;
 
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
 
@Component
public class DmsCursorCodec {
 
    public String encode(Date time, UUID id) {
        String raw = time.toInstant().toString() + "|" + id;
        return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
    }
 
    public Cursor decode(String value) {
        if (value == null || value.trim().isEmpty()) {
            return new Cursor(null, null);
        }
        try {
            String raw = new String(Base64.getUrlDecoder().decode(value), StandardCharsets.UTF_8);
            int separator = raw.indexOf('|');
            if (separator < 1) {
                throw new IllegalArgumentException("missing separator");
            }
            return new Cursor(Timestamp.from(Instant.parse(raw.substring(0, separator))),
                    UUID.fromString(raw.substring(separator + 1)));
        } catch (RuntimeException ex) {
            throw DmsPermissionException.of(DmsPermissionError.INVALID_REQUEST, "分页 cursor 无效");
        }
    }
 
    @Data
    @AllArgsConstructor
    public static class Cursor {
        private Date time;
        private UUID id;
    }
}