• 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.List;
24 import javax.annotation.Nullable;
25 import javax.annotation.concurrent.GuardedBy;
26 
27 /**
28  * A {@link SpanExporter.Handler} for testing only.
29  *
30  * @since 0.9
31  */
32 public final class TestHandler extends SpanExporter.Handler {
33 
34   private final Object monitor = new Object();
35 
36   @GuardedBy("monitor")
37   private final List<SpanData> spanDataList = new ArrayList<>();
38 
39   @Override
export(Collection<SpanData> spanDataList)40   public void export(Collection<SpanData> spanDataList) {
41     synchronized (monitor) {
42       this.spanDataList.addAll(spanDataList);
43       monitor.notifyAll();
44     }
45   }
46 
47   /**
48    * Waits until we received numberOfSpans spans to export. Returns the list of exported {@link
49    * SpanData} objects, otherwise {@code null} if the current thread is interrupted.
50    *
51    * @param numberOfSpans the number of minimum spans to be collected.
52    * @return the list of exported {@link SpanData} objects, otherwise {@code null} if the current
53    *     thread is interrupted.
54    * @since 0.9
55    */
56   @Nullable
waitForExport(int numberOfSpans)57   public List<SpanData> waitForExport(int numberOfSpans) {
58     List<SpanData> ret;
59     synchronized (monitor) {
60       while (spanDataList.size() < numberOfSpans) {
61         try {
62           monitor.wait();
63         } catch (InterruptedException e) {
64           // Preserve the interruption status as per guidance.
65           Thread.currentThread().interrupt();
66           return null;
67         }
68       }
69       ret = new ArrayList<>(spanDataList);
70       spanDataList.clear();
71     }
72     return ret;
73   }
74 }
75