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