-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathPayloadUtil.java
More file actions
executable file
·287 lines (263 loc) · 10.1 KB
/
PayloadUtil.java
File metadata and controls
executable file
·287 lines (263 loc) · 10.1 KB
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package emissary.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import emissary.core.IBaseDataObject;
import emissary.util.xml.JDOMUtil;
import org.jdom2.Document;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utilities for dealing with IBaseDataObject and Lists thereof
*/
public class PayloadUtil {
public static final Logger logger = LoggerFactory.getLogger(PayloadUtil.class);
private static final String LS = System.getProperty("line.separator");
/**
* Try really hard to get a meaningful name for a payload object
*/
public static String getName(final Object o) {
String payloadName = o.getClass().getName();
if (o instanceof IBaseDataObject) {
payloadName = ((IBaseDataObject) o).shortName();
} else if (o instanceof Collection) {
final Iterator<?> pi = ((Collection<?>) o).iterator();
if (pi.hasNext()) {
payloadName = ((IBaseDataObject) pi.next()).shortName() + "(" + ((Collection<?>) o).size() + ")";
}
}
return payloadName;
}
/**
* Generate a string about the payload object
*
* @param payload the payload to describe
* @param oneLine true for a condensed one-line string
*/
public static String getPayloadDisplayString(final IBaseDataObject payload, final boolean oneLine) {
return oneLine ? getPayloadOneLineString(payload) : getPayloadDisplayString(payload);
}
/**
* Generate a string about the payload object
*
* @param payload the payload to describe
*/
public static String getPayloadDisplayString(final IBaseDataObject payload) {
final StringBuilder sb = new StringBuilder();
final List<String> th = payload.transformHistory();
final String fileName = payload.getFilename();
final List<String> currentForms = payload.getAllCurrentForms();
final Date creationTimestamp = payload.getCreationTimestamp();
sb.append("\n").append("filename: ").append(fileName).append("\n").append(" creationTimestamp: ").append(creationTimestamp).append("\n")
.append(" currentForms: ").append(currentForms).append("\n").append(" filetype: ").append(payload.getFileType()).append("\n")
.append(" transform history (").append(th.size()).append(") :").append("\n");
for (final String h : th) {
sb.append(" ").append(h).append("\n");
}
return sb.toString();
}
/**
* Generate a one-line string about the payload object
*
* @param payload the payload to describe
*/
public static String getPayloadOneLineString(final IBaseDataObject payload) {
final StringBuilder sb = new StringBuilder();
final String fn = payload.getFilename();
final int attPos = fn.indexOf(emissary.core.Family.SEP);
if (attPos != -1) {
sb.append(fn.substring(attPos + 1)).append(" ");
}
final List<String> th = payload.transformHistory();
String prev = "";
for (final String h : th) {
final int pos = h.indexOf(".");
if (pos > 0) {
final String prefix = h.substring(0, pos);
if (!prev.equals(prefix)) {
if (prev.length() != 0) {
sb.append(",");
}
sb.append(prefix);
prev = prefix;
}
}
}
sb.append(">>").append(payload.getAllCurrentForms());
sb.append("//").append(payload.getFileType());
sb.append("//").append(payload.getCreationTimestamp());
return sb.toString();
}
public static ByteBuffer serializeToByteBuffer(final Object payload) throws IOException {
return ByteBuffer.wrap(serializeToBytes(payload));
}
/**
* Serialize a payload object to bytes
*/
public static byte[] serializeToBytes(final Object payload) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
serializeToStream(bos, payload);
return bos.toByteArray();
}
/**
* Serialize a payload object to string
*/
public static String serializeToString(final Object payload) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
serializeToStream(bos, payload);
String agentData = null;
try {
agentData = bos.toString("8859_1");
} catch (UnsupportedEncodingException e) {
logger.warn("Should always support 8859_1", e);
agentData = bos.toString();
}
return agentData;
}
/**
* Serialize a payload object onto the specified stream
*/
public static void serializeToStream(final OutputStream os, final Object payload) throws IOException {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(os);
oos.writeObject(payload);
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException ignore) {
// empty catch block
}
}
}
}
public static Object deserialize(final String s) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new ByteArrayInputStream(s.getBytes("8859_1")));
return ois.readObject();
} catch (Exception e) {
logger.error("Cannot deserialize payload using " + (s == null ? -1 : s.length()) + " bytes", e);
throw new IllegalArgumentException("Cannot deserialize payload");
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException ignore) {
// empty catch block
}
}
}
}
/**
* Turn the payload into an xml jdom document
*
* @param d the payload
*/
public static Document toXml(final IBaseDataObject d) {
final Element root = new Element("payload");
root.addContent(JDOMUtil.protectedElement("name", d.getFilename()));
final Element cf = new Element("current-forms");
for (final String c : d.getAllCurrentForms()) {
cf.addContent(JDOMUtil.simpleElement("current-form", c));
}
root.addContent(cf);
root.addContent(JDOMUtil.simpleElement("encoding", d.getFontEncoding()));
root.addContent(JDOMUtil.simpleElement("filetype", d.getFileType()));
root.addContent(JDOMUtil.simpleElement("classification", d.getClassification()));
final Element th = new Element("transform-history");
for (final String s : d.transformHistory()) {
th.addContent(JDOMUtil.simpleElement("itinerary-step", s));
}
root.addContent(th);
if (d.getProcessingError() != null) {
root.addContent(JDOMUtil.simpleElement("processing-error", d.getProcessingError()));
}
final Element meta = new Element("metadata");
for (final String key : d.getParameters().keySet()) {
final Element m = JDOMUtil.protectedElement("param", d.getStringParameter(key));
m.setAttribute("name", key.toString());
meta.addContent(m);
}
root.addContent(meta);
if (d.header() != null) {
root.addContent(JDOMUtil.protectedElement("header", d.header()));
}
if (d.dataLength() > 0) {
root.addContent(JDOMUtil.protectedElement("data", d.data()));
}
if (d.footer() != null) {
root.addContent(JDOMUtil.protectedElement("footer", d.footer()));
}
// Alt views
if (d.getNumAlternateViews() > 0) {
final Element views = new Element("views");
for (final String av : d.getAlternateViewNames()) {
final Element v = JDOMUtil.protectedElement("view", d.getAlternateView(av));
v.setAttribute("name", av);
views.addContent(v);
}
root.addContent(views);
}
logger.debug("Produced xml document for " + d.shortName());
final Document doc = new Document(root);
return doc;
}
/**
* Turn the payload into an xml string
*
* @param d the payload
*/
public static String toXmlString(final IBaseDataObject d) {
return JDOMUtil.toString(toXml(d));
}
/**
* Turn a list of payload into an xml jdom ocument
*
* @param list the payload list
*/
public static Document toXml(final List<IBaseDataObject> list) {
final Element root = new Element("payload-list");
for (final IBaseDataObject d : list) {
final Document doc = toXml(d);
root.addContent(doc.detachRootElement());
logger.debug("Adding xml content for " + d.shortName() + " to document");
}
final Document doc = new Document(root);
return doc;
}
/**
* Turn the payload list into an xml string
*
* @param list the payload list
*/
public static String toXmlString(final List<IBaseDataObject> list) {
return JDOMUtil.toString(toXml(list));
}
/**
* Print formatted metadata key:value pairs
*/
private static final String SEP = ": ";
public static String printFormattedMetadata(final IBaseDataObject payload) {
final StringBuilder out = new StringBuilder();
out.append(LS);
for (final Map.Entry<String, Collection<Object>> entry : payload.getParameters().entrySet()) {
out.append(entry.getKey() + SEP + entry.getValue() + LS);
}
return out.toString();
}
/** This class is not meant to be instantiated. */
private PayloadUtil() {}
}