Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: ea549b93f198f9efdfd80d8b321cc37e877b4935 (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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*******************************************************************************
 * Copyright (c) 2007, 2010 Wind River Systems, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tm.tcf.core;

import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import org.eclipse.tm.internal.tcf.core.Token;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IErrorReport;
import org.eclipse.tm.tcf.protocol.IService;
import org.eclipse.tm.tcf.protocol.IToken;
import org.eclipse.tm.tcf.protocol.JSON;
import org.eclipse.tm.tcf.protocol.Protocol;


/**
 * This is utility class that helps to implement sending a command and receiving
 * command result over TCF communication channel. The class uses JSON to encode
 * command arguments and to decode result data.
 *
 * The class also provides support for TCF standard error report encoding.
 *
 * Clients are expected to subclass <code>Command</code> and override <code>done</code> method.
 *
 * Note: most clients don't need to handle protocol commands directly and
 * can use service APIs instead. Service API does all command encoding/decoding
 * for a client.
 *
 * Typical usage example:
 *
 *  public IToken getContext(String id, final DoneGetContext done) {
 *      return new Command(channel, IService.this, "getContext", new Object[]{ id }) {
 *          @Override
 *          public void done(Exception error, Object[] args) {
 *              Context ctx = null;
 *              if (error == null) {
 *                  assert args.length == 2;
 *                  error = toError(args[0]);
 *                  if (args[1] != null) ctx = new Context(args[1]);
 *              }
 *              done.doneGetContext(token, error, ctx);
 *          }
 *      }.token;
 *  }
 */
public abstract class Command implements IChannel.ICommandListener {

    private final IService service;
    private final String command;
    private final Object[] args;

    public final IToken token;

    private boolean done;

    private static final SimpleDateFormat timestamp_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static int arg_size_limit = Integer.MAX_VALUE;

    public Command(IChannel channel, IService service, String command, Object[] args) {
        this.service = service;
        this.command = command;
        this.args = args;
        IToken t = null;
        try {
            boolean zero_copy = ((AbstractChannel)channel).isZeroCopySupported();
            t = channel.sendCommand(service, command, JSON.toJSONSequence(args, zero_copy), this);
        }
        catch (Throwable y) {
            t = new Token();
            final Exception x = y instanceof Exception ? (Exception)y : new Exception(y);
            Protocol.invokeLater(new Runnable() {
                public void run() {
                    assert !done;
                    done = true;
                    done(x, null);
                }
            });
        }
        token = t;
    }

    public void progress(IToken token, byte[] data) {
        assert this.token == token;
    }

    public void result(IToken token, byte[] data) {
        assert this.token == token;
        Exception error = null;
        Object[] args = null;
        try {
            args = JSON.parseSequence(data);
        }
        catch (Exception e) {
            error = e;
        }
        assert !done;
        done = true;
        done(error, args);
    }

    public void terminated(IToken token, Exception error) {
        assert this.token == token;
        assert !done;
        done = true;
        done(error, null);
    }

    public abstract void done(Exception error, Object[] args);

    private int getArgSizeLimit() {
        if (arg_size_limit == Integer.MAX_VALUE) {
            arg_size_limit = 100;
            String name = "org.eclipse.tcf.core.errmsg_size_limit";
            try {
                String s = System.getProperty(name);
                if (s != null) arg_size_limit = Integer.parseInt(s);
            }
            catch (NumberFormatException x) {
                Protocol.log("Invalid value of system property " + name, x);
            }
        }
        return arg_size_limit;
    }

    public String getCommandString(int arg_size_limit) {
        if (arg_size_limit <= 0) arg_size_limit = getArgSizeLimit();
        StringBuffer buf = new StringBuffer();
        buf.append(service.getName());
        buf.append(' ');
        buf.append(command);
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                buf.append(i == 0 ? " " : ", ");
                try {
                    String s = JSON.toJSON(args[i]);
                    if (s.length() > arg_size_limit) {
                        buf.append(s.substring(0, arg_size_limit));
                        buf.append("...");
                    }
                    else {
                        buf.append(s);
                    }
                }
                catch (IOException x) {
                    buf.append("***");
                    buf.append(x.getMessage());
                    buf.append("***");
                }
            }
        }
        return buf.toString();
    }

    public String getCommandString() {
        return getCommandString(Integer.MAX_VALUE);
    }

    @SuppressWarnings({ "unchecked" })
    public static String toErrorString(Object data) {
        if (data == null) return null;
        Map<String,Object> map = (Map<String,Object>)data;
        String fmt = (String)map.get(IErrorReport.ERROR_FORMAT);
        if (fmt != null) {
            Collection<Object> c = (Collection<Object>)map.get(IErrorReport.ERROR_PARAMS);
            if (c != null) return new MessageFormat(fmt).format(c.toArray());
            return fmt;
        }
        Number code = (Number)map.get(IErrorReport.ERROR_CODE);
        if (code != null) {
            if (code.intValue() == IErrorReport.TCF_ERROR_OTHER) {
                String alt_org = (String)map.get(IErrorReport.ERROR_ALT_ORG);
                Number alt_code = (Number)map.get(IErrorReport.ERROR_ALT_CODE);
                if (alt_org != null && alt_code != null) {
                    return alt_org + " Error " + alt_code;
                }
            }
            return "TCF Error " + code;
        }
        return "Invalid error report format";
    }

    static void appendErrorProps(StringBuffer bf, Map<String,Object> map) {
        Number time = (Number)map.get(IErrorReport.ERROR_TIME);
        Number code = (Number)map.get(IErrorReport.ERROR_CODE);
        String service = (String)map.get(IErrorReport.ERROR_SERVICE);
        Number severity = (Number)map.get(IErrorReport.ERROR_SEVERITY);
        Number alt_code = (Number)map.get(IErrorReport.ERROR_ALT_CODE);
        String alt_org = (String)map.get(IErrorReport.ERROR_ALT_ORG);
        if (time != null) {
            bf.append('\n');
            bf.append("Time: ");
            bf.append(timestamp_format.format(new Date(time.longValue())));
        }
        if (severity != null) {
            bf.append('\n');
            bf.append("Severity: ");
            switch (severity.intValue()) {
            case IErrorReport.SEVERITY_ERROR: bf.append("Error");
            case IErrorReport.SEVERITY_FATAL: bf.append("Fatal");
            case IErrorReport.SEVERITY_WARNING: bf.append("Warning");
            default: bf.append("Unknown");
            }
        }
        bf.append('\n');
        bf.append("Error text: ");
        bf.append(toErrorString(map));
        bf.append('\n');
        bf.append("Error code: ");
        bf.append(code);
        if (service != null) {
            bf.append('\n');
            bf.append("Service: ");
            bf.append(service);
        }
        if (alt_code != null) {
            bf.append('\n');
            bf.append("Alt code: ");
            bf.append(alt_code);
            if (alt_org != null) {
                bf.append('\n');
                bf.append("Alt org: ");
                bf.append(alt_org);
            }
        }
    }

    public Exception toError(Object data) {
        return toError(data, true);
    }

    @SuppressWarnings("unchecked")
    public Exception toError(Object data, boolean include_command_text) {
        if (data == null) return null;
        Map<String,Object> map = (Map<String,Object>)data;
        StringBuffer bf = new StringBuffer();
        bf.append("TCF error report:");
        bf.append('\n');
        if (include_command_text) {
            bf.append("Command: ");
            bf.append(getCommandString(0));
        }
        appendErrorProps(bf, map);
        return new ErrorReport(bf.toString(), map);
    }
}

Back to the top