Skip to main content
summaryrefslogtreecommitdiffstats
blob: 3ebeb8cbac7388c28cec7e78d66007a3bd5231db (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
/*******************************************************************************
 * Copyright (c) 2004, 2007 Boeing.
 * 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:
 *     Boeing - initial API and implementation
 *******************************************************************************/
package org.eclipse.osee.ote.message.data;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.logging.Level;

import org.eclipse.osee.framework.logging.OseeLog;
import org.eclipse.osee.ote.core.CopyOnWriteNoIteratorList;
import org.eclipse.osee.ote.core.GCHelper;
import org.eclipse.osee.ote.core.log.Env;
import org.eclipse.osee.ote.message.IMessageDisposeListener;
import org.eclipse.osee.ote.message.IMessageHeader;
import org.eclipse.osee.ote.message.IMessageSendListener;
import org.eclipse.osee.ote.message.Message;
import org.eclipse.osee.ote.message.MessageSystemException;
import org.eclipse.osee.ote.message.MessageSystemTestEnvironment;
import org.eclipse.osee.ote.message.enums.DataType;
import org.eclipse.osee.ote.message.interfaces.Namespace;
import org.eclipse.osee.ote.messaging.dds.Data;
import org.eclipse.osee.ote.messaging.dds.DataSample;
import org.eclipse.osee.ote.messaging.dds.IDestination;
import org.eclipse.osee.ote.messaging.dds.ISource;
import org.eclipse.osee.ote.messaging.dds.ReturnCode;
import org.eclipse.osee.ote.messaging.dds.entity.DataReader;
import org.eclipse.osee.ote.messaging.dds.entity.DataWriter;
import org.eclipse.osee.ote.messaging.dds.listener.DataReaderListener;
import org.eclipse.osee.ote.messaging.dds.listener.DataWriterListener;
import org.eclipse.osee.ote.messaging.dds.service.Key;
import org.eclipse.osee.ote.messaging.dds.service.TypeSupport;
import org.eclipse.osee.ote.messaging.dds.status.LivelinessChangedStatus;
import org.eclipse.osee.ote.messaging.dds.status.LivelinessLostStatus;
import org.eclipse.osee.ote.messaging.dds.status.OfferedDeadlineMissedStatus;
import org.eclipse.osee.ote.messaging.dds.status.OfferedIncompatibleQosStatus;
import org.eclipse.osee.ote.messaging.dds.status.PublicationMatchStatus;
import org.eclipse.osee.ote.messaging.dds.status.RequestedDeadlineMissedStatus;
import org.eclipse.osee.ote.messaging.dds.status.RequestedIncompatibleQosStatus;
import org.eclipse.osee.ote.messaging.dds.status.SampleLostStatus;
import org.eclipse.osee.ote.messaging.dds.status.SampleRejectedStatus;
import org.eclipse.osee.ote.messaging.dds.status.SubscriptionMatchStatus;
import org.eclipse.osee.ote.properties.OtePropertiesCore;

/**
 * @author Andrew M. Finkbeiner
 */
public abstract class MessageData implements DataReaderListener, DataWriterListener, Data, Key {

   private static long debugTimeout = OtePropertiesCore.timeDebugTimeout.getLongValue();
   private static boolean debugTime = OtePropertiesCore.timeDebug.getBooleanValue();

   private DataWriter writer;
   private DataReader reader;
   private DataSample myDataSample;

   private final MemoryResource mem;
   private final String typeName;
   private final String name;
   private final CopyOnWriteNoIteratorList<Message> messages = new CopyOnWriteNoIteratorList<Message>(Message.class);
   private final CopyOnWriteNoIteratorList<IMessageSendListener> messageSendListeners = new CopyOnWriteNoIteratorList<IMessageSendListener>(IMessageSendListener.class);
   private final int defaultDataByteSize;
   private final DataType memType;
   private final boolean isEnabled = true;
   private long activityCount = 0;
   private long sentCount;
   private int currentLength;
   private boolean isScheduled = false;
   private long time = -1;

   public MessageData(String typeName, String name, int dataByteSize, int offset, DataType memType) {
      mem = new MemoryResource(new byte[dataByteSize], offset, dataByteSize - offset);
      myDataSample = new DataSample(this);
      this.typeName = typeName;
      this.name = name;
      this.defaultDataByteSize = dataByteSize;
      this.currentLength = dataByteSize;
      this.memType = memType;
   }

   public MessageData(String typeName, String name, MemoryResource mem, DataType memType) {
      this.mem = mem;
      myDataSample = new DataSample(this);
      this.typeName = typeName;
      this.name = name;
      this.defaultDataByteSize = mem.getLength();
      this.currentLength = mem.getLength();
      this.memType = memType;
      GCHelper.getGCHelper().addRefWatch(this);
   }

   public MessageData(String name, int dataByteSize, int offset, DataType memType) {
      this(name, name, dataByteSize, offset, memType);
   }

   public MessageData(byte[] data, int dataByteSize, int offset) {
      this.mem = new MemoryResource(data, offset, dataByteSize - offset);
      this.typeName = "";
      this.name = "";
      this.defaultDataByteSize = dataByteSize;
      this.currentLength = dataByteSize;
      this.memType = null;
      GCHelper.getGCHelper().addRefWatch(this);
   }

   public MessageData(MemoryResource memoryResource) {
      this("", memoryResource);
   }

   public MessageData(String name, MemoryResource memoryResource) {
      this.mem = memoryResource;
      this.typeName = "";
      this.name = name;
      this.defaultDataByteSize = memoryResource.getLength();
      this.currentLength = memoryResource.getLength();
      this.memType = null;
      GCHelper.getGCHelper().addRefWatch(this);
   }

   public abstract IMessageHeader getMsgHeader();

   public DataType getType() {
      return memType;
   }

   /**
    * Returns the number of byte words in the payload of this message.
    * 
    * @return the number of bytes in the message payload
    */
   public int getPayloadSize() {
      return currentLength;
   }

   public String getName() {
      return name;
   }

   /**
    * adds a {@link Message} who are mapped to this data object
    */
   public void addMessage(Message message) {
      if (!messages.contains(message)) {
         messages.add(message);
         message.addPreMessageDisposeListener(disposeListener);
      }
   }

   /**
    * returns a list of the message that this data is a source for. <BR>
    * 
    * @return a collection of messages
    */
   public Collection<Message> getMessages() {
      return messages.fillCollection(new ArrayList<Message>());
      //      return new ArrayList<Message>(messages);
   }

   /**
    * @return Returns the activityCount.
    */
   public long getActivityCount() {
      return activityCount;
   }

   /**
    * @param activityCount The activityCount to set.
    */
   public void setActivityCount(long activityCount) {
      this.activityCount = activityCount;
   }

   public void incrementActivityCount() {
      activityCount++;
   }

   public void incrementSentCount() {
      sentCount++;
   }

   public long getSentCount() {
      return sentCount;
   }

   public boolean isEnabled() {
      return isEnabled;
   }

   public abstract void visit(IMessageDataVisitor visitor);

   public void dispose() {

      try{
         Message[] msgs = messages.get();
         for (int i = 0; i < msgs.length; i++){
            Message local = msgs[i];
            if(local != null){
               local.removePreMessageDisposeListener(disposeListener);
            }
         }
      } catch (Throwable th){
         OseeLog.log(getClass(), Level.SEVERE, "failed to remove message dispose listener.", th);
      }
      messages.clear();
      if (writer != null) {
         writer.getPublisher().deleteDataWriter(writer);
         writer.dispose(this, null);
         writer = null;
      } else if (reader != null && reader.getSubscriber() != null) {
         reader.getSubscriber().deleteDataReader(reader);
         reader.dispose();
         reader = null;
      }
      disposeListener = null;
   }

   public void copyData(int destOffset, byte[] data, int srcOffset, int length) {
      setCurrentLength(length + destOffset);
      mem.copyData(destOffset, data, srcOffset, length);
   }

   public void copyData(int destOffset, ByteBuffer data, int length) throws MessageSystemException {
      try {
         setCurrentLength(destOffset + length);
         mem.copyData(destOffset, data, length);
      } catch (MessageSystemException ex) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.INFO, ex,
               "increasing backing store for %s to %d. prev length: %d, recv cnt: %d", getName(), destOffset + length,
               mem.getData().length, this.activityCount);
         setNewBackingBuffer(data, destOffset, length);
      }
   }

   public void copyData(ByteBuffer data) {
      copyData(0, data, data.remaining());
   }

   /**
    * Notifies all {@link Message}s that have this registered as a data source of the update
    */
   public void notifyListeners() throws MessageSystemException {
      final DataType memType = getType();
      Message[] ref = messages.get();
      for (int i = 0; i < ref.length; i++) {
         Message message = ref[i];
         try {
            if (!message.isDestroyed()) {
               message.notifyListeners(this, memType);
            }
         } catch (Throwable t) {
            final String msg =
                  String.format("Problem during listener notification for message %s. Data=%s, MemType=%s",
                        message.getName(), this.getName(), this.getType());
            OseeLog.log(MessageSystemTestEnvironment.class, Level.SEVERE, msg, t);
         }
      }
   }

   /**
    * @return the currentLength
    */
   public int getCurrentLength() {
      return currentLength;
   }

   /**
    * @param currentLength the currentLength to set
    */
   public void setCurrentLength(int currentLength) {
      this.currentLength = currentLength;
   }

   /**
    * Override this method if you need to set some default data in the backing buffer.
    */
   public void setNewBackingBuffer(byte[] data) {
      setCurrentLength(data.length);
      this.mem.setData(data);
      if (this.getMsgHeader() != null) {
         initializeDefaultHeaderValues();
      } else {
         // System.out.println("what??-- bad HeaderData");
      }

   }

   public void setNewBackingBuffer(ByteBuffer buffer) {
      byte[] data = new byte[buffer.remaining()];
      buffer.get(data);
      this.mem.setData(data);
      setCurrentLength(data.length);
      if (this.getMsgHeader() != null) {
         initializeDefaultHeaderValues();
      } else {
         // System.out.println("what??-- bad HeaderData");
      }
   }

   public void setNewBackingBuffer(ByteBuffer buffer, int offset, int length) {
      byte[] data = new byte[offset + length];
      buffer.get(data, offset, length);
      this.mem.setData(data);
      setCurrentLength(data.length);
      if (this.getMsgHeader() != null) {
         initializeDefaultHeaderValues();
      } else {
         // System.out.println("what??-- bad HeaderData");
      }

   }

   public abstract void initializeDefaultHeaderValues();

   /**
    * @return the mem
    */
   public MemoryResource getMem() {
      return mem;
   }

   public int getDefaultDataByteSize() {
      return defaultDataByteSize;
   }

   @Override
   public synchronized void onDataAvailable(DataReader theReader) {
      // System.out.println(String.format("data available %s %s", this.getName(),
      // this.getNamespace()));
      if (isEnabled()) {
         ReturnCode val = theReader.takeNextSample(myDataSample);
         if (val == ReturnCode.OK) {
            incrementActivityCount();
            notifyListeners();
         } else {
            Env.getInstance().severe(val.getDescription());
         }
      }
   }

   @Override
   public void onLivelinessChanged(DataReader theReader, LivelinessChangedStatus status) {
   }

   @Override
   public void onRequestedDeadlineMissed(DataReader theReader, RequestedDeadlineMissedStatus status) {
   }

   @Override
   public void onRequestedIncompatibleQos(DataReader theReader, RequestedIncompatibleQosStatus status) {
   }

   @Override
   public void onSampleLost(DataReader theReader, SampleLostStatus status) {
   }

   @Override
   public void onSampleRejected(DataReader theReader, SampleRejectedStatus status) {
   }

   @Override
   public void onSubscriptionMatch(DataReader theReader, SubscriptionMatchStatus status) {
   }

   @Override
   public synchronized void onDataSentToMiddleware(DataWriter theWriter) {
      // header.setSequenceNumber(header.getSequenceNumber() + 1);
      notifyListeners();
   }

   @Override
   public void onLivelinessLost(DataWriter theWriter, LivelinessLostStatus status) {
   }

   @Override
   public void onOfferedDeadlineMissed(DataWriter theWriter, OfferedDeadlineMissedStatus status) {
   }

   @Override
   public void onOfferedIncompatibleQos(DataWriter theWriter, OfferedIncompatibleQosStatus status) {
   }

   @Override
   public void onPublicationMatch(DataWriter theWriter, PublicationMatchStatus status) {
   }

   @Override
   public Object getKeyValue() {
      return null;
   }

   @Override
   public void setFromByteArray(byte[] input) {
      try {
         copyData(0, input, 0, input.length);
      } catch (MessageSystemException ex) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.WARNING,

               "Copy Failed: setting new backing buffer.  msg[%s], oldSize[%d] newSize[%d]", this.getName(),
               this.mem.getData().length, input.length);
         setNewBackingBuffer(input);
      }
   }

   @Override
   public void setFromByteBuffer(ByteBuffer buffer) {
      try {
         copyData(buffer);
      } catch (Exception e) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.SEVERE,
               "Copy Failed: setting new backing buffer.  msg[%s], oldSize[%d] newSize[%d]", this.getName(),
               this.mem.getData().length, buffer.limit());
         setNewBackingBuffer(buffer);
      }
   }

   @Override
   public ByteBuffer toByteBuffer() {
      return mem.getAsBuffer();
   }

   public void setFromByteArray(byte[] input, int length) {
      try {
         copyData(0, input, 0, length);
      } catch (MessageSystemException ex) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.SEVERE,
               "Copy Failed: setting new backing buffer.  msg[%s], oldSize[%d] newSize[%d]", this.getName(),
               this.mem.getData().length, length);
         setNewBackingBuffer(input);
      }
   }

   public void setFromByteArray(int destOffset, byte[] input, int srcOffset, int length) {
      try {
         copyData(destOffset, input, srcOffset, length);
      } catch (MessageSystemException ex) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.SEVERE,
               "Copy Failed: setting new backing buffer.  msg[%s], oldSize[%d] newSize[%d]", this.getName(),
               this.mem.getData().length, length);
         setNewBackingBuffer(input);
      }
   }

   public void setFromByteArray(ByteBuffer input, int length) {
      try {
         copyData(0, input, length);
      } catch (MessageSystemException ex) {
         OseeLog.logf(MessageSystemTestEnvironment.class, Level.SEVERE,
               "Copy Failed: setting new backing buffer.  msg[%s], oldSize[%d] newSize[%d]", this.getName(),
               this.mem.getData().length, length);
         setNewBackingBuffer(input);
      }
   }

   @Override
   public byte[] toByteArray() {
      return mem.getData();
   }

   public void setReader(DataReader reader) {
      this.reader = reader;
   }

   public void setWriter(DataWriter writer) {
      this.writer = writer;
   }

   public void send() throws MessageSystemException {
      if (writer == null) {
         OseeLog.log(MessageSystemTestEnvironment.class, Level.SEVERE, getName() + " - the writer is null");
      } else if (shouldSendData()) {
         try {
            notifyPreSendListeners();
            long start = 0, elapsed;
            if(debugTime){
               start = System.nanoTime();
            }
            getMem().setDataHasChanged(false);
            writer.write(null, null, this, null);
            incrementSentCount();
            if(debugTime){
               elapsed = System.nanoTime() - start;
               if(elapsed > debugTimeout){
                  Locale.setDefault(Locale.US);
                  System.out.printf("%s SLOW IOSEND %,d\n", getName(), elapsed);
               }
            }
            notifyPostSendListeners();
         } catch (Throwable ex) {
            throw new MessageSystemException("Could not send message data " + getName(), Level.SEVERE, ex);
         }
      }
   }

   protected void sendTo(IDestination destination, ISource source) throws MessageSystemException {
      if (writer == null) {
         OseeLog.log(MessageSystemTestEnvironment.class, Level.WARNING, getName() + " - the writer is null");
      } else if (shouldSendData()) {
         try {
            notifyPreSendListeners();
            // this.initializeDefaultHeaderValues();
            getMem().setDataHasChanged(false);
            writer.write(destination, source, this, null);
            incrementSentCount();
            notifyPostSendListeners();
         } catch (Throwable ex) {
            throw new MessageSystemException("Could not send message data " + getName(), Level.SEVERE, ex);
         }
      }
   }

   /**
    * Override this method if you want to specialize the send criteria in a data source. For example, if you only want
    * to send data to the MUX driver if the data has changed.
    */
   protected boolean shouldSendData() {
      return true;
   }

   public TypeSupport getTypeSupport() {
      return new DDSTypeSupport(this, getName(), getName(), getPayloadSize());
   }

   public String getTopicName() {
      return getName();
   }

   public String getTypeName() {
      return typeName;
   }

   @Override
   public boolean isSameInstance(byte[] data1, byte[] data2) {
      return true;
   }

   public Namespace getNamespace() {
      if (isWriter()) {
         return new Namespace(writer.getTopic().getNamespace());
      } else {
         return new Namespace(reader.getTopicDescription().getNamespace());
      }
   }

   /*
    * each type that extends DDSData needs to have it's own namespace.... we need to go through each DDSData child and
    * determine all of it's possible namespaces
    */
   public boolean isWriter() {
      if (writer != null && reader == null) {
         return true;
      } else if (writer == null && reader != null) {
         return false;
      } else {
         throw new MessageSystemException(
               "This is an illegal message it has neither a reader or a writer [" + this.getName() + "].", Level.SEVERE);
      }
   }

   private IMessageDisposeListener disposeListener = new IMessageDisposeListener() {

      @Override
      public void onPreDispose(Message message) {
         messages.remove(message);
      }

      @Override
      public void onPostDispose(Message message) {
      }

   };

   @Override
   public void copyFrom(Data data) {
      ByteBuffer buffer = data.toByteBuffer();
      copyData(data.getOffset(), buffer, buffer.remaining());
   }

   @Override
   public String toString() {
      return getClass().getName() + ": name=" + getName();
   }

   @Override
   public int getOffset() {
      return 0;
   }

   /**
    * @return the isScheduled
    */
   public boolean isScheduled() {
      return isScheduled;
   }

   /**
    * @param isScheduled the isScheduled to set
    */
   public void setScheduled(boolean isScheduled) {
      this.isScheduled = isScheduled;
   }

   private void notifyPostSendListeners() {
      try {
         long start = 0, elapsed;
         IMessageSendListener[] listeners = messageSendListeners.get();
         for (int i = 0; i < listeners.length; i++) {
            IMessageSendListener listener = listeners[i];
            if(debugTime){
               start = System.nanoTime();
            }
            listener.onPostSend(this);
            if(debugTime){
               elapsed = System.nanoTime() - start;
               if(elapsed > debugTimeout){
                  Locale.setDefault(Locale.US);
                  System.out.printf("%s %s SLOW POST SEND %,d\n", getName(), listener.getClass().getName(), elapsed);
               }
            }
         }
      } catch (Exception ex) {
         OseeLog.log(Message.class, Level.SEVERE, ex);
      }
   }

   private void notifyPreSendListeners() {
      try {
         long start = 0, elapsed;
         IMessageSendListener[] listeners = messageSendListeners.get();
         for (int i = 0; i < listeners.length; i++) {
            IMessageSendListener listener = listeners[i];
            if(debugTime){
               start = System.nanoTime();
            }
            listener.onPreSend(this);
            if(debugTime){
               elapsed = System.nanoTime() - start;
               if(elapsed > debugTimeout){
                  Locale.setDefault(Locale.US);
                  System.out.printf("%s %s SLOW PRE SEND %,d\n", getName(), listener.getClass().getName(), elapsed);
               }
            }
         }
      } catch (Exception ex) {
         OseeLog.log(Message.class, Level.SEVERE, ex);
      }
   }

   public void addSendListener(IMessageSendListener listener) {
      messageSendListeners.add(listener);
   }

   public void removeSendListener(IMessageSendListener listener) {
      messageSendListeners.remove(listener);
   }

   public boolean containsSendListener(IMessageSendListener listener) {
      return messageSendListeners.contains(listener);
   }

   public boolean isMessageCollectionNotEmpty() {
      return messages.get().length > 0;
   }

   public void zeroize() {
      final byte[] data = toByteArray();
      Arrays.fill(data, getMsgHeader().getHeaderSize(), data.length, (byte) 0);
   }

   /**
    * A time value associated with this message.
    * The time value will have different meanings or may not be used depending on the context and usage.
    */
   public long getTime() {
      return time;
   }

   public void setTime(long time) {
      this.time = time;
   }
}

Back to the top