Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 115e6f9efd0072cda900ab69ec9d33a6b4019dc7 (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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
/*
 * Copyright (c) 2007-2016, 2018, 2019 Eike Stepper (Loehne, 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
 *    Caspar De Groot - maintenance
 */
package org.eclipse.internal.net4j.buffer;

import org.eclipse.net4j.buffer.BufferState;
import org.eclipse.net4j.buffer.IBufferProvider;
import org.eclipse.net4j.util.HexUtil;
import org.eclipse.net4j.util.IErrorHandler;
import org.eclipse.net4j.util.StringUtil;
import org.eclipse.net4j.util.om.trace.ContextTracer;

import org.eclipse.internal.net4j.bundle.OM;

import org.eclipse.spi.net4j.InternalBuffer;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SocketChannel;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Eike Stepper
 * @since 4.0
 */
public class Buffer implements InternalBuffer
{
  private static final byte FLAG_EOS = 1 << 0;

  private static final byte FLAG_CCAM = 1 << 1;

  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_BUFFER, Buffer.class);

  private static AtomicInteger lastID = new AtomicInteger();

  private int id = lastID.incrementAndGet();

  private IErrorHandler errorHandler;

  private IBufferProvider bufferProvider;

  private ByteBuffer byteBuffer;

  private BufferState state = BufferState.INITIAL;

  private short channelID;

  private byte flags;

  public Buffer(IBufferProvider provider, short capacity)
  {
    bufferProvider = provider;
    byteBuffer = ByteBuffer.allocateDirect(capacity);
  }

  public final int getID()
  {
    return id;
  }

  @Override
  public boolean isEOS()
  {
    return (flags & FLAG_EOS) != 0;
  }

  @Override
  public void setEOS(boolean eos)
  {
    if (eos)
    {
      flags |= FLAG_EOS;
    }
    else
    {
      flags &= ~FLAG_EOS;
    }
  }

  @Override
  public boolean isCCAM()
  {
    return (flags & FLAG_CCAM) != 0;
  }

  @Override
  public void setCCAM(boolean ccam)
  {
    if (ccam)
    {
      flags |= FLAG_CCAM;
    }
    else
    {
      flags &= ~FLAG_CCAM;
    }
  }

  @Override
  public IBufferProvider getBufferProvider()
  {
    return bufferProvider;
  }

  @Override
  public void setBufferProvider(IBufferProvider bufferProvider)
  {
    this.bufferProvider = bufferProvider;
  }

  @Override
  public short getChannelID()
  {
    if (state == BufferState.INITIAL || state == BufferState.READING_HEADER)
    {
      throw new IllegalStateException(toString());
    }

    return channelID;
  }

  public void setChannelID(short channelID)
  {
    this.channelID = channelID;
  }

  @Override
  public short getCapacity()
  {
    return (short)byteBuffer.capacity();
  }

  @Override
  public BufferState getState()
  {
    return state;
  }

  public void setState(BufferState state)
  {
    this.state = state;
  }

  @Override
  public ByteBuffer getByteBuffer()
  {
    return byteBuffer;
  }

  public void setByteBuffer(ByteBuffer buffer)
  {
    byteBuffer = buffer;
  }

  @Override
  public void clear()
  {
    state = BufferState.INITIAL;
    channelID = NO_CHANNEL;
    flags = 0;
    byteBuffer.clear();
  }

  @Override
  public void release()
  {
    try
    {
      if (state != BufferState.RELEASED)
      {
        state = BufferState.RELEASED;
        errorHandler = null;

        if (bufferProvider != null)
        {
          bufferProvider.retainBuffer(this);
        }
      }
    }
    catch (Error ex)
    {
      // Don't swallow errors.
      throw ex;
    }
    catch (Exception ex)
    {
      // A normal exception can only occur if the buffer provider implementation is buggy.
      // Do not simply continue in this case because it's not known in which state this buffer is then.
      throw new Error("Implementation error in buffer provider " + bufferProvider, ex);
    }
  }

  @Override
  public void dispose()
  {
    state = BufferState.DISPOSED;
    bufferProvider = null;
    byteBuffer = null;
  }

  @Override
  public ByteBuffer startGetting(SocketChannel socketChannel) throws IOException
  {
    try
    {
      if (state != BufferState.INITIAL && state != BufferState.READING_HEADER && state != BufferState.READING_BODY)
      {
        throw new IllegalStateException(toString());
      }

      if (state == BufferState.INITIAL)
      {
        byteBuffer.limit(HEADER_SIZE);
        state = BufferState.READING_HEADER;
      }

      if (state == BufferState.READING_HEADER)
      {
        readChannel(socketChannel, byteBuffer);

        if (byteBuffer.hasRemaining())
        {
          // Limit is set to HEADER_SIZE.
          // Header is not fully received, yet.
          return null;
        }

        // Header is fully received.
        channelID = byteBuffer.getShort(CHANNEL_ID_POS);
        short payloadSize = byteBuffer.getShort(PAYLOAD_SIZE_POS);

        if (payloadSize == 0)
        {
          setEOS(true);
        }
        else if (payloadSize < 0)
        {
          setEOS(true);
          payloadSize = (short)-payloadSize;
        }

        try
        {
          byteBuffer.limit(HEADER_SIZE + payloadSize);
        }
        catch (IllegalArgumentException ex)
        {
          if (payloadSize < 0)
          {
            throw new IllegalArgumentException(toString() + ": New limit " + payloadSize + " is < 0" + (isEOS() ? " (EOS)" : ""), ex);
          }

          int capacity = byteBuffer.capacity();
          if (payloadSize > capacity)
          {
            throw new IllegalArgumentException(toString() + ": New limit " + payloadSize + " is > " + capacity + (isEOS() ? " (EOS)" : ""), ex);
          }

          throw new IllegalArgumentException(toString() + ": " + ex.getMessage(), ex);
        }

        state = BufferState.READING_BODY;
      }

      readChannel(socketChannel, byteBuffer);
      if (byteBuffer.hasRemaining())
      {
        return null;
      }

      if (TRACER.isEnabled())
      {
        TRACER.trace("Read " + byteBuffer.limit() + " bytes" //$NON-NLS-1$ //$NON-NLS-2$
            + (isEOS() ? " (EOS)" : "") + StringUtil.NL + formatContent(false)); //$NON-NLS-1$ //$NON-NLS-2$
      }

      byteBuffer.position(HEADER_SIZE);
      state = BufferState.GETTING;
      return byteBuffer;
    }
    catch (IOException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (RuntimeException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (Error ex)
    {
      handleError(ex);
      throw ex;
    }
  }

  @Override
  public ByteBuffer startPutting(short channelID)
  {
    try
    {
      if (state == BufferState.PUTTING)
      {
        if (channelID != this.channelID)
        {
          throw new IllegalArgumentException(toString() + ": channelID != this.channelID"); //$NON-NLS-1$
        }
      }
      else if (state != BufferState.INITIAL)
      {
        throw new IllegalStateException(toString());
      }
      else
      {
        state = BufferState.PUTTING;
        this.channelID = channelID;

        byteBuffer.clear();
        byteBuffer.position(HEADER_SIZE);
      }

      return byteBuffer;
    }
    catch (RuntimeException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (Error ex)
    {
      handleError(ex);
      throw ex;
    }
  }

  /**
   * @return <code>true</code> if the buffer has been completely written, <code>false</code> otherwise.
   */
  @Override
  public boolean write(SocketChannel socketChannel) throws IOException
  {
    try
    {
      if (state != BufferState.PUTTING && state != BufferState.WRITING)
      {
        throw new IllegalStateException(toString());
      }

      if (state == BufferState.PUTTING)
      {
        if (channelID == NO_CHANNEL)
        {
          throw new IllegalStateException(toString() + ": channelID == NO_CHANNEL"); //$NON-NLS-1$
        }

        int payloadSize = byteBuffer.position() - HEADER_SIZE;
        boolean eos = isEOS();
        if (eos)
        {
          payloadSize = -payloadSize;
        }

        if (TRACER.isEnabled())
        {
          TRACER.trace("Writing " + (Math.abs(payloadSize) - 1) + " bytes" //$NON-NLS-1$ //$NON-NLS-2$
              + (eos ? " (EOS)" : "") + StringUtil.NL + formatContent(false)); //$NON-NLS-1$ //$NON-NLS-2$
        }

        byteBuffer.flip();
        byteBuffer.putShort(channelID);
        byteBuffer.putShort((short)payloadSize);
        byteBuffer.position(0);
        state = BufferState.WRITING;
      }

      int numBytes = socketChannel.write(byteBuffer);
      if (numBytes == -1)
      {
        throw new IOException(toString() + ": Channel closed"); //$NON-NLS-1$
      }

      if (byteBuffer.hasRemaining())
      {
        return false;
      }

      clear();
      return true;
    }
    catch (IOException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (RuntimeException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (Error ex)
    {
      handleError(ex);
      throw ex;
    }
  }

  @Override
  public void flip()
  {
    try
    {
      if (state != BufferState.PUTTING)
      {
        throw new IllegalStateException(toString());
      }

      byteBuffer.flip();
      byteBuffer.position(HEADER_SIZE);
      state = BufferState.GETTING;
    }
    catch (RuntimeException ex)
    {
      handleError(ex);
      throw ex;
    }
    catch (Error ex)
    {
      handleError(ex);
      throw ex;
    }
  }

  @Override
  public void compact()
  {
    byteBuffer.compact();
  }

  @Override
  public int getPosition()
  {
    return byteBuffer.position();
  }

  @Override
  public void setPosition(int position)
  {
    byteBuffer.position(position);
  }

  @Override
  public int getLimit()
  {
    return byteBuffer.limit();
  }

  @Override
  public void setLimit(int limit)
  {
    byteBuffer.limit(limit);
  }

  @Override
  public boolean hasRemaining()
  {
    return byteBuffer.hasRemaining();
  }

  @Override
  public byte get()
  {
    return byteBuffer.get();
  }

  @Override
  public void get(byte[] dst)
  {
    byteBuffer.get(dst);
  }

  @Override
  public short getShort()
  {
    return byteBuffer.getShort();
  }

  @Override
  public int getInt()
  {
    return byteBuffer.getInt();
  }

  @Override
  public String getString()
  {
    return BufferUtil.getString(byteBuffer);
  }

  @Override
  public void put(byte b)
  {
    byteBuffer.put(b);
  }

  @Override
  public void put(byte[] src, int offset, int length)
  {
    byteBuffer.put(src, offset, length);
  }

  @Override
  public void putShort(short value)
  {
    byteBuffer.putShort(value);
  }

  @Override
  public String toString()
  {
    return MessageFormat.format("Buffer@{0}[{1}]", id, state); //$NON-NLS-1$
  }

  @Override
  @SuppressWarnings("deprecation")
  public String formatContent(boolean showHeader)
  {
    final int oldPosition = byteBuffer.position();
    final int oldLimit = byteBuffer.limit();

    try
    {
      if (state != BufferState.GETTING)
      {
        byteBuffer.flip();
      }

      if (state == BufferState.PUTTING && !showHeader)
      {
        byteBuffer.position(HEADER_SIZE);
      }

      StringBuilder builder = new StringBuilder();
      while (byteBuffer.hasRemaining())
      {
        byte b = byteBuffer.get();
        HexUtil.appendHex(builder, b < 0 ? ~b : b);
        builder.append(' ');
      }

      return builder.toString();
    }
    finally
    {
      byteBuffer.position(oldPosition);
      byteBuffer.limit(oldLimit);
    }
  }

  @Override
  public IErrorHandler getErrorHandler()
  {
    return errorHandler;
  }

  @Override
  public void setErrorHandler(IErrorHandler errorHandler)
  {
    this.errorHandler = errorHandler;
  }

  public void handleError(Throwable t)
  {
    try
    {
      if (errorHandler != null)
      {
        errorHandler.handleError(t);
      }
      else if (TRACER.isEnabled())
      {
        TRACER.trace(t);
      }
    }
    finally
    {
      release();
    }
  }

  private void readChannel(SocketChannel socketChannel, ByteBuffer byteBuffer) throws ClosedChannelException
  {
    try
    {
      int numBytes = socketChannel.read(byteBuffer);
      if (numBytes == -1)
      {
        throw new IOException(toString() + ": Channel has reached end-of-stream");
      }
    }
    catch (ClosedChannelException ex)
    {
      throw ex;
    }
    catch (IOException ex)
    {
      ClosedChannelException exception = new ClosedChannelException();
      exception.initCause(ex);
      throw exception;
    }
  }

  private static String formatHex(String hex)
  {
    StringBuilder builder = new StringBuilder();

    int length = hex.length();
    for (int i = 0; i < length; i++)
    {
      builder.append(hex.charAt(i));
      if (i % 2 == 1 && i < length - 1)
      {
        builder.append(' ');
      }
    }

    return builder.toString();
  }

  private static void decodeBuffer(String hex) throws IOException
  {
    System.out.println("Buffer: " + formatHex(hex));
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(HexUtil.hexToBytes(hex)));

    short channelID = in.readShort();

    boolean eos = false;
    short payloadSize = in.readShort();
    if (payloadSize < 0)
    {
      payloadSize = (short)-payloadSize;
      eos = true;
    }

    System.out.println("channelID:     " + channelID);
    System.out.println("payloadSize:   " + payloadSize);
    System.out.println("eos:           " + eos);

    String type = "request";
    int correlationID = in.readInt();
    if (correlationID < 0)
    {
      correlationID = -correlationID;
      type = "response";
    }
    else if (in.available() >= 2)
    {
      short signalID = in.readShort();
      System.out.println("signalID:      " + signalID);
    }

    System.out.println("correlationID: " + correlationID);
    System.out.println("type:          " + type);
    System.out.println();
  }

  public static String dump(ByteBuffer byteBuffer)
  {
    return dump(byteBuffer, false);
  }

  public static String dump(ByteBuffer byteBuffer, boolean fullCapacity)
  {
    final int position = byteBuffer.position();
    final int limit = byteBuffer.limit();

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < limit; i++)
    {
      dumpByte(byteBuffer, builder, i);
    }

    if (fullCapacity)
    {
      int capacity = byteBuffer.capacity();
      if (limit < capacity)
      {
        byteBuffer.limit(capacity);

        try
        {
          builder.append("\n--");
          for (int i = limit; i < capacity; i++)
          {
            dumpByte(byteBuffer, builder, i);
          }
        }
        finally
        {
          byteBuffer.limit(limit);
        }
      }
    }

    return "pos\u00A0" + position + "/" + limit + ":" + builder;
  }

  private static void dumpByte(ByteBuffer byteBuffer, StringBuilder builder, int i)
  {
    int b = byteBuffer.get(i) & 0xFF; // Dump unsigned int instead of signed byte.
    builder.append('\u00A0'); // NO-BREAK SPACE. A bug in JDT's detail formatter hates normal spaces.
    builder.append(b);
  }

  public static void main(String[] args) throws Exception
  {
    decodeBuffer("0001ffea0000026b001a0000000101ff000000000000058d00");
    decodeBuffer("0001fffafffffd9500");
    decodeBuffer("0001ffea00000064001a0000000101ff000000000000040c00");
    decodeBuffer("0001fffaffffff9c00");
  }
}

Back to the top