aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/construct/MessageLoader.java
blob: 6063d51d94eaff58f5764fd11c4f34b9a0022cb9 (plain) (blame)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
 *
 * This file is part of GNUnet.
 * Copyright (C) 2011 Christian Grothoff (and other contributing authors)
 *
 * GNUnet is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2, or (at your
 * option) any later version.
 *
 * GNUnet is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNUnet; see the file COPYING.  If not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

package org.gnunet.construct;


import com.google.common.base.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * Load message maps, which contain the information the parse/write unions.
 */
public class MessageLoader {
    private static final Logger logger = LoggerFactory
            .getLogger(MessageLoader.class);


    /**
     * Thrown when trying to serialize an object that is not registered as a union type.
     */
    public static class UnknownUnionException extends RuntimeException {
        public UnknownUnionException(String msg) {
            super(msg);
        }
    }


    /**
     * Thrown when parsing a union whose ID is not known.
     */
    public static class UnknownUnionIdException extends RuntimeException {

    }

    /**
     * Maps a class and tag to the corresponding union case.
     * <p/>
     * XXX: how much of generics is too much?
     */
    private static Map<Class<? extends MessageUnion>, Map<Integer, Class<? extends MessageUnion>>> unionmap
            = new HashMap<Class<? extends MessageUnion>, Map<Integer, Class<? extends MessageUnion>>>(100);

    /*
     * Maps a union interface and union case to the corresponding tag.
     */
    private static Map<Class<? extends MessageUnion>, Map<Class<? extends MessageUnion>, Integer>> tagmap
            = new HashMap<Class<? extends MessageUnion>, Map<Class<? extends MessageUnion>, Integer>>(100);


    static {
        ClassLoader classLoader = MessageLoader.class.getClassLoader();
        Enumeration<URL> resources;
        try {
            resources = classLoader.getResources("org/gnunet/construct/MsgMap.txt");
        } catch (IOException e) {
            throw new RuntimeException("something went wrong with loading MsgMap.txt");
        }

        while (resources.hasMoreElements()) {
            loadMessageMap(resources.nextElement());
        }

        if (tagmap.isEmpty()) {
            logger.warn("message map empty");
        }

    }

    public static void loadMessageMap(URL loc) {
        if (loc == null) {
            throw new RuntimeException("could not load message map");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(loc.openStream(), Charsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                // skip empty lines and comments
                if (line.isEmpty() || line.charAt(0) == '#') {
                    continue;
                }
                String[] m = line.split("=");
                if (m.length != 2) {
                    throw new RuntimeException("invalid message map format (separation by '=')");
                }
                String[] left = m[0].split("[|]");
                if (left.length != 2) {
                    logger.debug(m[0]);
                    logger.debug(m[1]);
                    logger.debug("split in " + left.length);
                    throw new RuntimeException("invalid message map format (left hand side)");
                }
                int id = java.lang.Integer.parseInt(left[1].trim());
                String unionCaseName = m[1].trim();
                String unionInterfaceName = left[0];

                Class<? extends MessageUnion> unionInterface = loadClass(unionInterfaceName);
                Class<? extends MessageUnion> unionCase = loadClass(unionCaseName);

                if (!unionmap.containsKey(unionInterface)) {
                    unionmap.put(unionInterface, new HashMap<Integer, Class<? extends MessageUnion>>(5));
                }
                unionmap.get(unionInterface).put(id, unionCase);


                if (!tagmap.containsKey(unionInterface)) {
                    tagmap.put(unionInterface, new HashMap<Class<? extends MessageUnion>, Integer>(5));
                }
                tagmap.get(unionInterface).put(unionCase, id);

            }
        } catch (IOException e) {
            throw new RuntimeException("could not read message map");
        } finally {
            maybeClose(in);
        }
    }

    private static void maybeClose(Closeable in) {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("error closing stream: " + e.getMessage());
        }
    }


    @SuppressWarnings("unchecked")
    private static Class<? extends MessageUnion> loadClass(String className) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Class<MessageUnion> msgClass;
        try {
            msgClass = (Class<MessageUnion>) cl.loadClass(className);
        } catch (ClassNotFoundException e) {
            throw new AssertionError(String.format("message class '%s' not found in classpath", className));
        } catch (ClassCastException e) {
            throw new AssertionError(String.format("Class %s does not inherit from MessageUnion", className));
        }
        return msgClass;
    }

    public static Class<? extends MessageUnion> getUnionClass(Class<? extends MessageUnion> unionInterface, int tag) {
        Map<Integer, Class<? extends MessageUnion>> map = unionmap.get(unionInterface);
        if (map == null) {
            throw new UnknownUnionException("don't know how to handle unions of type '" + unionInterface + "'");
        }

        Class<? extends MessageUnion> cls = map.get(tag);
        if (cls == null) {
            throw new ProtocolViolationException("don't know how to translate message of type " + tag);
        }

        return cls;
    }


    public static int getUnionTag(Class<? extends MessageUnion> unionInterface, Class<? extends MessageUnion> unionCase) {
        Map<Class<? extends MessageUnion>, Integer> map = tagmap.get(unionInterface);
        if (map == null) {
            throw new AssertionError(String.format("%s is not a known union type", unionInterface));
        }
        if (!map.containsKey(unionCase)) {
            throw new AssertionError(String.format("%s is not a known instance of %s", unionCase, unionInterface));
        }
        return map.get(unionCase);
    }

    public static Class<? extends MessageUnion>[] getUnionCases(Class<? extends MessageUnion> unionInterface) {
        Map<Class<? extends MessageUnion>, Integer> map = tagmap.get(unionInterface);
        //noinspection unchecked
        return (Class<? extends MessageUnion>[]) map.keySet().toArray(new Class[map.keySet().size()]);
    }

    public static void registerUnionCase(Class<? extends MessageUnion> unionInterface,
                                         Class<? extends MessageUnion> unionCase, int tag) {
        if (!unionmap.containsKey(unionInterface)) {
            unionmap.put(unionInterface, new HashMap<Integer, Class<? extends MessageUnion>>(5));
        }
        unionmap.get(unionInterface).put(tag, unionCase);


        if (!tagmap.containsKey(unionInterface)) {
            tagmap.put(unionInterface, new HashMap<Class<? extends MessageUnion>, Integer>(5));
        }
        tagmap.get(unionInterface).put(unionCase, tag);


    }
}