1 package com.tapina.robe.swi;
2
3 import com.tapina.robe.module.Module;
4
5 import java.lang.reflect.InvocationTargetException;
6 import java.lang.reflect.Method;
7 import java.util.Map;
8 import java.util.HashMap;
9
10 /***
11 * Created by IntelliJ IDEA.
12 * User: gareth
13 * Date: Aug 21, 2003
14 * Time: 6:13:16 PM
15 */
16 public final class SWIDecoder {
17 private static final Map swiHandlers = new HashMap(30);
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 private static final Class[] EMPTY_PARAM_TYPE = new Class[0];
39 private static final Object[] EMPTY_PARAM_LIST = new Object[0];
40 private static final Class[] INT_PARAM_TYPE = new Class[] { Integer.class };
41 static final int SWI_BASE_MASK = 0xffffc0;
42
43 public static Method decode(int swiNumber) throws NoSuchMethodException {
44 final Object[] swiOffsetParam = new Object[] { new Integer(swiNumber & 0x3f) };
45 Class swiHandler = getSwiHandler(swiNumber);
46 try {
47 final Method method = (Method) swiHandler.getMethod("getMethod", INT_PARAM_TYPE).invoke(null, swiOffsetParam);
48 if (method == null) {
49 throw new NoSuchMethodException();
50 }
51 return method;
52 } catch (IllegalAccessException e) {
53 throw new NoSuchMethodException();
54 } catch (InvocationTargetException e) {
55 throw new NoSuchMethodException();
56 }
57 }
58
59 public static Class getSwiHandler(int swiNumber) throws NoSuchMethodException {
60 final Integer swiBase = new Integer(swiNumber & SWI_BASE_MASK);
61 final Class swiHandler = (Class) swiHandlers.get(swiBase);
62 if (swiHandler != null) {
63 return swiHandler;
64 }
65 throw new NoSuchMethodException();
66 }
67
68 public static void registerHandler(SWIHandler handler) {
69 try {
70 final Class swiHandler = handler.getClass();
71 final int swiHandlerBase = ((Integer) swiHandler.getMethod("getBase", EMPTY_PARAM_TYPE)
72 .invoke(null, EMPTY_PARAM_LIST)).intValue();
73 swiHandlers.put(new Integer(swiHandlerBase), swiHandler);
74 } catch (Exception e) {
75 throw new RuntimeException(e);
76 }
77 }
78 }