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