001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import org.apache.hbase.thirdparty.com.google.common.base.Throwables;
021
022import java.io.IOException;
023import java.util.ArrayDeque;
024import java.util.Queue;
025
026import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
027
028/**
029 * A scan result consumer which buffers all the data in memory and you can call the {@link #take()}
030 * method below to get the result one by one. Should only be used by tests, do not write production
031 * code like this as the buffer is unlimited and may cause OOM.
032 */
033class BufferingScanResultConsumer implements AdvancedScanResultConsumer {
034
035  private ScanMetrics scanMetrics;
036
037  private final Queue<Result> queue = new ArrayDeque<>();
038
039  private boolean finished;
040
041  private Throwable error;
042
043  @Override
044  public void onScanMetricsCreated(ScanMetrics scanMetrics) {
045    this.scanMetrics = scanMetrics;
046  }
047
048  @Override
049  public synchronized void onNext(Result[] results, ScanController controller) {
050    for (Result result : results) {
051      queue.offer(result);
052    }
053    notifyAll();
054  }
055
056  @Override
057  public synchronized void onError(Throwable error) {
058    finished = true;
059    this.error = error;
060    notifyAll();
061  }
062
063  @Override
064  public synchronized void onComplete() {
065    finished = true;
066    notifyAll();
067  }
068
069  public synchronized Result take() throws IOException, InterruptedException {
070    for (;;) {
071      if (!queue.isEmpty()) {
072        return queue.poll();
073      }
074      if (finished) {
075        if (error != null) {
076          Throwables.propagateIfPossible(error, IOException.class);
077          throw new IOException(error);
078        } else {
079          return null;
080        }
081      }
082      wait();
083    }
084  }
085
086  public ScanMetrics getScanMetrics() {
087    return scanMetrics;
088  }
089}