• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017, OpenCensus Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package io.opencensus.testing.export;
18 
19 import io.opencensus.trace.export.SpanData;
20 import io.opencensus.trace.export.SpanExporter;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.LinkedList;
24 import java.util.List;
25 import javax.annotation.Nullable;
26 import javax.annotation.concurrent.GuardedBy;
27 
28 /**
29  * A {@link SpanExporter.Handler} for testing only.
30  *
31  * @since 0.9
32  */
33 public final class TestHandler extends SpanExporter.Handler {
34 
35   private final Object monitor = new Object();
36 
37   // TODO: Decide whether to use a different class instead of LinkedList.
38   @GuardedBy("monitor")
39   @SuppressWarnings("JdkObsolete")
40   private final List<SpanData> spanDataList = new LinkedList<SpanData>();
41 
42   @Override
export(Collection<SpanData> spanDataList)43   public void export(Collection<SpanData> spanDataList) {
44     synchronized (monitor) {
45       this.spanDataList.addAll(spanDataList);
46       monitor.notifyAll();
47     }
48   }
49 
50   /**
51    * Waits until we received numberOfSpans spans to export. Returns the list of exported {@link
52    * SpanData} objects, otherwise {@code null} if the current thread is interrupted.
53    *
54    * @param numberOfSpans the number of minimum spans to be collected.
55    * @return the list of exported {@link SpanData} objects, otherwise {@code null} if the current
56    *     thread is interrupted.
57    * @since 0.9
58    */
59   @Nullable
waitForExport(int numberOfSpans)60   public List<SpanData> waitForExport(int numberOfSpans) {
61     List<SpanData> ret;
62     synchronized (monitor) {
63       while (spanDataList.size() < numberOfSpans) {
64         try {
65           monitor.wait();
66         } catch (InterruptedException e) {
67           // Preserve the interruption status as per guidance.
68           Thread.currentThread().interrupt();
69           return null;
70         }
71       }
72       ret = new ArrayList<SpanData>(spanDataList);
73       spanDataList.clear();
74     }
75     return ret;
76   }
77 }
78