MCPcopy Create free account
hub / github.com/PlexPt/rocket-pt / BencodeUtil

Class BencodeUtil

src/main/java/com/rocketpt/server/util/BencodeUtil.java:14–128  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12 *
13 */
14public class BencodeUtil {
15
16 public static final String exceptionMsg = "Oops! Your request is like an alien language to us, we " +
17 "can't encode it!";
18
19 public interface Errors {
20 String CLIENT_ERROR = BencodeUtil.error("Oops! Your request is like an alien language to " +
21 "us, we can't decode it!");
22 String INTERNAL_ERROR_60 = BencodeUtil.error("Give us a moment, try again later!", 60);
23 String INTERNAL_ERROR_120 = BencodeUtil.error("Hold your horses! then try again later!",
24 120);
25
26
27 }
28
29 public static String error(String reason) {
30 return encode(Map.of("failure reason", reason));
31 }
32
33 public static String errorNoRetry(String reason) {
34 return encode(Map.of("failure reason", reason,
35 "retry in", "never"
36 ));
37 }
38
39 public static String warning(String reason) {
40 return encode(Map.of("warning message", reason));
41 }
42
43 public static String error() {
44 return Errors.CLIENT_ERROR;
45 }
46
47
48 public static String error(String reason, Integer retry) {
49 return encode(Map.of("failure reason", reason, "retry in", retry));
50 }
51
52 public static <K, V> String encode(Map<K, V> data) {
53 try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
54 try (BencodeOutputStream bencoder = new BencodeOutputStream(out)) {
55 bencoder.writeDictionary(data);
56 return out.toString();
57 }
58 } catch (IOException e) {
59 throw new TrackerException(exceptionMsg, e);
60 }
61 }
62
63 public static String encode(Integer data) {
64 try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
65 try (BencodeOutputStream bencoder = new BencodeOutputStream(out)) {
66 bencoder.write(data);
67 return out.toString();
68 }
69 } catch (IOException e) {
70 throw new TrackerException(exceptionMsg, e);
71 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected