View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.client;
20  
21  import com.google.common.annotations.VisibleForTesting;
22  import com.google.protobuf.Descriptors;
23  import com.google.protobuf.Message;
24  import com.google.protobuf.Service;
25  import com.google.protobuf.ServiceException;
26  
27  import java.io.IOException;
28  import java.io.InterruptedIOException;
29  import java.util.ArrayList;
30  import java.util.Collections;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.NavigableMap;
34  import java.util.TreeMap;
35  import java.util.concurrent.Callable;
36  import java.util.concurrent.ExecutionException;
37  import java.util.concurrent.ExecutorService;
38  import java.util.concurrent.Future;
39  import java.util.concurrent.SynchronousQueue;
40  import java.util.concurrent.ThreadPoolExecutor;
41  import java.util.concurrent.TimeUnit;
42  
43  import org.apache.commons.logging.Log;
44  import org.apache.commons.logging.LogFactory;
45  import org.apache.hadoop.conf.Configuration;
46  import org.apache.hadoop.hbase.Cell;
47  import org.apache.hadoop.hbase.DoNotRetryIOException;
48  import org.apache.hadoop.hbase.HBaseConfiguration;
49  import org.apache.hadoop.hbase.HConstants;
50  import org.apache.hadoop.hbase.HRegionInfo;
51  import org.apache.hadoop.hbase.HRegionLocation;
52  import org.apache.hadoop.hbase.HTableDescriptor;
53  import org.apache.hadoop.hbase.KeyValueUtil;
54  import org.apache.hadoop.hbase.ServerName;
55  import org.apache.hadoop.hbase.TableName;
56  import org.apache.hadoop.hbase.classification.InterfaceAudience;
57  import org.apache.hadoop.hbase.classification.InterfaceStability;
58  import org.apache.hadoop.hbase.client.AsyncProcess.AsyncRequestFuture;
59  import org.apache.hadoop.hbase.client.coprocessor.Batch;
60  import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
61  import org.apache.hadoop.hbase.filter.BinaryComparator;
62  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
63  import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
64  import org.apache.hadoop.hbase.ipc.HBaseRpcController;
65  import org.apache.hadoop.hbase.ipc.RegionCoprocessorRpcChannel;
66  import org.apache.hadoop.hbase.ipc.RpcControllerFactory;
67  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
68  import org.apache.hadoop.hbase.protobuf.RequestConverter;
69  import org.apache.hadoop.hbase.protobuf.ResponseConverter;
70  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
71  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
72  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateRequest;
73  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateResponse;
74  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionAction;
75  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.CompareType;
76  import org.apache.hadoop.hbase.util.Bytes;
77  import org.apache.hadoop.hbase.util.Pair;
78  import org.apache.hadoop.hbase.util.ReflectionUtils;
79  import org.apache.hadoop.hbase.util.Threads;
80  
81  /**
82   * An implementation of {@link Table}. Used to communicate with a single HBase table.
83   * Lightweight. Get as needed and just close when done.
84   * Instances of this class SHOULD NOT be constructed directly.
85   * Obtain an instance via {@link Connection}. See {@link ConnectionFactory}
86   * class comment for an example of how.
87   *
88   * <p>This class is NOT thread safe for reads nor writes.
89   * In the case of writes (Put, Delete), the underlying write buffer can
90   * be corrupted if multiple threads contend over a single HTable instance.
91   * In the case of reads, some fields used by a Scan are shared among all threads.
92   *
93   * <p>HTable is no longer a client API. Use {@link Table} instead. It is marked
94   * InterfaceAudience.Private as of hbase-1.0.0 indicating that this is an
95   * HBase-internal class as defined in
96   * <a href="https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/InterfaceClassification.html">Hadoop
97   * Interface Classification</a>. There are no guarantees for backwards
98   * source / binary compatibility and methods or the class can
99   * change or go away without deprecation.
100  * <p>Near all methods of this * class made it out to the new {@link Table}
101  * Interface or were * instantiations of methods defined in {@link HTableInterface}.
102  * A few did not. Namely, the {@link #getStartEndKeys}, {@link #getEndKeys},
103  * and {@link #getStartKeys} methods. These three methods are available
104  * in {@link RegionLocator} as of 1.0.0 but were NOT marked as
105  * deprecated when we released 1.0.0. In spite of this oversight on our
106  * part, these methods will be removed in 2.0.0.
107  *
108  * @see Table
109  * @see Admin
110  * @see Connection
111  * @see ConnectionFactory
112  */
113 @InterfaceAudience.Private
114 @InterfaceStability.Stable
115 public class HTable implements HTableInterface, RegionLocator {
116   private static final Log LOG = LogFactory.getLog(HTable.class);
117   protected ClusterConnection connection;
118   private final TableName tableName;
119   private volatile Configuration configuration;
120   private ConnectionConfiguration connConfiguration;
121   protected BufferedMutatorImpl mutator;
122   private boolean autoFlush = true;
123   private boolean closed = false;
124   protected int scannerCaching;
125   protected long scannerMaxResultSize;
126   private ExecutorService pool;  // For Multi & Scan
127   private int operationTimeout; // global timeout for each blocking method with retrying rpc
128   private int readRpcTimeout; // timeout for each read rpc request
129   private int writeRpcTimeout; // timeout for each write rpc request
130   private final boolean cleanupPoolOnClose; // shutdown the pool in close()
131   private final boolean cleanupConnectionOnClose; // close the connection in close()
132   private Consistency defaultConsistency = Consistency.STRONG;
133   private HRegionLocator locator;
134 
135   /** The Async process for batch */
136   protected AsyncProcess multiAp;
137   private RpcRetryingCallerFactory rpcCallerFactory;
138   private RpcControllerFactory rpcControllerFactory;
139 
140   /**
141    * Creates an object to access a HBase table.
142    * @param conf Configuration object to use.
143    * @param tableName Name of the table.
144    * @throws IOException if a remote or network exception occurs
145    * @deprecated Constructing HTable objects manually has been deprecated. Please use
146    * {@link Connection} to instantiate a {@link Table} instead.
147    */
148   @Deprecated
149   public HTable(Configuration conf, final String tableName)
150   throws IOException {
151     this(conf, TableName.valueOf(tableName));
152   }
153 
154   /**
155    * Creates an object to access a HBase table.
156    * @param conf Configuration object to use.
157    * @param tableName Name of the table.
158    * @throws IOException if a remote or network exception occurs
159    * @deprecated Constructing HTable objects manually has been deprecated. Please use
160    * {@link Connection} to instantiate a {@link Table} instead.
161    */
162   @Deprecated
163   public HTable(Configuration conf, final byte[] tableName)
164   throws IOException {
165     this(conf, TableName.valueOf(tableName));
166   }
167 
168   /**
169    * Creates an object to access a HBase table.
170    * @param conf Configuration object to use.
171    * @param tableName table name pojo
172    * @throws IOException if a remote or network exception occurs
173    * @deprecated Constructing HTable objects manually has been deprecated. Please use
174    * {@link Connection} to instantiate a {@link Table} instead.
175    */
176   @Deprecated
177   public HTable(Configuration conf, final TableName tableName)
178   throws IOException {
179     this.tableName = tableName;
180     this.cleanupPoolOnClose = this.cleanupConnectionOnClose = true;
181     if (conf == null) {
182       this.connection = null;
183       return;
184     }
185     this.connection = ConnectionManager.getConnectionInternal(conf);
186     this.configuration = conf;
187 
188     this.pool = getDefaultExecutor(conf);
189     this.finishSetup();
190   }
191 
192   /**
193    * Creates an object to access a HBase table.
194    * @param tableName Name of the table.
195    * @param connection HConnection to be used.
196    * @throws IOException if a remote or network exception occurs
197    * @deprecated Do not use.
198    */
199   @Deprecated
200   public HTable(TableName tableName, Connection connection) throws IOException {
201     this.tableName = tableName;
202     this.cleanupPoolOnClose = true;
203     this.cleanupConnectionOnClose = false;
204     this.connection = (ClusterConnection)connection;
205     this.configuration = connection.getConfiguration();
206 
207     this.pool = getDefaultExecutor(this.configuration);
208     this.finishSetup();
209   }
210 
211   // Marked Private @since 1.0
212   @InterfaceAudience.Private
213   public static ThreadPoolExecutor getDefaultExecutor(Configuration conf) {
214     int maxThreads = conf.getInt("hbase.htable.threads.max", Integer.MAX_VALUE);
215     if (maxThreads == 0) {
216       maxThreads = 1; // is there a better default?
217     }
218     long keepAliveTime = conf.getLong("hbase.htable.threads.keepalivetime", 60);
219 
220     // Using the "direct handoff" approach, new threads will only be created
221     // if it is necessary and will grow unbounded. This could be bad but in HCM
222     // we only create as many Runnables as there are region servers. It means
223     // it also scales when new region servers are added.
224     ThreadPoolExecutor pool = new ThreadPoolExecutor(1, maxThreads, keepAliveTime, TimeUnit.SECONDS,
225         new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("htable"));
226     pool.allowCoreThreadTimeOut(true);
227     return pool;
228   }
229 
230   /**
231    * Creates an object to access a HBase table.
232    * @param conf Configuration object to use.
233    * @param tableName Name of the table.
234    * @param pool ExecutorService to be used.
235    * @throws IOException if a remote or network exception occurs
236    * @deprecated Constructing HTable objects manually has been deprecated. Please use
237    * {@link Connection} to instantiate a {@link Table} instead.
238    */
239   @Deprecated
240   public HTable(Configuration conf, final byte[] tableName, final ExecutorService pool)
241       throws IOException {
242     this(conf, TableName.valueOf(tableName), pool);
243   }
244 
245   /**
246    * Creates an object to access a HBase table.
247    * @param conf Configuration object to use.
248    * @param tableName Name of the table.
249    * @param pool ExecutorService to be used.
250    * @throws IOException if a remote or network exception occurs
251    * @deprecated Constructing HTable objects manually has been deprecated. Please use
252    * {@link Connection} to instantiate a {@link Table} instead.
253    */
254   @Deprecated
255   public HTable(Configuration conf, final TableName tableName, final ExecutorService pool)
256       throws IOException {
257     this.connection = ConnectionManager.getConnectionInternal(conf);
258     this.configuration = conf;
259     this.pool = pool;
260     if (pool == null) {
261       this.pool = getDefaultExecutor(conf);
262       this.cleanupPoolOnClose = true;
263     } else {
264       this.cleanupPoolOnClose = false;
265     }
266     this.tableName = tableName;
267     this.cleanupConnectionOnClose = true;
268     this.finishSetup();
269   }
270 
271   /**
272    * Creates an object to access a HBase table.
273    * @param tableName Name of the table.
274    * @param connection HConnection to be used.
275    * @param pool ExecutorService to be used.
276    * @throws IOException if a remote or network exception occurs.
277    * @deprecated Do not use, internal ctor.
278    */
279   @Deprecated
280   public HTable(final byte[] tableName, final Connection connection,
281       final ExecutorService pool) throws IOException {
282     this(TableName.valueOf(tableName), connection, pool);
283   }
284 
285   /** @deprecated Do not use, internal ctor. */
286   @Deprecated
287   public HTable(TableName tableName, final Connection connection,
288       final ExecutorService pool) throws IOException {
289     this(tableName, (ClusterConnection)connection, null, null, null, pool);
290   }
291 
292   /**
293    * Creates an object to access a HBase table.
294    * Used by HBase internally.  DO NOT USE. See {@link ConnectionFactory} class comment for how to
295    * get a {@link Table} instance (use {@link Table} instead of {@link HTable}).
296    * @param tableName Name of the table.
297    * @param connection HConnection to be used.
298    * @param pool ExecutorService to be used.
299    * @throws IOException if a remote or network exception occurs
300    */
301   @InterfaceAudience.Private
302   public HTable(TableName tableName, final ClusterConnection connection,
303       final ConnectionConfiguration tableConfig,
304       final RpcRetryingCallerFactory rpcCallerFactory,
305       final RpcControllerFactory rpcControllerFactory,
306       final ExecutorService pool) throws IOException {
307     if (connection == null || connection.isClosed()) {
308       throw new IllegalArgumentException("Connection is null or closed.");
309     }
310     if (tableName == null) {
311       throw new IllegalArgumentException("Given table name is null");
312     }
313     this.tableName = tableName;
314     this.cleanupConnectionOnClose = false;
315     this.connection = connection;
316     this.configuration = connection.getConfiguration();
317     this.connConfiguration = tableConfig;
318     this.pool = pool;
319     if (pool == null) {
320       this.pool = getDefaultExecutor(this.configuration);
321       this.cleanupPoolOnClose = true;
322     } else {
323       this.cleanupPoolOnClose = false;
324     }
325 
326     this.rpcCallerFactory = rpcCallerFactory;
327     this.rpcControllerFactory = rpcControllerFactory;
328 
329     this.finishSetup();
330   }
331 
332   /**
333    * For internal testing. Uses Connection provided in {@code params}.
334    * @throws IOException
335    */
336   @VisibleForTesting
337   protected HTable(ClusterConnection conn, BufferedMutatorParams params) throws IOException {
338     connection = conn;
339     tableName = params.getTableName();
340     connConfiguration = new ConnectionConfiguration(connection.getConfiguration());
341     cleanupPoolOnClose = false;
342     cleanupConnectionOnClose = false;
343     // used from tests, don't trust the connection is real
344     this.mutator = new BufferedMutatorImpl(conn, null, null, params);
345     this.readRpcTimeout = conn.getConfiguration().getInt(HConstants.HBASE_RPC_READ_TIMEOUT_KEY,
346         conn.getConfiguration().getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
347             HConstants.DEFAULT_HBASE_RPC_TIMEOUT));
348     this.writeRpcTimeout = conn.getConfiguration().getInt(HConstants.HBASE_RPC_WRITE_TIMEOUT_KEY,
349         conn.getConfiguration().getInt(HConstants.HBASE_RPC_TIMEOUT_KEY,
350             HConstants.DEFAULT_HBASE_RPC_TIMEOUT));
351   }
352 
353   /**
354    * @return maxKeyValueSize from configuration.
355    */
356   public static int getMaxKeyValueSize(Configuration conf) {
357     return conf.getInt("hbase.client.keyvalue.maxsize", -1);
358   }
359 
360   /**
361    * setup this HTable's parameter based on the passed configuration
362    */
363   private void finishSetup() throws IOException {
364     if (connConfiguration == null) {
365       connConfiguration = new ConnectionConfiguration(configuration);
366     }
367     this.operationTimeout = tableName.isSystemTable() ?
368         connConfiguration.getMetaOperationTimeout() : connConfiguration.getOperationTimeout();
369     this.readRpcTimeout = connConfiguration.getReadRpcTimeout();
370     this.writeRpcTimeout = connConfiguration.getWriteRpcTimeout();
371     this.scannerCaching = connConfiguration.getScannerCaching();
372     this.scannerMaxResultSize = connConfiguration.getScannerMaxResultSize();
373     if (this.rpcCallerFactory == null) {
374       this.rpcCallerFactory = connection.getNewRpcRetryingCallerFactory(configuration);
375     }
376     if (this.rpcControllerFactory == null) {
377       this.rpcControllerFactory = RpcControllerFactory.instantiate(configuration);
378     }
379 
380     // puts need to track errors globally due to how the APIs currently work.
381     multiAp = this.connection.getAsyncProcess();
382 
383     this.closed = false;
384 
385     this.locator = new HRegionLocator(tableName, connection);
386   }
387 
388   /**
389    * {@inheritDoc}
390    */
391   @Override
392   public Configuration getConfiguration() {
393     return configuration;
394   }
395 
396   /**
397    * Tells whether or not a table is enabled or not. This method creates a
398    * new HBase configuration, so it might make your unit tests fail due to
399    * incorrect ZK client port.
400    * @param tableName Name of table to check.
401    * @return {@code true} if table is online.
402    * @throws IOException if a remote or network exception occurs
403    * @deprecated use {@link HBaseAdmin#isTableEnabled(byte[])}
404    */
405   @Deprecated
406   public static boolean isTableEnabled(String tableName) throws IOException {
407     return isTableEnabled(TableName.valueOf(tableName));
408   }
409 
410   /**
411    * Tells whether or not a table is enabled or not. This method creates a
412    * new HBase configuration, so it might make your unit tests fail due to
413    * incorrect ZK client port.
414    * @param tableName Name of table to check.
415    * @return {@code true} if table is online.
416    * @throws IOException if a remote or network exception occurs
417    * @deprecated use {@link HBaseAdmin#isTableEnabled(byte[])}
418    */
419   @Deprecated
420   public static boolean isTableEnabled(byte[] tableName) throws IOException {
421     return isTableEnabled(TableName.valueOf(tableName));
422   }
423 
424   /**
425    * Tells whether or not a table is enabled or not. This method creates a
426    * new HBase configuration, so it might make your unit tests fail due to
427    * incorrect ZK client port.
428    * @param tableName Name of table to check.
429    * @return {@code true} if table is online.
430    * @throws IOException if a remote or network exception occurs
431    * @deprecated use {@link HBaseAdmin#isTableEnabled(byte[])}
432    */
433   @Deprecated
434   public static boolean isTableEnabled(TableName tableName) throws IOException {
435     return isTableEnabled(HBaseConfiguration.create(), tableName);
436   }
437 
438   /**
439    * Tells whether or not a table is enabled or not.
440    * @param conf The Configuration object to use.
441    * @param tableName Name of table to check.
442    * @return {@code true} if table is online.
443    * @throws IOException if a remote or network exception occurs
444    * @deprecated use {@link HBaseAdmin#isTableEnabled(byte[])}
445    */
446   @Deprecated
447   public static boolean isTableEnabled(Configuration conf, String tableName)
448   throws IOException {
449     return isTableEnabled(conf, TableName.valueOf(tableName));
450   }
451 
452   /**
453    * Tells whether or not a table is enabled or not.
454    * @param conf The Configuration object to use.
455    * @param tableName Name of table to check.
456    * @return {@code true} if table is online.
457    * @throws IOException if a remote or network exception occurs
458    * @deprecated use {@link HBaseAdmin#isTableEnabled(byte[])}
459    */
460   @Deprecated
461   public static boolean isTableEnabled(Configuration conf, byte[] tableName)
462   throws IOException {
463     return isTableEnabled(conf, TableName.valueOf(tableName));
464   }
465 
466   /**
467    * Tells whether or not a table is enabled or not.
468    * @param conf The Configuration object to use.
469    * @param tableName Name of table to check.
470    * @return {@code true} if table is online.
471    * @throws IOException if a remote or network exception occurs
472    * @deprecated use {@link HBaseAdmin#isTableEnabled(org.apache.hadoop.hbase.TableName tableName)}
473    */
474   @Deprecated
475   public static boolean isTableEnabled(Configuration conf,
476       final TableName tableName) throws IOException {
477     return HConnectionManager.execute(new HConnectable<Boolean>(conf) {
478       @Override
479       public Boolean connect(HConnection connection) throws IOException {
480         return connection.isTableEnabled(tableName);
481       }
482     });
483   }
484 
485   /**
486    * Find region location hosting passed row using cached info
487    * @param row Row to find.
488    * @return The location of the given row.
489    * @throws IOException if a remote or network exception occurs
490    * @deprecated Use {@link RegionLocator#getRegionLocation(byte[])}
491    */
492   @Deprecated
493   public HRegionLocation getRegionLocation(final String row)
494   throws IOException {
495     return getRegionLocation(Bytes.toBytes(row), false);
496   }
497 
498   /**
499    * @deprecated Use {@link RegionLocator#getRegionLocation(byte[])} instead.
500    */
501   @Override
502   @Deprecated
503   public HRegionLocation getRegionLocation(final byte [] row)
504   throws IOException {
505     return locator.getRegionLocation(row);
506   }
507 
508   /**
509    * @deprecated Use {@link RegionLocator#getRegionLocation(byte[], boolean)} instead.
510    */
511   @Override
512   @Deprecated
513   public HRegionLocation getRegionLocation(final byte [] row, boolean reload)
514   throws IOException {
515     return locator.getRegionLocation(row, reload);
516   }
517 
518   /**
519    * {@inheritDoc}
520    */
521   @Override
522   public byte [] getTableName() {
523     return this.tableName.getName();
524   }
525 
526   @Override
527   public TableName getName() {
528     return tableName;
529   }
530 
531   /**
532    * <em>INTERNAL</em> Used by unit tests and tools to do low-level
533    * manipulations.
534    * @return An HConnection instance.
535    * @deprecated This method will be changed from public to package protected.
536    */
537   // TODO(tsuna): Remove this.  Unit tests shouldn't require public helpers.
538   @Deprecated
539   @VisibleForTesting
540   public HConnection getConnection() {
541     return this.connection;
542   }
543 
544   /**
545    * Gets the number of rows that a scanner will fetch at once.
546    * <p>
547    * The default value comes from {@code hbase.client.scanner.caching}.
548    * @deprecated Use {@link Scan#setCaching(int)} and {@link Scan#getCaching()}
549    */
550   @Deprecated
551   public int getScannerCaching() {
552     return scannerCaching;
553   }
554 
555   /**
556    * Kept in 0.96 for backward compatibility
557    * @deprecated  since 0.96. This is an internal buffer that should not be read nor write.
558    */
559   @Deprecated
560   public List<Row> getWriteBuffer() {
561     return mutator == null ? null : mutator.getWriteBuffer();
562   }
563 
564   /**
565    * Sets the number of rows that a scanner will fetch at once.
566    * <p>
567    * This will override the value specified by
568    * {@code hbase.client.scanner.caching}.
569    * Increasing this value will reduce the amount of work needed each time
570    * {@code next()} is called on a scanner, at the expense of memory use
571    * (since more rows will need to be maintained in memory by the scanners).
572    * @param scannerCaching the number of rows a scanner will fetch at once.
573    * @deprecated Use {@link Scan#setCaching(int)}
574    */
575   @Deprecated
576   public void setScannerCaching(int scannerCaching) {
577     this.scannerCaching = scannerCaching;
578   }
579 
580   /**
581    * {@inheritDoc}
582    */
583   @Override
584   public HTableDescriptor getTableDescriptor() throws IOException {
585     HTableDescriptor htd = HBaseAdmin.getTableDescriptor(tableName, connection, rpcCallerFactory,
586       rpcControllerFactory, operationTimeout, readRpcTimeout);
587     if (htd != null) {
588       return new UnmodifyableHTableDescriptor(htd);
589     }
590     return null;
591   }
592 
593   /**
594    * To be removed in 2.0.0.
595    * @deprecated Since 1.1.0. Use {@link RegionLocator#getStartEndKeys()} instead
596    */
597   @Override
598   @Deprecated
599   public byte [][] getStartKeys() throws IOException {
600     return locator.getStartKeys();
601   }
602 
603   /**
604    * To be removed in 2.0.0.
605    * @deprecated Since 1.1.0. Use {@link RegionLocator#getEndKeys()} instead;
606    */
607   @Override
608   @Deprecated
609   public byte[][] getEndKeys() throws IOException {
610     return locator.getEndKeys();
611   }
612 
613   /**
614    * To be removed in 2.0.0.
615    * @deprecated Since 1.1.0. Use {@link RegionLocator#getStartEndKeys()} instead;
616    */
617   @Override
618   @Deprecated
619   public Pair<byte[][],byte[][]> getStartEndKeys() throws IOException {
620     return locator.getStartEndKeys();
621   }
622 
623   /**
624    * Gets all the regions and their address for this table.
625    * <p>
626    * This is mainly useful for the MapReduce integration.
627    * @return A map of HRegionInfo with it's server address
628    * @throws IOException if a remote or network exception occurs
629    * @deprecated This is no longer a public API.  Use {@link #getAllRegionLocations()} instead.
630    */
631   @Deprecated
632   public NavigableMap<HRegionInfo, ServerName> getRegionLocations() throws IOException {
633     // TODO: Odd that this returns a Map of HRI to SN whereas getRegionLocator, singular, returns an HRegionLocation.
634     return MetaScanner.allTableRegions(this.connection, getName());
635   }
636 
637   /**
638    * Gets all the regions and their address for this table.
639    * <p>
640    * This is mainly useful for the MapReduce integration.
641    * @return A map of HRegionInfo with it's server address
642    * @throws IOException if a remote or network exception occurs
643    *
644    * @deprecated Use {@link RegionLocator#getAllRegionLocations()} instead;
645    */
646   @Override
647   @Deprecated
648   public List<HRegionLocation> getAllRegionLocations() throws IOException {
649     return locator.getAllRegionLocations();
650   }
651 
652   /**
653    * Get the corresponding regions for an arbitrary range of keys.
654    * <p>
655    * @param startKey Starting row in range, inclusive
656    * @param endKey Ending row in range, exclusive
657    * @return A list of HRegionLocations corresponding to the regions that
658    * contain the specified range
659    * @throws IOException if a remote or network exception occurs
660    * @deprecated This is no longer a public API
661    */
662   @Deprecated
663   public List<HRegionLocation> getRegionsInRange(final byte [] startKey,
664     final byte [] endKey) throws IOException {
665     return getRegionsInRange(startKey, endKey, false);
666   }
667 
668   /**
669    * Get the corresponding regions for an arbitrary range of keys.
670    * <p>
671    * @param startKey Starting row in range, inclusive
672    * @param endKey Ending row in range, exclusive
673    * @param reload true to reload information or false to use cached information
674    * @return A list of HRegionLocations corresponding to the regions that
675    * contain the specified range
676    * @throws IOException if a remote or network exception occurs
677    * @deprecated This is no longer a public API
678    */
679   @Deprecated
680   public List<HRegionLocation> getRegionsInRange(final byte [] startKey,
681       final byte [] endKey, final boolean reload) throws IOException {
682     return getKeysAndRegionsInRange(startKey, endKey, false, reload).getSecond();
683   }
684 
685   /**
686    * Get the corresponding start keys and regions for an arbitrary range of
687    * keys.
688    * <p>
689    * @param startKey Starting row in range, inclusive
690    * @param endKey Ending row in range
691    * @param includeEndKey true if endRow is inclusive, false if exclusive
692    * @return A pair of list of start keys and list of HRegionLocations that
693    *         contain the specified range
694    * @throws IOException if a remote or network exception occurs
695    * @deprecated This is no longer a public API
696    */
697   @Deprecated
698   private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
699       final byte[] startKey, final byte[] endKey, final boolean includeEndKey)
700       throws IOException {
701     return getKeysAndRegionsInRange(startKey, endKey, includeEndKey, false);
702   }
703 
704   /**
705    * Get the corresponding start keys and regions for an arbitrary range of
706    * keys.
707    * <p>
708    * @param startKey Starting row in range, inclusive
709    * @param endKey Ending row in range
710    * @param includeEndKey true if endRow is inclusive, false if exclusive
711    * @param reload true to reload information or false to use cached information
712    * @return A pair of list of start keys and list of HRegionLocations that
713    *         contain the specified range
714    * @throws IOException if a remote or network exception occurs
715    * @deprecated This is no longer a public API
716    */
717   @Deprecated
718   private Pair<List<byte[]>, List<HRegionLocation>> getKeysAndRegionsInRange(
719       final byte[] startKey, final byte[] endKey, final boolean includeEndKey,
720       final boolean reload) throws IOException {
721     final boolean endKeyIsEndOfTable = Bytes.equals(endKey,HConstants.EMPTY_END_ROW);
722     if ((Bytes.compareTo(startKey, endKey) > 0) && !endKeyIsEndOfTable) {
723       throw new IllegalArgumentException(
724         "Invalid range: " + Bytes.toStringBinary(startKey) +
725         " > " + Bytes.toStringBinary(endKey));
726     }
727     List<byte[]> keysInRange = new ArrayList<byte[]>();
728     List<HRegionLocation> regionsInRange = new ArrayList<HRegionLocation>();
729     byte[] currentKey = startKey;
730     do {
731       HRegionLocation regionLocation = getRegionLocation(currentKey, reload);
732       keysInRange.add(currentKey);
733       regionsInRange.add(regionLocation);
734       currentKey = regionLocation.getRegionInfo().getEndKey();
735     } while (!Bytes.equals(currentKey, HConstants.EMPTY_END_ROW)
736         && (endKeyIsEndOfTable || Bytes.compareTo(currentKey, endKey) < 0
737             || (includeEndKey && Bytes.compareTo(currentKey, endKey) == 0)));
738     return new Pair<List<byte[]>, List<HRegionLocation>>(keysInRange,
739         regionsInRange);
740   }
741 
742   /**
743    * {@inheritDoc}
744    * @deprecated Use reversed scan instead.
745    */
746    @Override
747    @Deprecated
748    public Result getRowOrBefore(final byte[] row, final byte[] family)
749        throws IOException {
750      RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
751          tableName, row) {
752        @Override
753       public Result call(int callTimeout) throws IOException {
754          HBaseRpcController controller = rpcControllerFactory.newController();
755          controller.setPriority(tableName);
756          controller.setCallTimeout(callTimeout);
757          ClientProtos.GetRequest request = RequestConverter.buildGetRowOrBeforeRequest(
758              getLocation().getRegionInfo().getRegionName(), row, family);
759          try {
760            ClientProtos.GetResponse response = getStub().get(controller, request);
761            if (!response.hasResult()) return null;
762            return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
763          } catch (ServiceException se) {
764            throw ProtobufUtil.getRemoteException(se);
765          }
766        }
767      };
768      return rpcCallerFactory.<Result>newCaller(readRpcTimeout).callWithRetries(callable,
769          this.operationTimeout);
770    }
771 
772   /**
773    * The underlying {@link HTable} must not be closed.
774    * {@link HTableInterface#getScanner(Scan)} has other usage details.
775    */
776   @Override
777   public ResultScanner getScanner(Scan scan) throws IOException {
778     if (scan.getCaching() <= 0) {
779       scan.setCaching(getScannerCaching());
780     }
781     if (scan.getMaxResultSize() <= 0) {
782       scan.setMaxResultSize(scannerMaxResultSize);
783     }
784     if (scan.getMvccReadPoint() > 0) {
785       // it is not supposed to be set by user, clear
786       scan.resetMvccReadPoint();
787     }
788 
789     if (scan.isReversed()) {
790       return new ReversedClientScanner(getConfiguration(), scan, getName(),
791         this.connection, this.rpcCallerFactory, this.rpcControllerFactory,
792         pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
793     } else {
794       return new ClientSimpleScanner(getConfiguration(), scan, getName(), this.connection,
795           this.rpcCallerFactory, this.rpcControllerFactory,
796           pool, connConfiguration.getReplicaCallTimeoutMicroSecondScan());
797     }
798   }
799 
800   /**
801    * The underlying {@link HTable} must not be closed.
802    * {@link HTableInterface#getScanner(byte[])} has other usage details.
803    */
804   @Override
805   public ResultScanner getScanner(byte [] family) throws IOException {
806     Scan scan = new Scan();
807     scan.addFamily(family);
808     return getScanner(scan);
809   }
810 
811   /**
812    * The underlying {@link HTable} must not be closed.
813    * {@link HTableInterface#getScanner(byte[], byte[])} has other usage details.
814    */
815   @Override
816   public ResultScanner getScanner(byte [] family, byte [] qualifier)
817   throws IOException {
818     Scan scan = new Scan();
819     scan.addColumn(family, qualifier);
820     return getScanner(scan);
821   }
822 
823   /**
824    * {@inheritDoc}
825    */
826   @Override
827   public Result get(final Get get) throws IOException {
828     return get(get, get.isCheckExistenceOnly());
829   }
830 
831   private Result get(Get get, final boolean checkExistenceOnly) throws IOException {
832     // if we are changing settings to the get, clone it.
833     if (get.isCheckExistenceOnly() != checkExistenceOnly || get.getConsistency() == null) {
834       get = ReflectionUtils.newInstance(get.getClass(), get);
835       get.setCheckExistenceOnly(checkExistenceOnly);
836       if (get.getConsistency() == null){
837         get.setConsistency(defaultConsistency);
838       }
839     }
840 
841     if (get.getConsistency() == Consistency.STRONG) {
842       // Good old call.
843       final Get getReq = get;
844       RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
845           getName(), get.getRow(), get.getPriority()) {
846         @Override
847         public Result call(int callTimeout) throws IOException {
848           ClientProtos.GetRequest request =
849             RequestConverter.buildGetRequest(getLocation().getRegionInfo().getRegionName(), getReq);
850           HBaseRpcController controller = rpcControllerFactory.newController();
851           controller.setPriority(tableName);
852           controller.setPriority(getPriority());
853           controller.setCallTimeout(callTimeout);
854           try {
855             ClientProtos.GetResponse response = getStub().get(controller, request);
856             if (response == null) return null;
857             return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
858           } catch (ServiceException se) {
859             throw ProtobufUtil.getRemoteException(se);
860           }
861         }
862       };
863       return rpcCallerFactory.<Result>newCaller(readRpcTimeout).callWithRetries(callable,
864           this.operationTimeout);
865     }
866 
867     // Call that takes into account the replica
868     RpcRetryingCallerWithReadReplicas callable = new RpcRetryingCallerWithReadReplicas(
869       rpcControllerFactory, tableName, this.connection, get, pool,
870       connConfiguration.getRetriesNumber(),
871       operationTimeout,
872       connConfiguration.getPrimaryCallTimeoutMicroSecond());
873     return callable.call(operationTimeout);
874   }
875 
876 
877   /**
878    * {@inheritDoc}
879    */
880   @Override
881   public Result[] get(List<Get> gets) throws IOException {
882     if (gets.size() == 1) {
883       return new Result[]{get(gets.get(0))};
884     }
885     try {
886       Object[] r1 = new Object[gets.size()];
887       batch((List<? extends Row>)gets, r1, readRpcTimeout);
888       // translate.
889       Result [] results = new Result[r1.length];
890       int i=0;
891       for (Object o : r1) {
892         // batch ensures if there is a failure we get an exception instead
893         results[i++] = (Result) o;
894       }
895 
896       return results;
897     } catch (InterruptedException e) {
898       throw (InterruptedIOException)new InterruptedIOException().initCause(e);
899     }
900   }
901 
902   public void batch(final List<? extends Row> actions, final Object[] results, int rpcTimeout)
903       throws InterruptedException, IOException {
904     AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, actions, null, results, null,
905         operationTimeout, rpcTimeout);
906     ars.waitUntilDone();
907     if (ars.hasError()) {
908       throw ars.getErrors();
909     }
910   }
911 
912   /**
913    * {@inheritDoc}
914    */
915   @Override
916   public void batch(final List<? extends Row> actions, final Object[] results)
917       throws InterruptedException, IOException {
918     AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, actions, null, results);
919     ars.waitUntilDone();
920     if (ars.hasError()) {
921       throw ars.getErrors();
922     }
923   }
924 
925   /**
926    * {@inheritDoc}
927    * @deprecated If any exception is thrown by one of the actions, there is no way to
928    * retrieve the partially executed results. Use {@link #batch(List, Object[])} instead.
929    */
930   @Deprecated
931   @Override
932   public Object[] batch(final List<? extends Row> actions)
933      throws InterruptedException, IOException {
934     Object[] results = new Object[actions.size()];
935     batch(actions, results);
936     return results;
937   }
938 
939   /**
940    * {@inheritDoc}
941    */
942   @Override
943   public <R> void batchCallback(
944       final List<? extends Row> actions, final Object[] results, final Batch.Callback<R> callback)
945       throws IOException, InterruptedException {
946     connection.processBatchCallback(actions, tableName, pool, results, callback);
947   }
948 
949   /**
950    * {@inheritDoc}
951    * @deprecated If any exception is thrown by one of the actions, there is no way to
952    * retrieve the partially executed results. Use
953    * {@link #batchCallback(List, Object[], org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)}
954    * instead.
955    */
956   @Deprecated
957   @Override
958   public <R> Object[] batchCallback(
959     final List<? extends Row> actions, final Batch.Callback<R> callback) throws IOException,
960       InterruptedException {
961     Object[] results = new Object[actions.size()];
962     batchCallback(actions, results, callback);
963     return results;
964   }
965 
966   /**
967    * {@inheritDoc}
968    */
969   @Override
970   public void delete(final Delete delete)
971   throws IOException {
972     RegionServerCallable<Boolean> callable = new RegionServerCallable<Boolean>(connection,
973         tableName, delete.getRow(), delete.getPriority()) {
974       @Override
975       public Boolean call(int callTimeout) throws IOException {
976         HBaseRpcController controller = rpcControllerFactory.newController();
977         controller.setPriority(tableName);
978         controller.setPriority(getPriority());
979         controller.setCallTimeout(callTimeout);
980 
981         try {
982           MutateRequest request = RequestConverter.buildMutateRequest(
983             getLocation().getRegionInfo().getRegionName(), delete);
984           MutateResponse response = getStub().mutate(controller, request);
985           return Boolean.valueOf(response.getProcessed());
986         } catch (ServiceException se) {
987           throw ProtobufUtil.getRemoteException(se);
988         }
989       }
990     };
991     rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
992         this.operationTimeout);
993   }
994 
995   /**
996    * {@inheritDoc}
997    */
998   @Override
999   public void delete(final List<Delete> deletes)
1000   throws IOException {
1001     Object[] results = new Object[deletes.size()];
1002     try {
1003       batch(deletes, results, writeRpcTimeout);
1004     } catch (InterruptedException e) {
1005       throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1006     } finally {
1007       // mutate list so that it is empty for complete success, or contains only failed records
1008       // results are returned in the same order as the requests in list
1009       // walk the list backwards, so we can remove from list without impacting the indexes of earlier members
1010       for (int i = results.length - 1; i>=0; i--) {
1011         // if result is not null, it succeeded
1012         if (results[i] instanceof Result) {
1013           deletes.remove(i);
1014         }
1015       }
1016     }
1017   }
1018 
1019   /**
1020    * {@inheritDoc}
1021    * @throws IOException
1022    */
1023   @Override
1024   public void put(final Put put) throws IOException {
1025     getBufferedMutator().mutate(put);
1026     if (autoFlush) {
1027       flushCommits();
1028     }
1029   }
1030 
1031   /**
1032    * {@inheritDoc}
1033    * @throws IOException
1034    */
1035   @Override
1036   public void put(final List<Put> puts) throws IOException {
1037     getBufferedMutator().mutate(puts);
1038     if (autoFlush) {
1039       flushCommits();
1040     }
1041   }
1042 
1043   /**
1044    * {@inheritDoc}
1045    */
1046   @Override
1047   public void mutateRow(final RowMutations rm) throws IOException {
1048     final RetryingTimeTracker tracker = new RetryingTimeTracker().start();
1049     PayloadCarryingServerCallable<MultiResponse> callable =
1050       new PayloadCarryingServerCallable<MultiResponse>(connection, getName(), rm.getRow(),
1051           rpcControllerFactory) {
1052         @Override
1053         public MultiResponse call(int callTimeout) throws IOException {
1054           controller.reset();
1055           controller.setPriority(tableName);
1056           controller.setPriority(rm.getMaxPriority());
1057           int remainingTime = tracker.getRemainingTime(callTimeout);
1058           if (remainingTime == 0) {
1059             throw new DoNotRetryIOException("Timeout for mutate row");
1060           }
1061           controller.setCallTimeout(remainingTime);
1062           try {
1063             RegionAction.Builder regionMutationBuilder = RequestConverter.buildRegionAction(
1064                 getLocation().getRegionInfo().getRegionName(), rm);
1065             regionMutationBuilder.setAtomic(true);
1066             MultiRequest request =
1067                 MultiRequest.newBuilder().addRegionAction(regionMutationBuilder.build()).build();
1068             ClientProtos.MultiResponse response = getStub().multi(controller, request);
1069             ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
1070             if (res.hasException()) {
1071               Throwable ex = ProtobufUtil.toException(res.getException());
1072               if (ex instanceof IOException) {
1073                 throw (IOException) ex;
1074               }
1075               throw new IOException("Failed to mutate row: " +
1076                   Bytes.toStringBinary(rm.getRow()), ex);
1077             }
1078             return ResponseConverter.getResults(request, response, controller.cellScanner());
1079           } catch (ServiceException se) {
1080             throw ProtobufUtil.getRemoteException(se);
1081           }
1082         }
1083       };
1084     AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, rm.getMutations(),
1085         null, null, callable, operationTimeout, writeRpcTimeout);
1086     ars.waitUntilDone();
1087     if (ars.hasError()) {
1088       throw ars.getErrors();
1089     }
1090   }
1091 
1092   /**
1093    * {@inheritDoc}
1094    */
1095   @Override
1096   public Result append(final Append append) throws IOException {
1097     if (append.numFamilies() == 0) {
1098       throw new IOException(
1099           "Invalid arguments to append, no columns specified");
1100     }
1101 
1102     NonceGenerator ng = this.connection.getNonceGenerator();
1103     final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1104     RegionServerCallable<Result> callable =
1105       new RegionServerCallable<Result>(this.connection, getName(), append.getRow(), append.getPriority()) {
1106         @Override
1107         public Result call(int callTimeout) throws IOException {
1108           HBaseRpcController controller = rpcControllerFactory.newController();
1109           controller.setPriority(getTableName());
1110           controller.setCallTimeout(getPriority());
1111           try {
1112             MutateRequest request = RequestConverter.buildMutateRequest(
1113               getLocation().getRegionInfo().getRegionName(), append, nonceGroup, nonce);
1114             MutateResponse response = getStub().mutate(controller, request);
1115             if (!response.hasResult()) return null;
1116             return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1117           } catch (ServiceException se) {
1118             throw ProtobufUtil.getRemoteException(se);
1119           }
1120         }
1121       };
1122     return rpcCallerFactory.<Result> newCaller(writeRpcTimeout).callWithRetries(callable,
1123         this.operationTimeout);
1124   }
1125 
1126   /**
1127    * {@inheritDoc}
1128    */
1129   @Override
1130   public Result increment(final Increment increment) throws IOException {
1131     if (!increment.hasFamilies()) {
1132       throw new IOException(
1133           "Invalid arguments to increment, no columns specified");
1134     }
1135     NonceGenerator ng = this.connection.getNonceGenerator();
1136     final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1137     RegionServerCallable<Result> callable = new RegionServerCallable<Result>(this.connection,
1138         getName(), increment.getRow(), increment.getPriority()) {
1139       @Override
1140       public Result call(int callTimeout) throws IOException {
1141         HBaseRpcController controller = rpcControllerFactory.newController();
1142         controller.setPriority(getTableName());
1143         controller.setPriority(getPriority());
1144         controller.setCallTimeout(callTimeout);
1145         try {
1146           MutateRequest request = RequestConverter.buildMutateRequest(
1147             getLocation().getRegionInfo().getRegionName(), increment, nonceGroup, nonce);
1148           MutateResponse response = getStub().mutate(controller, request);
1149           return ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1150         } catch (ServiceException se) {
1151           throw ProtobufUtil.getRemoteException(se);
1152         }
1153       }
1154     };
1155     return rpcCallerFactory.<Result> newCaller(writeRpcTimeout).callWithRetries(callable,
1156         this.operationTimeout);
1157   }
1158 
1159   /**
1160    * {@inheritDoc}
1161    */
1162   @Override
1163   public long incrementColumnValue(final byte [] row, final byte [] family,
1164       final byte [] qualifier, final long amount)
1165   throws IOException {
1166     return incrementColumnValue(row, family, qualifier, amount, Durability.SYNC_WAL);
1167   }
1168 
1169   /**
1170    * @deprecated As of release 0.96
1171    *             (<a href="https://issues.apache.org/jira/browse/HBASE-9508">HBASE-9508</a>).
1172    *             This will be removed in HBase 2.0.0.
1173    *             Use {@link #incrementColumnValue(byte[], byte[], byte[], long, Durability)}.
1174    */
1175   @Deprecated
1176   @Override
1177   public long incrementColumnValue(final byte [] row, final byte [] family,
1178       final byte [] qualifier, final long amount, final boolean writeToWAL)
1179   throws IOException {
1180     return incrementColumnValue(row, family, qualifier, amount,
1181       writeToWAL? Durability.SYNC_WAL: Durability.SKIP_WAL);
1182   }
1183 
1184   /**
1185    * {@inheritDoc}
1186    */
1187   @Override
1188   public long incrementColumnValue(final byte [] row, final byte [] family,
1189       final byte [] qualifier, final long amount, final Durability durability)
1190   throws IOException {
1191     NullPointerException npe = null;
1192     if (row == null) {
1193       npe = new NullPointerException("row is null");
1194     } else if (family == null) {
1195       npe = new NullPointerException("family is null");
1196     } else if (qualifier == null) {
1197       npe = new NullPointerException("qualifier is null");
1198     }
1199     if (npe != null) {
1200       throw new IOException(
1201           "Invalid arguments to incrementColumnValue", npe);
1202     }
1203 
1204     NonceGenerator ng = this.connection.getNonceGenerator();
1205     final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce();
1206     RegionServerCallable<Long> callable =
1207       new RegionServerCallable<Long>(connection, getName(), row) {
1208         @Override
1209         public Long call(int callTimeout) throws IOException {
1210           HBaseRpcController controller = rpcControllerFactory.newController();
1211           controller.setPriority(getTableName());
1212           controller.setCallTimeout(callTimeout);
1213           try {
1214             MutateRequest request = RequestConverter.buildIncrementRequest(
1215               getLocation().getRegionInfo().getRegionName(), row, family,
1216               qualifier, amount, durability, nonceGroup, nonce);
1217             MutateResponse response = getStub().mutate(controller, request);
1218             Result result =
1219               ProtobufUtil.toResult(response.getResult(), controller.cellScanner());
1220             return Long.valueOf(Bytes.toLong(result.getValue(family, qualifier)));
1221           } catch (ServiceException se) {
1222             throw ProtobufUtil.getRemoteException(se);
1223           }
1224         }
1225       };
1226     return rpcCallerFactory.<Long> newCaller(writeRpcTimeout).callWithRetries(callable,
1227         this.operationTimeout);
1228   }
1229 
1230   /**
1231    * {@inheritDoc}
1232    */
1233   @Override
1234   public boolean checkAndPut(final byte [] row,
1235       final byte [] family, final byte [] qualifier, final byte [] value,
1236       final Put put)
1237   throws IOException {
1238     RegionServerCallable<Boolean> callable =
1239       new RegionServerCallable<Boolean>(connection, getName(), row, put.getPriority()) {
1240         @Override
1241         public Boolean call(int callTimeout) throws IOException {
1242           HBaseRpcController controller = rpcControllerFactory.newController();
1243           controller.setPriority(tableName);
1244           controller.setPriority(getPriority());
1245           controller.setCallTimeout(callTimeout);
1246           try {
1247             MutateRequest request = RequestConverter.buildMutateRequest(
1248                 getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1249                 new BinaryComparator(value), CompareType.EQUAL, put);
1250             MutateResponse response = getStub().mutate(controller, request);
1251             return Boolean.valueOf(response.getProcessed());
1252           } catch (ServiceException se) {
1253             throw ProtobufUtil.getRemoteException(se);
1254           }
1255         }
1256       };
1257     return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1258         this.operationTimeout);
1259   }
1260 
1261   /**
1262    * {@inheritDoc}
1263    */
1264   @Override
1265   public boolean checkAndPut(final byte [] row, final byte [] family,
1266       final byte [] qualifier, final CompareOp compareOp, final byte [] value,
1267       final Put put)
1268   throws IOException {
1269     RegionServerCallable<Boolean> callable =
1270       new RegionServerCallable<Boolean>(connection, getName(), row, put.getPriority()) {
1271         @Override
1272         public Boolean call(int callTimeout) throws IOException {
1273           HBaseRpcController controller = rpcControllerFactory.newController();
1274           controller.setPriority(tableName);
1275           controller.setPriority(getPriority());
1276           controller.setCallTimeout(callTimeout);
1277           try {
1278             CompareType compareType = CompareType.valueOf(compareOp.name());
1279             MutateRequest request = RequestConverter.buildMutateRequest(
1280               getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1281                 new BinaryComparator(value), compareType, put);
1282             MutateResponse response = getStub().mutate(controller, request);
1283             return Boolean.valueOf(response.getProcessed());
1284           } catch (ServiceException se) {
1285             throw ProtobufUtil.getRemoteException(se);
1286           }
1287         }
1288       };
1289     return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1290         this.operationTimeout);
1291   }
1292 
1293   /**
1294    * {@inheritDoc}
1295    */
1296   @Override
1297   public boolean checkAndDelete(final byte [] row,
1298       final byte [] family, final byte [] qualifier, final byte [] value,
1299       final Delete delete)
1300   throws IOException {
1301     RegionServerCallable<Boolean> callable =
1302       new RegionServerCallable<Boolean>(connection, getName(), row, delete.getPriority()) {
1303         @Override
1304         public Boolean call(int callTimeout) throws IOException {
1305           HBaseRpcController controller = rpcControllerFactory.newController();
1306           controller.setPriority(tableName);
1307           controller.setPriority(getPriority());
1308           controller.setCallTimeout(callTimeout);
1309           try {
1310             MutateRequest request = RequestConverter.buildMutateRequest(
1311               getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1312                 new BinaryComparator(value), CompareType.EQUAL, delete);
1313             MutateResponse response = getStub().mutate(controller, request);
1314             return Boolean.valueOf(response.getProcessed());
1315           } catch (ServiceException se) {
1316             throw ProtobufUtil.getRemoteException(se);
1317           }
1318         }
1319       };
1320     return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1321         this.operationTimeout);
1322   }
1323 
1324   /**
1325    * {@inheritDoc}
1326    */
1327   @Override
1328   public boolean checkAndDelete(final byte [] row, final byte [] family,
1329       final byte [] qualifier, final CompareOp compareOp, final byte [] value,
1330       final Delete delete)
1331   throws IOException {
1332     RegionServerCallable<Boolean> callable =
1333       new RegionServerCallable<Boolean>(connection, getName(), row, delete.getPriority()) {
1334         @Override
1335         public Boolean call(int callTimeout) throws IOException {
1336           HBaseRpcController controller = rpcControllerFactory.newController();
1337           controller.setPriority(tableName);
1338           controller.setPriority(getPriority());
1339           controller.setCallTimeout(callTimeout);
1340           try {
1341             CompareType compareType = CompareType.valueOf(compareOp.name());
1342             MutateRequest request = RequestConverter.buildMutateRequest(
1343               getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1344                 new BinaryComparator(value), compareType, delete);
1345             MutateResponse response = getStub().mutate(controller, request);
1346             return Boolean.valueOf(response.getProcessed());
1347           } catch (ServiceException se) {
1348             throw ProtobufUtil.getRemoteException(se);
1349           }
1350         }
1351       };
1352     return rpcCallerFactory.<Boolean> newCaller(writeRpcTimeout).callWithRetries(callable,
1353         this.operationTimeout);
1354   }
1355 
1356   /**
1357    * {@inheritDoc}
1358    */
1359   @Override
1360   public boolean checkAndMutate(final byte [] row, final byte [] family, final byte [] qualifier,
1361     final CompareOp compareOp, final byte [] value, final RowMutations rm)
1362     throws IOException {
1363     final RetryingTimeTracker tracker = new RetryingTimeTracker().start();
1364     PayloadCarryingServerCallable<MultiResponse> callable =
1365       new PayloadCarryingServerCallable<MultiResponse>(connection, getName(), row,
1366         rpcControllerFactory) {
1367         @Override
1368         public MultiResponse call(int callTimeout) throws IOException {
1369           controller.reset();
1370           controller.setPriority(tableName);
1371           controller.setPriority(rm.getMaxPriority());
1372           int remainingTime = tracker.getRemainingTime(callTimeout);
1373           if (remainingTime == 0) {
1374             throw new DoNotRetryIOException("Timeout for mutate row");
1375           }
1376           controller.setCallTimeout(remainingTime);
1377           try {
1378             CompareType compareType = CompareType.valueOf(compareOp.name());
1379             MultiRequest request = RequestConverter.buildMutateRequest(
1380               getLocation().getRegionInfo().getRegionName(), row, family, qualifier,
1381               new BinaryComparator(value), compareType, rm);
1382             ClientProtos.MultiResponse response = getStub().multi(controller, request);
1383             ClientProtos.RegionActionResult res = response.getRegionActionResultList().get(0);
1384             if (res.hasException()) {
1385               Throwable ex = ProtobufUtil.toException(res.getException());
1386               if(ex instanceof IOException) {
1387                 throw (IOException)ex;
1388               }
1389               throw new IOException("Failed to checkAndMutate row: "+
1390                 Bytes.toStringBinary(row), ex);
1391             }
1392             return ResponseConverter.getResults(request, response, controller.cellScanner());
1393           } catch (ServiceException se) {
1394             throw ProtobufUtil.getRemoteException(se);
1395           }
1396         }
1397       };
1398     /**
1399      *  Currently, we use one array to store 'processed' flag which is returned by server.
1400      *  It is excessive to send such a large array, but that is required by the framework right now
1401      * */
1402     Object[] results = new Object[rm.getMutations().size()];
1403     AsyncRequestFuture ars = multiAp.submitAll(pool, tableName, rm.getMutations(),
1404       null, results, callable, operationTimeout, writeRpcTimeout);
1405     ars.waitUntilDone();
1406     if (ars.hasError()) {
1407       throw ars.getErrors();
1408     }
1409 
1410     return ((Result)results[0]).getExists();
1411   }
1412 
1413   /**
1414    * {@inheritDoc}
1415    */
1416   @Override
1417   public boolean exists(final Get get) throws IOException {
1418     Result r = get(get, true);
1419     assert r.getExists() != null;
1420     return r.getExists();
1421   }
1422 
1423   /**
1424    * {@inheritDoc}
1425    */
1426   @Override
1427   public boolean[] existsAll(final List<Get> gets) throws IOException {
1428     if (gets.isEmpty()) return new boolean[]{};
1429     if (gets.size() == 1) return new boolean[]{exists(gets.get(0))};
1430 
1431     ArrayList<Get> exists = new ArrayList<Get>(gets.size());
1432     for (Get g: gets){
1433       Get ge = new Get(g);
1434       ge.setCheckExistenceOnly(true);
1435       exists.add(ge);
1436     }
1437 
1438     Object[] r1 = new Object[exists.size()];
1439     try {
1440       batch(exists, r1, readRpcTimeout);
1441     } catch (InterruptedException e) {
1442       throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1443     }
1444 
1445     // translate.
1446     boolean[] results = new boolean[r1.length];
1447     int i = 0;
1448     for (Object o : r1) {
1449       // batch ensures if there is a failure we get an exception instead
1450       results[i++] = ((Result)o).getExists();
1451     }
1452 
1453     return results;
1454   }
1455 
1456   /**
1457    * {@inheritDoc}
1458    */
1459   @Override
1460   @Deprecated
1461   public Boolean[] exists(final List<Get> gets) throws IOException {
1462     boolean[] results = existsAll(gets);
1463     Boolean[] objectResults = new Boolean[results.length];
1464     for (int i = 0; i < results.length; ++i) {
1465       objectResults[i] = results[i];
1466     }
1467     return objectResults;
1468   }
1469 
1470   /**
1471    * {@inheritDoc}
1472    * @throws IOException
1473    */
1474   @Override
1475   public void flushCommits() throws IOException {
1476     if (mutator == null) {
1477       // nothing to flush if there's no mutator; don't bother creating one.
1478       return;
1479     }
1480     getBufferedMutator().flush();
1481   }
1482 
1483   /**
1484    * Process a mixed batch of Get, Put and Delete actions. All actions for a
1485    * RegionServer are forwarded in one RPC call. Queries are executed in parallel.
1486    *
1487    * @param list The collection of actions.
1488    * @param results An empty array, same size as list. If an exception is thrown,
1489    * you can test here for partial results, and to determine which actions
1490    * processed successfully.
1491    * @throws IOException if there are problems talking to META. Per-item
1492    * exceptions are stored in the results array.
1493    */
1494   public <R> void processBatchCallback(
1495     final List<? extends Row> list, final Object[] results, final Batch.Callback<R> callback)
1496     throws IOException, InterruptedException {
1497     this.batchCallback(list, results, callback);
1498   }
1499 
1500   @Override
1501   public void close() throws IOException {
1502     if (this.closed) {
1503       return;
1504     }
1505     flushCommits();
1506     if (cleanupPoolOnClose) {
1507       this.pool.shutdown();
1508       try {
1509         boolean terminated = false;
1510         do {
1511           // wait until the pool has terminated
1512           terminated = this.pool.awaitTermination(60, TimeUnit.SECONDS);
1513         } while (!terminated);
1514       } catch (InterruptedException e) {
1515         this.pool.shutdownNow();
1516         LOG.warn("waitForTermination interrupted");
1517       }
1518     }
1519     if (cleanupConnectionOnClose) {
1520       if (this.connection != null) {
1521         this.connection.close();
1522       }
1523     }
1524     this.closed = true;
1525   }
1526 
1527   // validate for well-formedness
1528   public void validatePut(final Put put) throws IllegalArgumentException {
1529     validatePut(put, connConfiguration.getMaxKeyValueSize());
1530   }
1531 
1532   // validate for well-formedness
1533   public static void validatePut(Put put, int maxKeyValueSize) throws IllegalArgumentException {
1534     if (put.isEmpty()) {
1535       throw new IllegalArgumentException("No columns to insert");
1536     }
1537     if (maxKeyValueSize > 0) {
1538       for (List<Cell> list : put.getFamilyCellMap().values()) {
1539         for (Cell cell : list) {
1540           if (KeyValueUtil.length(cell) > maxKeyValueSize) {
1541             throw new IllegalArgumentException("KeyValue size too large");
1542           }
1543         }
1544       }
1545     }
1546   }
1547 
1548   /**
1549    * {@inheritDoc}
1550    */
1551   @Override
1552   public boolean isAutoFlush() {
1553     return autoFlush;
1554   }
1555 
1556   /**
1557    * {@inheritDoc}
1558    */
1559   @Deprecated
1560   @Override
1561   public void setAutoFlush(boolean autoFlush) {
1562     this.autoFlush = autoFlush;
1563   }
1564 
1565   /**
1566    * {@inheritDoc}
1567    */
1568   @Override
1569   public void setAutoFlushTo(boolean autoFlush) {
1570     this.autoFlush = autoFlush;
1571   }
1572 
1573   /**
1574    * {@inheritDoc}
1575    */
1576   @Override
1577   public void setAutoFlush(boolean autoFlush, boolean clearBufferOnFail) {
1578     this.autoFlush = autoFlush;
1579   }
1580 
1581   /**
1582    * Returns the maximum size in bytes of the write buffer for this HTable.
1583    * <p>
1584    * The default value comes from the configuration parameter
1585    * {@code hbase.client.write.buffer}.
1586    * @return The size of the write buffer in bytes.
1587    */
1588   @Override
1589   public long getWriteBufferSize() {
1590     if (mutator == null) {
1591       return connConfiguration.getWriteBufferSize();
1592     } else {
1593       return mutator.getWriteBufferSize();
1594     }
1595   }
1596 
1597   /**
1598    * Sets the size of the buffer in bytes.
1599    * <p>
1600    * If the new size is less than the current amount of data in the
1601    * write buffer, the buffer gets flushed.
1602    * @param writeBufferSize The new write buffer size, in bytes.
1603    * @throws IOException if a remote or network exception occurs.
1604    */
1605   @Override
1606   public void setWriteBufferSize(long writeBufferSize) throws IOException {
1607     getBufferedMutator();
1608     mutator.setWriteBufferSize(writeBufferSize);
1609   }
1610 
1611   /**
1612    * The pool is used for mutli requests for this HTable
1613    * @return the pool used for mutli
1614    */
1615   ExecutorService getPool() {
1616     return this.pool;
1617   }
1618 
1619   /**
1620    * Enable or disable region cache prefetch for the table. It will be
1621    * applied for the given table's all HTable instances who share the same
1622    * connection. By default, the cache prefetch is enabled.
1623    * @param tableName name of table to configure.
1624    * @param enable Set to true to enable region cache prefetch. Or set to
1625    * false to disable it.
1626    * @throws IOException
1627    * @deprecated does nothing since 0.99
1628    */
1629   @Deprecated
1630   public static void setRegionCachePrefetch(final byte[] tableName,
1631       final boolean enable)  throws IOException {
1632   }
1633 
1634   /**
1635    * @deprecated does nothing since 0.99
1636    */
1637   @Deprecated
1638   public static void setRegionCachePrefetch(
1639       final TableName tableName,
1640       final boolean enable) throws IOException {
1641   }
1642 
1643   /**
1644    * Enable or disable region cache prefetch for the table. It will be
1645    * applied for the given table's all HTable instances who share the same
1646    * connection. By default, the cache prefetch is enabled.
1647    * @param conf The Configuration object to use.
1648    * @param tableName name of table to configure.
1649    * @param enable Set to true to enable region cache prefetch. Or set to
1650    * false to disable it.
1651    * @throws IOException
1652    * @deprecated does nothing since 0.99
1653    */
1654   @Deprecated
1655   public static void setRegionCachePrefetch(final Configuration conf,
1656       final byte[] tableName, final boolean enable) throws IOException {
1657   }
1658 
1659   /**
1660    * @deprecated does nothing since 0.99
1661    */
1662   @Deprecated
1663   public static void setRegionCachePrefetch(final Configuration conf,
1664       final TableName tableName,
1665       final boolean enable) throws IOException {
1666   }
1667 
1668   /**
1669    * Check whether region cache prefetch is enabled or not for the table.
1670    * @param conf The Configuration object to use.
1671    * @param tableName name of table to check
1672    * @return true if table's region cache prefecth is enabled. Otherwise
1673    * it is disabled.
1674    * @throws IOException
1675    * @deprecated always return false since 0.99
1676    */
1677   @Deprecated
1678   public static boolean getRegionCachePrefetch(final Configuration conf,
1679       final byte[] tableName) throws IOException {
1680     return false;
1681   }
1682 
1683   /**
1684    * @deprecated always return false since 0.99
1685    */
1686   @Deprecated
1687   public static boolean getRegionCachePrefetch(final Configuration conf,
1688       final TableName tableName) throws IOException {
1689     return false;
1690   }
1691 
1692   /**
1693    * Check whether region cache prefetch is enabled or not for the table.
1694    * @param tableName name of table to check
1695    * @return true if table's region cache prefecth is enabled. Otherwise
1696    * it is disabled.
1697    * @throws IOException
1698    * @deprecated always return false since 0.99
1699    */
1700   @Deprecated
1701   public static boolean getRegionCachePrefetch(final byte[] tableName) throws IOException {
1702     return false;
1703   }
1704 
1705   /**
1706    * @deprecated always return false since 0.99
1707    */
1708   @Deprecated
1709   public static boolean getRegionCachePrefetch(
1710       final TableName tableName) throws IOException {
1711     return false;
1712   }
1713 
1714   /**
1715    * Explicitly clears the region cache to fetch the latest value from META.
1716    * This is a power user function: avoid unless you know the ramifications.
1717    */
1718   public void clearRegionCache() {
1719     this.connection.clearRegionCache();
1720   }
1721 
1722   /**
1723    * {@inheritDoc}
1724    */
1725   @Override
1726   public CoprocessorRpcChannel coprocessorService(byte[] row) {
1727     return new RegionCoprocessorRpcChannel(connection, tableName, row);
1728   }
1729 
1730   /**
1731    * {@inheritDoc}
1732    */
1733   @Override
1734   public <T extends Service, R> Map<byte[],R> coprocessorService(final Class<T> service,
1735       byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable)
1736       throws ServiceException, Throwable {
1737     final Map<byte[],R> results =  Collections.synchronizedMap(
1738         new TreeMap<byte[], R>(Bytes.BYTES_COMPARATOR));
1739     coprocessorService(service, startKey, endKey, callable, new Batch.Callback<R>() {
1740       @Override
1741       public void update(byte[] region, byte[] row, R value) {
1742         if (region != null) {
1743           results.put(region, value);
1744         }
1745       }
1746     });
1747     return results;
1748   }
1749 
1750   /**
1751    * {@inheritDoc}
1752    */
1753   @Override
1754   public <T extends Service, R> void coprocessorService(final Class<T> service,
1755       byte[] startKey, byte[] endKey, final Batch.Call<T,R> callable,
1756       final Batch.Callback<R> callback) throws ServiceException, Throwable {
1757 
1758     // get regions covered by the row range
1759     List<byte[]> keys = getStartKeysInRange(startKey, endKey);
1760 
1761     Map<byte[],Future<R>> futures =
1762         new TreeMap<byte[],Future<R>>(Bytes.BYTES_COMPARATOR);
1763     for (final byte[] r : keys) {
1764       final RegionCoprocessorRpcChannel channel =
1765           new RegionCoprocessorRpcChannel(connection, tableName, r);
1766       Future<R> future = pool.submit(
1767           new Callable<R>() {
1768             @Override
1769             public R call() throws Exception {
1770               T instance = ProtobufUtil.newServiceStub(service, channel);
1771               R result = callable.call(instance);
1772               byte[] region = channel.getLastRegion();
1773               if (callback != null) {
1774                 callback.update(region, r, result);
1775               }
1776               return result;
1777             }
1778           });
1779       futures.put(r, future);
1780     }
1781     for (Map.Entry<byte[],Future<R>> e : futures.entrySet()) {
1782       try {
1783         e.getValue().get();
1784       } catch (ExecutionException ee) {
1785         LOG.warn("Error calling coprocessor service " + service.getName() + " for row "
1786             + Bytes.toStringBinary(e.getKey()), ee);
1787         throw ee.getCause();
1788       } catch (InterruptedException ie) {
1789         throw new InterruptedIOException("Interrupted calling coprocessor service " + service.getName()
1790             + " for row " + Bytes.toStringBinary(e.getKey()))
1791             .initCause(ie);
1792       }
1793     }
1794   }
1795 
1796   private List<byte[]> getStartKeysInRange(byte[] start, byte[] end)
1797   throws IOException {
1798     if (start == null) {
1799       start = HConstants.EMPTY_START_ROW;
1800     }
1801     if (end == null) {
1802       end = HConstants.EMPTY_END_ROW;
1803     }
1804     return getKeysAndRegionsInRange(start, end, true).getFirst();
1805   }
1806 
1807   @Override
1808   public void setOperationTimeout(int operationTimeout) {
1809     this.operationTimeout = operationTimeout;
1810     if (mutator != null) {
1811       mutator.setOperationTimeout(operationTimeout);
1812     }
1813     multiAp.setOperationTimeout(operationTimeout);
1814   }
1815 
1816   @Override
1817   public int getOperationTimeout() {
1818     return operationTimeout;
1819   }
1820 
1821   @Override
1822   @Deprecated
1823   public int getRpcTimeout() {
1824     return readRpcTimeout;
1825   }
1826 
1827   @Override
1828   @Deprecated
1829   public void setRpcTimeout(int rpcTimeout) {
1830     setWriteRpcTimeout(rpcTimeout);
1831     setReadRpcTimeout(rpcTimeout);
1832   }
1833 
1834   @Override
1835   public int getWriteRpcTimeout() {
1836     return writeRpcTimeout;
1837   }
1838 
1839   @Override
1840   public void setWriteRpcTimeout(int writeRpcTimeout) {
1841     this.writeRpcTimeout = writeRpcTimeout;
1842     if (mutator != null) {
1843       mutator.setRpcTimeout(writeRpcTimeout);
1844     }
1845     multiAp.setRpcTimeout(writeRpcTimeout);
1846   }
1847 
1848   @Override
1849   public int getReadRpcTimeout() { return readRpcTimeout; }
1850 
1851   @Override
1852   public void setReadRpcTimeout(int readRpcTimeout) {
1853     this.readRpcTimeout = readRpcTimeout;
1854   }
1855 
1856   @Override
1857   public String toString() {
1858     return tableName + ";" + connection;
1859   }
1860 
1861   /**
1862    * {@inheritDoc}
1863    */
1864   @Override
1865   public <R extends Message> Map<byte[], R> batchCoprocessorService(
1866       Descriptors.MethodDescriptor methodDescriptor, Message request,
1867       byte[] startKey, byte[] endKey, R responsePrototype) throws ServiceException, Throwable {
1868     final Map<byte[], R> results = Collections.synchronizedMap(new TreeMap<byte[], R>(
1869         Bytes.BYTES_COMPARATOR));
1870     batchCoprocessorService(methodDescriptor, request, startKey, endKey, responsePrototype,
1871         new Callback<R>() {
1872 
1873           @Override
1874           public void update(byte[] region, byte[] row, R result) {
1875             if (region != null) {
1876               results.put(region, result);
1877             }
1878           }
1879         });
1880     return results;
1881   }
1882 
1883   /**
1884    * {@inheritDoc}
1885    */
1886   @Override
1887   public <R extends Message> void batchCoprocessorService(
1888       final Descriptors.MethodDescriptor methodDescriptor, final Message request,
1889       byte[] startKey, byte[] endKey, final R responsePrototype, final Callback<R> callback)
1890       throws ServiceException, Throwable {
1891 
1892     if (startKey == null) {
1893       startKey = HConstants.EMPTY_START_ROW;
1894     }
1895     if (endKey == null) {
1896       endKey = HConstants.EMPTY_END_ROW;
1897     }
1898     // get regions covered by the row range
1899     Pair<List<byte[]>, List<HRegionLocation>> keysAndRegions =
1900         getKeysAndRegionsInRange(startKey, endKey, true);
1901     List<byte[]> keys = keysAndRegions.getFirst();
1902     List<HRegionLocation> regions = keysAndRegions.getSecond();
1903 
1904     // check if we have any calls to make
1905     if (keys.isEmpty()) {
1906       LOG.info("No regions were selected by key range start=" + Bytes.toStringBinary(startKey) +
1907           ", end=" + Bytes.toStringBinary(endKey));
1908       return;
1909     }
1910 
1911     List<RegionCoprocessorServiceExec> execs = new ArrayList<RegionCoprocessorServiceExec>();
1912     final Map<byte[], RegionCoprocessorServiceExec> execsByRow =
1913         new TreeMap<byte[], RegionCoprocessorServiceExec>(Bytes.BYTES_COMPARATOR);
1914     for (int i = 0; i < keys.size(); i++) {
1915       final byte[] rowKey = keys.get(i);
1916       final byte[] region = regions.get(i).getRegionInfo().getRegionName();
1917       RegionCoprocessorServiceExec exec =
1918           new RegionCoprocessorServiceExec(region, rowKey, methodDescriptor, request);
1919       execs.add(exec);
1920       execsByRow.put(rowKey, exec);
1921     }
1922 
1923     // tracking for any possible deserialization errors on success callback
1924     // TODO: it would be better to be able to reuse AsyncProcess.BatchErrors here
1925     final List<Throwable> callbackErrorExceptions = new ArrayList<Throwable>();
1926     final List<Row> callbackErrorActions = new ArrayList<Row>();
1927     final List<String> callbackErrorServers = new ArrayList<String>();
1928     Object[] results = new Object[execs.size()];
1929 
1930     AsyncProcess asyncProcess =
1931         new AsyncProcess(connection, configuration, pool,
1932             RpcRetryingCallerFactory.instantiate(configuration, connection.getStatisticsTracker()),
1933             true, RpcControllerFactory.instantiate(configuration), readRpcTimeout);
1934 
1935     AsyncRequestFuture future = asyncProcess.submitAll(tableName, execs,
1936         new Callback<ClientProtos.CoprocessorServiceResult>() {
1937           @Override
1938           public void update(byte[] region, byte[] row,
1939                               ClientProtos.CoprocessorServiceResult serviceResult) {
1940             if (LOG.isTraceEnabled()) {
1941               LOG.trace("Received result for endpoint " + methodDescriptor.getFullName() +
1942                   ": region=" + Bytes.toStringBinary(region) +
1943                   ", row=" + Bytes.toStringBinary(row) +
1944                   ", value=" + serviceResult.getValue().getValue());
1945             }
1946             try {
1947               Message.Builder builder = responsePrototype.newBuilderForType();
1948               ProtobufUtil.mergeFrom(builder, serviceResult.getValue().getValue());
1949               callback.update(region, row, (R) builder.build());
1950             } catch (IOException e) {
1951               LOG.error("Unexpected response type from endpoint " + methodDescriptor.getFullName(),
1952                   e);
1953               callbackErrorExceptions.add(e);
1954               callbackErrorActions.add(execsByRow.get(row));
1955               callbackErrorServers.add("null");
1956             }
1957           }
1958         }, results);
1959 
1960     future.waitUntilDone();
1961 
1962     if (future.hasError()) {
1963       throw future.getErrors();
1964     } else if (!callbackErrorExceptions.isEmpty()) {
1965       throw new RetriesExhaustedWithDetailsException(callbackErrorExceptions, callbackErrorActions,
1966           callbackErrorServers);
1967     }
1968   }
1969 
1970   public RegionLocator getRegionLocator() {
1971     return this.locator;
1972   }
1973 
1974   @VisibleForTesting
1975   BufferedMutator getBufferedMutator() throws IOException {
1976     if (mutator == null) {
1977       this.mutator = (BufferedMutatorImpl) connection.getBufferedMutator(
1978           new BufferedMutatorParams(tableName)
1979               .pool(pool)
1980               .writeBufferSize(connConfiguration.getWriteBufferSize())
1981               .maxKeyValueSize(connConfiguration.getMaxKeyValueSize())
1982       );
1983       mutator.setRpcTimeout(writeRpcTimeout);
1984       mutator.setOperationTimeout(operationTimeout);
1985     }
1986     return mutator;
1987   }
1988 }