Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a0a4847b53e5d8391d51d95dd746d73d8b2432d5 (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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
 * Copyright (c) 2007-2013, 2015, 2016 Eike Stepper (Berlin, Germany) 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:
 *    Eike Stepper - initial API and implementation
 */
package org.eclipse.net4j.util.io;

import org.eclipse.net4j.internal.util.bundle.OM;
import org.eclipse.net4j.util.ObjectUtil;
import org.eclipse.net4j.util.StringUtil;
import org.eclipse.net4j.util.WrappedException;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * @author Eike Stepper
 */
public final class ExtendedIOUtil
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ExtendedIOUtil.class);

  private static final int UTF_HEADER_SIZE = 2;

  private static final int MAX_16_BIT = (1 << 16) - 1;

  private static final int MAX_UTF_LENGTH = MAX_16_BIT - UTF_HEADER_SIZE;

  private static final int MAX_UTF_CHARS = MAX_UTF_LENGTH / 3;

  private static final int MAX_ENUM_LITERALS = Byte.MAX_VALUE - Byte.MIN_VALUE;

  private static final byte NO_ENUM_LITERAL = Byte.MIN_VALUE;

  private static final int BYTE_BUFFER_SIZE = 8192;

  private static final int CHARACTER_BUFFER_SIZE = 4096;

  private static final byte[] EMPTY_BYTE_ARRAY = {};

  private ExtendedIOUtil()
  {
  }

  /**
   * @since 3.7
   */
  public static void writeVarInt(DataOutput out, int v) throws IOException
  {
    while ((v & ~0x7f) != 0)
    {
      out.writeByte((byte)(0x80 | v & 0x7f));
      v >>>= 7;
    }

    out.writeByte((byte)v);
  }

  /**
   * @since 3.7
   */
  public static int readVarInt(DataInput in) throws IOException
  {
    int b = in.readByte();
    if (b >= 0)
    {
      return b;
    }

    int v = b & 0x7f;
    b = in.readByte();
    if (b >= 0)
    {
      return v | b << 7;
    }

    v |= (b & 0x7f) << 7;
    b = in.readByte();
    if (b >= 0)
    {
      return v | b << 14;
    }

    v |= (b & 0x7f) << 14;
    b = in.readByte();
    if (b >= 0)
    {
      return v | b << 21;
    }

    v |= (b & 0x7f) << 21;
    b = in.readByte();
    return v | b << 28;
  }

  /**
   * @since 3.7
   */
  public static void writeVarLong(DataOutput out, long v) throws IOException
  {
    while ((v & ~0x7f) != 0)
    {
      out.writeByte((byte)(v & 0x7f | 0x80));
      v >>>= 7;
    }

    out.writeByte((byte)v);
  }

  /**
   * @since 3.7
   */
  public static long readVarLong(DataInput in) throws IOException
  {
    long v = in.readByte();
    if (v >= 0)
    {
      return v;
    }

    v &= 0x7f;
    for (int s = 7;; s += 7)
    {
      long b = in.readByte();
      v |= (b & 0x7f) << s;
      if (b >= 0)
      {
        return v;
      }
    }
  }

  public static void writeByteArray(DataOutput out, byte[] b) throws IOException
  {
    if (b != null)
    {
      out.writeInt(b.length);
      out.write(b);
    }
    else
    {
      out.writeInt(-1);
    }
  }

  public static byte[] readByteArray(DataInput in) throws IOException
  {
    int length = in.readInt();
    if (length < 0)
    {
      return null;
    }

    if (length == 0)
    {
      return EMPTY_BYTE_ARRAY;
    }

    byte[] b;
    try
    {
      b = new byte[length];
    }
    catch (Throwable t)
    {
      throw new IOException("Unable to allocate " + length + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    in.readFully(b);
    return b;
  }

  public static void writeObject(final DataOutput out, Object object) throws IOException
  {
    ObjectOutput objectOutput = null;
    if (out instanceof ObjectOutput)
    {
      objectOutput = (ObjectOutput)out;
    }
    else
    {
      ObjectOutputStream wrapper = new ObjectOutputStream(new OutputStream()
      {
        @Override
        public void write(int b) throws IOException
        {
          out.writeByte((b & 0xff) + Byte.MIN_VALUE);
        }
      });

      if (ObjectUtil.never())
      {
        // Suppress resource leak warning.
        wrapper.close();
      }

      objectOutput = wrapper;
    }

    objectOutput.writeObject(object);
  }

  public static Object readObject(final DataInput in) throws IOException
  {
    return readObject(in, (ClassResolver)null);
  }

  public static Object readObject(final DataInput in, ClassLoader classLoader) throws IOException
  {
    return readObject(in, new ClassLoaderClassResolver(classLoader));
  }

  public static Object readObject(final DataInput in, final ClassResolver classResolver) throws IOException
  {
    ObjectInput objectInput = null;
    if (in instanceof ObjectInput)
    {
      objectInput = (ObjectInput)in;
    }
    else
    {
      ObjectInputStream wrapper = new ObjectInputStream(new InputStream()
      {
        @Override
        public int read() throws IOException
        {
          return in.readByte() - Byte.MIN_VALUE;
        }
      })
      {
        @Override
        protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
        {
          if (classResolver != null)
          {
            if (TRACER.isEnabled())
            {
              TRACER.format("Deserializing class {0}", desc.getName()); //$NON-NLS-1$
            }

            Class<?> c = classResolver.resolveClass(desc);
            if (c != null)
            {
              return c;
            }
          }

          return super.resolveClass(desc);
        }
      };

      if (ObjectUtil.never())
      {
        // Suppress resource leak warning.
        wrapper.close();
      }

      objectInput = wrapper;
    }

    try
    {
      return objectInput.readObject();
    }
    catch (ClassNotFoundException ex)
    {
      throw WrappedException.wrap(ex);
    }
  }

  public static void writeString(DataOutput out, String str) throws IOException
  {
    if (str != null)
    {
      int size = str.length();
      int start = 0;

      do
      {
        out.writeBoolean(true);
        int chunk = Math.min(size, MAX_UTF_CHARS);
        int end = start + chunk;
        out.writeUTF(str.substring(start, end));
        start = end;
        size -= chunk;
      } while (size > 0);
    }

    out.writeBoolean(false);
  }

  public static String readString(DataInput in) throws IOException
  {
    boolean more = in.readBoolean();
    if (!more)
    {
      return null;
    }

    StringBuilder builder = new StringBuilder();

    do
    {
      String chunk = in.readUTF();
      builder.append(chunk);
      more = in.readBoolean();
    } while (more);

    return builder.toString();
  }

  /**
   * @since 3.3
   */
  public static long writeBinaryStream(DataOutput out, InputStream inputStream) throws IOException
  {
    long length = 0;
    byte[] buffer = new byte[BYTE_BUFFER_SIZE];

    for (;;)
    {
      int n = inputStream.read(buffer);
      if (n == IOUtil.EOF)
      {
        out.writeShort(0);
        break;
      }

      out.writeShort(n);
      out.write(buffer, 0, n);
      length += n;
    }

    return length;
  }

  /**
   * @since 3.3
   */
  public static long readBinaryStream(DataInput in, OutputStream outputStream) throws IOException
  {
    long length = 0;
    byte[] buffer = new byte[BYTE_BUFFER_SIZE];

    for (;;)
    {
      int n = in.readShort();
      if (n == 0)
      {
        break;
      }

      in.readFully(buffer, 0, n);
      outputStream.write(buffer, 0, n);
      length += n;
    }

    return length;
  }

  /**
   * @since 3.3
   */
  public static long writeCharacterStream(DataOutput out, Reader reader) throws IOException
  {
    long length = 0;
    char[] buffer = new char[CHARACTER_BUFFER_SIZE];

    for (;;)
    {
      int n = reader.read(buffer);
      if (n == IOUtil.EOF)
      {
        out.writeShort(0);
        break;
      }

      out.writeShort(n);
      for (int i = 0; i < n; i++)
      {
        out.writeChar(buffer[i]);
      }

      length += n;
    }

    return length;
  }

  /**
   * @since 3.3
   */
  public static long readCharacterStream(DataInput in, Writer writer) throws IOException
  {
    long length = 0;
    char[] buffer = new char[CHARACTER_BUFFER_SIZE];

    for (;;)
    {
      int n = in.readShort();
      if (n == 0)
      {
        break;
      }

      for (int i = 0; i < n; i++)
      {
        buffer[i] = in.readChar();
      }

      writer.write(buffer, 0, n);
      length += n;
    }

    return length;
  }

  /**
   * @since 3.0
   */
  public static void writeEnum(DataOutput out, Enum<?> literal) throws IOException
  {
    if (literal == null)
    {
      out.writeByte(NO_ENUM_LITERAL);
    }
    else
    {
      getEnumLiterals(literal.getDeclaringClass()); // Check valid size

      int ordinal = literal.ordinal();
      out.writeByte(ordinal + Byte.MIN_VALUE + 1);
    }
  }

  /**
   * @since 3.0
   */
  public static <T extends Enum<?>> T readEnum(DataInput in, Class<T> type) throws IOException
  {
    T[] literals = getEnumLiterals(type);

    int ordinal = in.readByte();
    if (ordinal == NO_ENUM_LITERAL)
    {
      return null;
    }

    return literals[ordinal - Byte.MIN_VALUE - 1];
  }

  /**
   * @since 3.4
   */
  public static void writeException(DataOutput out, Throwable t) throws IOException
  {
    String message = StringUtil.formatException(t);
    writeString(out, message);

    byte[] bytes = ExtendedIOUtil.serializeThrowable(t);
    writeByteArray(out, bytes);
  }

  /**
   * @since 3.4
   */
  public static Throwable readException(DataInput in) throws IOException
  {
    String message = readString(in);
    byte[] bytes = readByteArray(in);

    try
    {
      return ExtendedIOUtil.deserializeThrowable(bytes);
    }
    catch (Throwable couldNotLoadExceptionClass)
    {
      return new RuntimeException(message);
    }
  }

  /**
   * @since 3.4
   */
  public static byte[] serializeThrowable(Throwable t)
  {
    try
    {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(baos);
      writeObject(dos, t);
      return baos.toByteArray();
    }
    catch (Exception ex)
    {
      return null;
    }
  }

  /**
   * @since 3.4
   */
  public static Throwable deserializeThrowable(byte[] bytes)
  {
    try
    {
      ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
      DataInputStream dis = new DataInputStream(bais);
      return (Throwable)readObject(dis, OM.class.getClassLoader());
    }
    catch (IOException ex)
    {
      return null;
    }
  }

  private static <T> T[] getEnumLiterals(Class<T> type)
  {
    T[] literals = type.getEnumConstants();

    int size = literals.length;
    if (size > MAX_ENUM_LITERALS)
    {
      throw new AssertionError("Enum too large: " + size + " literals");
    }

    return literals;
  }

  /**
   * @author Eike Stepper
   */
  public interface ClassResolver
  {
    public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException;
  }

  /**
   * @author Eike Stepper
   */
  public static class ClassLoaderClassResolver implements ClassResolver
  {
    private static final String STACK_TRACE_ELEMENT = StackTraceElement[].class.getName();

    private ClassLoader classLoader;

    public ClassLoaderClassResolver(ClassLoader classLoader)
    {
      this.classLoader = classLoader;
    }

    public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException
    {
      String className = v.getName();

      try
      {
        return classLoader.loadClass(className);
      }
      catch (ClassNotFoundException ex)
      {
        if (!STACK_TRACE_ELEMENT.equals(className))
        {
          if (TRACER.isEnabled())
          {
            TRACER.trace("Exception in resolver", ex); //$NON-NLS-1$
          }
        }

        return null;
      }
    }
  }
}

Back to the top