index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/TokenHostConnectionPoolPartition.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.math.BigInteger;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
/**
* Collection of pools that own a token range of the ring
*
* @author elandau
*
* @param <CL>
*/
public class TokenHostConnectionPoolPartition<CL> extends HostConnectionPoolPartition<CL> {
private final BigInteger token;
public TokenHostConnectionPoolPartition(BigInteger id, LatencyScoreStrategy strategy) {
super(strategy);
this.token = id;
}
/**
* Token or shard identifying this partition.
*
* @return
*/
public BigInteger id() {
return token;
}
}
| 7,700 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/BagOfConnectionsConnectionPoolImpl.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.List;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.netflix.astyanax.connectionpool.Connection;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.ExecuteWithFailover;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.InterruptedOperationException;
import com.netflix.astyanax.connectionpool.exceptions.IsDeadConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.IsTimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException;
import com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException;
/**
* Connection pool which puts all connections in a single queue. The load
* balancing is essentially random here. <br/>
*
* The class consults {@link Topology} for all the pools and then selects a pool at random using {@link #randomIndex}
* For {@link #executeWithFailover(Operation, com.netflix.astyanax.retry.RetryPolicy)} it just fails over to the next pool in the list of pools
* starting at the random index.
*
* @author elandau
*
* @param <CL>
*
* @see {@link AbstractHostPartitionConnectionPool} for the base class that provides the rest of the functionality
* @see {@link Topology} and {@link TokenPartitionedTopology} for details on where this class gets it list of host connection pools to randomly index over
*/
public class BagOfConnectionsConnectionPoolImpl<CL> extends AbstractHostPartitionConnectionPool<CL> {
private final LinkedBlockingQueue<Connection<CL>> idleConnections = new LinkedBlockingQueue<Connection<CL>>();
private final AtomicInteger activeConnectionCount = new AtomicInteger(0);
private final Random randomIndex = new Random();
/**
* @param config
* @param factory
* @param monitor
*/
public BagOfConnectionsConnectionPoolImpl(ConnectionPoolConfiguration config, ConnectionFactory<CL> factory,
ConnectionPoolMonitor monitor) {
super(config, factory, monitor);
}
private <R> Connection<CL> borrowConnection(Operation<CL, R> op) throws ConnectionException {
long startTime = System.currentTimeMillis();
// Try to get an open connection from the bag
Connection<CL> connection = null;
boolean newConnection = false;
try {
connection = idleConnections.poll();
if (connection != null) {
return connection;
}
// Already reached max connections so just wait
if (activeConnectionCount.incrementAndGet() > config.getMaxConns()) {
activeConnectionCount.decrementAndGet();
try {
connection = idleConnections.poll(config.getMaxTimeoutWhenExhausted(), TimeUnit.MILLISECONDS);
if (connection == null) {
throw new PoolTimeoutException("Timed out waiting for connection from bag");
}
return connection;
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedOperationException("Interrupted waiting to borrow a connection");
}
}
// Try to create a new one
try {
newConnection = true;
// Find a random node and open a connection on it. If that node
// has been exhausted
// then try the next one in array order until a connection can
// be created
List<HostConnectionPool<CL>> pools = topology.getAllPools().getPools();
if (pools != null && pools.size() > 0) {
int index = randomIndex.nextInt(pools.size());
for (int i = 0; i < pools.size(); ++i, ++index) {
HostConnectionPool<CL> pool = pools.get(index % pools.size());
try {
connection = pool.borrowConnection(config.getConnectTimeout());
return connection;
}
catch (ConnectionException connectionException) {
// Ignore
}
}
throw new NoAvailableHostsException("Too many errors trying to open a connection");
}
else {
throw new NoAvailableHostsException("No hosts to borrow from");
}
}
finally {
if (connection == null)
activeConnectionCount.decrementAndGet();
}
}
finally {
if (connection != null && newConnection == false)
monitor.incConnectionBorrowed(connection.getHostConnectionPool().getHost(), System.currentTimeMillis()
- startTime);
}
}
protected boolean returnConnection(Connection<CL> connection) {
if (connection != null) {
if (connection.getHostConnectionPool().isReconnecting()
|| connection.getOperationCount() > config.getMaxOperationsPerConnection()) {
closeConnection(connection);
}
else {
ConnectionException ce = connection.getLastException();
if (ce != null && (ce instanceof IsDeadConnectionException || ce instanceof IsTimeoutException)) {
closeConnection(connection);
}
else if (!this.idleConnections.offer(connection)) {
closeConnection(connection);
}
else {
this.monitor.incConnectionReturned(connection.getHostConnectionPool().getHost());
}
}
return true;
}
return false;
}
private void closeConnection(Connection<CL> connection) {
connection.getHostConnectionPool().closeConnection(connection);
activeConnectionCount.decrementAndGet();
}
class BagExecuteWithFailover<R> extends AbstractExecuteWithFailoverImpl<CL, R> {
private int retryCountdown;
private HostConnectionPool<CL> pool = null;
private int size = 0;
public BagExecuteWithFailover(ConnectionPoolConfiguration config) throws ConnectionException {
super(config, monitor);
size = topology.getAllPools().getPools().size();
retryCountdown = Math.min(config.getMaxFailoverCount(), size);
if (retryCountdown < 0)
retryCountdown = size;
}
@Override
public HostConnectionPool<CL> getCurrentHostConnectionPool() {
return pool;
}
@Override
public Connection<CL> borrowConnection(Operation<CL, R> operation) throws ConnectionException {
pool = null;
connection = BagOfConnectionsConnectionPoolImpl.this.borrowConnection(operation);
pool = connection.getHostConnectionPool();
return connection;
}
@Override
public boolean canRetry() {
return --retryCountdown >= 0;
}
@Override
public void releaseConnection() {
BagOfConnectionsConnectionPoolImpl.this.returnConnection(connection);
connection = null;
}
}
@Override
public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> op) throws ConnectionException {
return new BagExecuteWithFailover<R>(config);
}
}
| 7,701 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/TokenRangeImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.netflix.astyanax.connectionpool.TokenRange;
/**
* Impl for {@link TokenRange}
*
* @author elandau
*/
public class TokenRangeImpl implements TokenRange {
private final String startToken;
private final String endToken;
private final List<String> endpoints;
public TokenRangeImpl(String startToken, String endToken, List<String> endpoints) {
this.startToken = startToken;
this.endToken = endToken;
if (endpoints != null)
this.endpoints = ImmutableList.copyOf(endpoints);
else
this.endpoints = Lists.newArrayList();
}
@Override
public String getStartToken() {
return this.startToken;
}
@Override
public String getEndToken() {
return this.endToken;
}
@Override
public List<String> getEndpoints() {
return this.endpoints;
}
@Override
public String toString() {
return "TokenRangeImpl [startToken=" + startToken + ", endToken=" + endToken + ", endpoints=" + endpoints + "]";
}
}
| 7,702 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/NodeDiscoveryMonitorManager.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.google.common.collect.Maps;
import com.netflix.astyanax.connectionpool.NodeDiscovery;
import com.netflix.astyanax.connectionpool.NodeDiscoveryMonitor;
import com.netflix.astyanax.connectionpool.NodeDiscoveryMonitorMBean;
/**
* Jmx bean monitor manager for {@link NodeDiscoveryMonitor}
* @author elandau
*
*/
public class NodeDiscoveryMonitorManager {
private MBeanServer mbs;
private static class LazyHolder {
private static final NodeDiscoveryMonitorManager instance = new NodeDiscoveryMonitorManager();
}
private HashMap<String, NodeDiscoveryMonitorMBean> monitors;
private NodeDiscoveryMonitorManager() {
mbs = ManagementFactory.getPlatformMBeanServer();
monitors = Maps.newHashMap();
}
public static NodeDiscoveryMonitorManager getInstance() {
return LazyHolder.instance;
}
public synchronized void registerMonitor(String monitorName, NodeDiscovery discovery) {
monitorName = generateMonitorName(monitorName);
if (!monitors.containsKey(monitorName)) {
NodeDiscoveryMonitorMBean mbean;
try {
ObjectName oName = new ObjectName(monitorName);
mbean = new NodeDiscoveryMonitor(discovery);
monitors.put(monitorName, mbean);
mbs.registerMBean(mbean, oName);
}
catch (Exception e) {
monitors.remove(monitorName);
}
}
}
public synchronized void unregisterMonitor(String monitorName, NodeDiscovery discovery) {
monitorName = generateMonitorName(monitorName);
monitors.remove(monitorName);
try {
mbs.unregisterMBean(new ObjectName(monitorName));
}
catch (Exception e) {
}
}
public synchronized NodeDiscoveryMonitorMBean getCassandraMonitor(String monitorName) {
monitorName = generateMonitorName(monitorName);
return monitors.get(monitorName);
}
private String generateMonitorName(String monitorName) {
StringBuilder sb = new StringBuilder();
sb.append("com.netflix.MonitoredResources");
sb.append(":type=ASTYANAX");
sb.append(",name=" + monitorName.toString());
sb.append(",ServiceType=discovery");
return sb.toString();
}
}
| 7,703 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/NodeDiscoveryImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.joda.time.DateTime;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.NodeDiscovery;
/**
* Re-discover the ring on a fixed interval to identify new nodes or changes to
* the ring tokens. <br/> <br/>
*
* The class is started by the AstyanaxContext and uses a thread within an executor to repeatedly update the list of hosts required by a {@link ConnectionPool} using
* {@link ConnectionPool#setHosts(java.util.Collection)}. Note that the host source / supplier is passed in as an argument.
* @author elandau
*
* @param <CL>
*/
public class NodeDiscoveryImpl implements NodeDiscovery {
private final ConnectionPool<?> connectionPool;
private final ScheduledExecutorService executor;
private boolean bOwnedExecutor = false;
private final int interval;
private final String name;
private final Supplier<List<Host>> hostSupplier;
private final AtomicReference<DateTime> lastUpdateTime = new AtomicReference<DateTime>();
private final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
private final AtomicLong refreshCounter = new AtomicLong();
private final AtomicLong errorCounter = new AtomicLong();
public NodeDiscoveryImpl(
String name,
int interval,
Supplier<List<Host>> hostSupplier,
ConnectionPool<?> connectionPool) {
this(name, interval, hostSupplier, connectionPool,
Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setDaemon(true).build()));
bOwnedExecutor = true;
}
public NodeDiscoveryImpl(
String name,
int interval,
Supplier<List<Host>> hostSupplier,
ConnectionPool<?> connectionPool,
ScheduledExecutorService executor) {
this.connectionPool = connectionPool;
this.interval = interval;
this.hostSupplier = hostSupplier;
this.name = name;
this.executor = executor;
}
/**
*
*/
@Override
public void start() {
update();
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("RingDescribeAutoDiscovery");
update();
}
}, interval, interval, TimeUnit.MILLISECONDS);
NodeDiscoveryMonitorManager.getInstance().registerMonitor(name, this);
}
@Override
public void shutdown() {
if (bOwnedExecutor)
executor.shutdown();
NodeDiscoveryMonitorManager.getInstance().unregisterMonitor(name, this);
}
private void update() {
try {
connectionPool.setHosts(hostSupplier.get());
refreshCounter.incrementAndGet();
lastUpdateTime.set(new DateTime());
}
catch (Exception e) {
errorCounter.incrementAndGet();
lastException.set(e);
}
}
@Override
public DateTime getLastRefreshTime() {
return lastUpdateTime.get();
}
@Override
public long getRefreshCount() {
return refreshCounter.get();
}
@Override
public Exception getLastException() {
return lastException.get();
}
@Override
public long getErrorCount() {
return errorCounter.get();
}
@Override
public String getRawHostList() {
try {
return hostSupplier.get().toString();
}
catch (Exception e) {
return e.getMessage();
}
}
}
| 7,704 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/OperationResultImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.concurrent.TimeUnit;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.OperationResult;
/**
* Impl for {@link OperationResult}
* Tracks operation attempts, operation pinned host and latency associated with the operation.
*
* @author elandau
*
* @param <R>
*/
public class OperationResultImpl<R> implements OperationResult<R> {
private final Host host;
private final R result;
private final long latency;
private int attemptCount = 0;
public OperationResultImpl(Host host, R result, long latency) {
this.host = host;
this.result = result;
this.latency = latency;
}
@Override
public Host getHost() {
return this.host;
}
@Override
public R getResult() {
return this.result;
}
@Override
public long getLatency() {
return this.latency;
}
@Override
public long getLatency(TimeUnit units) {
return units.convert(this.latency, TimeUnit.NANOSECONDS);
}
@Override
public int getAttemptsCount() {
return attemptCount;
}
@Override
public void setAttemptsCount(int count) {
this.attemptCount = count;
}
}
| 7,705 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractTopology.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
public class AbstractTopology<CL> implements Topology<CL> {
/**
* Partition which contains all hosts. This is the fallback partition when no tokens are provided.
*/
private TokenHostConnectionPoolPartition<CL> allPools;
/**
* Strategy used to score hosts within a partition.
*/
private LatencyScoreStrategy strategy;
public AbstractTopology(LatencyScoreStrategy strategy) {
this.strategy = strategy;
this.allPools = new TokenHostConnectionPoolPartition<CL>(null, this.strategy);
}
@SuppressWarnings("unchecked")
@Override
/**
* Update the list of pools using the provided mapping of start token to collection of hosts
* that own the token
*/
public synchronized boolean setPools(Collection<HostConnectionPool<CL>> ring) {
boolean didChange = false;
Set<HostConnectionPool<CL>> allPools = Sets.newHashSet();
// Create a mapping of end token to a list of hosts that own the token
for (HostConnectionPool<CL> pool : ring) {
allPools.add(pool);
if (!this.allPools.hasPool(pool))
didChange = true;
}
return didChange;
}
@Override
public synchronized void resumePool(HostConnectionPool<CL> pool) {
refresh();
}
@Override
public synchronized void suspendPool(HostConnectionPool<CL> pool) {
refresh();
}
@Override
public synchronized void refresh() {
allPools.refresh();
}
@Override
public TokenHostConnectionPoolPartition<CL> getPartition(ByteBuffer rowkey) {
return getAllPools();
}
@Override
public TokenHostConnectionPoolPartition<CL> getAllPools() {
return allPools;
}
@Override
public int getPartitionCount() {
return 1;
}
@Override
public synchronized void removePool(HostConnectionPool<CL> pool) {
allPools.removePool(pool);
refresh();
}
@Override
public synchronized void addPool(HostConnectionPool<CL> pool) {
allPools.addPool(pool);
allPools.refresh();
}
@Override
public List<String> getPartitionNames() {
return Lists.newArrayList(allPools.id().toString());
}
@Override
public TokenHostConnectionPoolPartition<CL> getPartition(String token) {
return allPools;
}
@Override
public Map<String, TokenHostConnectionPoolPartition<CL>> getPartitions() {
return ImmutableMap.of(allPools.id().toString(), allPools);
}
}
| 7,706 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/TokenPartitionedTopology.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang.StringUtils;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
import com.netflix.astyanax.connectionpool.TokenRange;
import com.netflix.astyanax.partitioner.Partitioner;
/**
* Partition hosts by start token. Each token may map to a list of partitions. The class maintains 3 different data structures to represent {@link HostConnectionPool}s
* for a set of hosts in a partitioned ring.
*
* <ol>
* <li> <b> sortedRing </b> - the list of all pools for all hosts sorted in order specified by the token ranges for the cluster
* <li> <b> tokenToPartitionMap </b> - map of token range to host connection pools for that range
* <li> <b> allPools </b> - all pools for all known hosts in case no tokens can be found by calls such as ring describe etc
* </ol>
*
* <b> Prominent features of this class </b>
*
* <p>
* <b> Maintaining the set of pools for all hosts in a token ring </b>
* See the {@link #setPools(Collection)} method for details on how the various data structures are updated from a list of {@link HostConnectionPool}s
* Note that when host connection pools are set on this class, each host associated with the host conneciton pool can serve multiple partitions,
* hence this class builds a reverse index from token range -> list < HostConnectionPool> using this update.
* </p>
*
* <p>
* <b> Lookup all HostConnectionPools for a given row keyor token </b>
* See the {@link #getPartition(ByteBuffer)} method for details on how the various data structures are consulted for retrieving the comprehensive list of
* host connection pools for a row key. <br/>
* Note that if the token range token is provided directly, then we can directly consult the tokenPartitionMap. But if we receive a row key, then that is converted
* to an integer which is then used to do a bin search over the list of all sorted tokens in the token ring.
* </p>
*
*
* @author elandau
*
* @param <CL>
*
* @see {@link HostConnectionPoolPartition} for details of token ranges partition based connection pools maintained for each host.
*/
public class TokenPartitionedTopology<CL> implements Topology<CL> {
/**
* Sorted list of partitions. A binary search is performed on this list to determine
* the list of hosts that own the token range.
*/
private AtomicReference<List<TokenHostConnectionPoolPartition<CL>>> sortedRing
= new AtomicReference<List<TokenHostConnectionPoolPartition<CL>>>(new ArrayList<TokenHostConnectionPoolPartition<CL>>());
/**
* Lookup of end token to partition
*/
private NonBlockingHashMap<BigInteger, TokenHostConnectionPoolPartition<CL>> tokenToPartitionMap
= new NonBlockingHashMap<BigInteger, TokenHostConnectionPoolPartition<CL>>();
/**
* Partition which contains all hosts. This is the fallback partition when no tokens are provided.
*/
private TokenHostConnectionPoolPartition<CL> allPools;
/**
* Strategy used to score hosts within a partition.
*/
private LatencyScoreStrategy strategy;
/**
* Assume random partitioner, for now
*/
private final Partitioner partitioner;
/**
* Comparator used to find the partition mapping to a token
*/
@SuppressWarnings("rawtypes")
private Comparator tokenSearchComparator = new Comparator() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object arg0, Object arg1) {
TokenHostConnectionPoolPartition<CL> partition = (TokenHostConnectionPoolPartition<CL>) arg0;
BigInteger token = (BigInteger) arg1;
return partition.id().compareTo(token);
}
};
/**
* Compartor used to sort partitions in token order.
*/
@SuppressWarnings("rawtypes")
private Comparator partitionComparator = new Comparator() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object arg0, Object arg1) {
TokenHostConnectionPoolPartition<CL> partition0 = (TokenHostConnectionPoolPartition<CL>) arg0;
TokenHostConnectionPoolPartition<CL> partition1 = (TokenHostConnectionPoolPartition<CL>) arg1;
return partition0.id().compareTo(partition1.id());
}
};
public TokenPartitionedTopology(Partitioner partitioner, LatencyScoreStrategy strategy) {
this.strategy = strategy;
this.partitioner = partitioner;
this.allPools = new TokenHostConnectionPoolPartition<CL>(null, this.strategy);
}
protected TokenHostConnectionPoolPartition<CL> makePartition(BigInteger partition) {
return new TokenHostConnectionPoolPartition<CL>(partition, strategy);
}
@SuppressWarnings("unchecked")
@Override
/**
* Update the list of pools using the provided mapping of start token to collection of hosts
* that own the token
*/
public synchronized boolean setPools(Collection<HostConnectionPool<CL>> ring) {
boolean didChange = false;
Set<HostConnectionPool<CL>> allPools = Sets.newHashSet();
// Create a mapping of end token to a list of hosts that own the token
Map<BigInteger, List<HostConnectionPool<CL>>> tokenHostMap = Maps.newHashMap();
for (HostConnectionPool<CL> pool : ring) {
allPools.add(pool);
if (!this.allPools.hasPool(pool))
didChange = true;
for (TokenRange range : pool.getHost().getTokenRanges()) {
BigInteger endToken = new BigInteger(range.getEndToken());
List<HostConnectionPool<CL>> partition = tokenHostMap.get(endToken);
if (partition == null) {
partition = Lists.newArrayList();
tokenHostMap.put(endToken, partition);
}
partition.add(pool);
}
}
// Temporary list of token that will be removed if not found in the new ring
Set<BigInteger> tokensToRemove = Sets.newHashSet(tokenHostMap.keySet());
// Iterate all tokens
for (Entry<BigInteger, List<HostConnectionPool<CL>>> entry : tokenHostMap.entrySet()) {
BigInteger token = entry.getKey();
tokensToRemove.remove(token);
// Add a new partition or modify an existing one
TokenHostConnectionPoolPartition<CL> partition = tokenToPartitionMap.get(token);
if (partition == null) {
partition = makePartition(token);
tokenToPartitionMap.put(token, partition);
didChange = true;
}
if (partition.setPools(entry.getValue()))
didChange = true;
}
// Remove the tokens that are no longer in the ring
for (BigInteger token : tokensToRemove) {
tokenHostMap.remove(token);
didChange = true;
}
// Sort partitions by token
if (didChange) {
List<TokenHostConnectionPoolPartition<CL>> partitions = Lists.newArrayList(tokenToPartitionMap.values());
Collections.sort(partitions, partitionComparator);
this.allPools.setPools(allPools);
refresh();
this.sortedRing.set(Collections.unmodifiableList(partitions));
}
return didChange;
}
@Override
public synchronized void resumePool(HostConnectionPool<CL> pool) {
refresh();
}
@Override
public synchronized void suspendPool(HostConnectionPool<CL> pool) {
refresh();
}
@Override
public synchronized void refresh() {
allPools.refresh();
for (TokenHostConnectionPoolPartition<CL> partition : tokenToPartitionMap.values()) {
partition.refresh();
}
}
@Override
public TokenHostConnectionPoolPartition<CL> getPartition(String token) {
return tokenToPartitionMap.get(new BigInteger(token));
}
@Override
public TokenHostConnectionPoolPartition<CL> getPartition(ByteBuffer rowkey) {
if (rowkey == null)
return getAllPools();
BigInteger token = new BigInteger(partitioner.getTokenForKey(rowkey));
// First, get a copy of the partitions.
List<TokenHostConnectionPoolPartition<CL>> partitions = this.sortedRing.get();
// Must have a token otherwise we default to the base class
// implementation
if (token == null || partitions == null || partitions.isEmpty()) {
return getAllPools();
}
// Do a binary search to find the token partition which owns the
// token. We can get two responses here.
// 1. The token is in the list in which case the response is the
// index of the partition
// 2. The token is not in the list in which case the response is the
// index where the token would have been inserted into the list.
// We convert this index (which is negative) to the index of the
// previous position in the list.
@SuppressWarnings("unchecked")
int partitionIndex = Collections.binarySearch(partitions, token, tokenSearchComparator);
if (partitionIndex < 0) {
partitionIndex = -(partitionIndex + 1);
}
return partitions.get(partitionIndex % partitions.size());
}
@Override
public TokenHostConnectionPoolPartition<CL> getAllPools() {
return allPools;
}
@Override
public int getPartitionCount() {
return tokenToPartitionMap.size();
}
@Override
public synchronized void removePool(HostConnectionPool<CL> pool) {
allPools.removePool(pool);
for (TokenHostConnectionPoolPartition<CL> partition : tokenToPartitionMap.values()) {
partition.removePool(pool);
}
}
@Override
public synchronized void addPool(HostConnectionPool<CL> pool) {
allPools.addPool(pool);
}
@Override
public List<String> getPartitionNames() {
return Lists.newArrayList(Collections2.transform(tokenToPartitionMap.keySet(), new Function<BigInteger, String>() {
@Override
public String apply(BigInteger input) {
return input.toString();
}
}));
}
@Override
public Map<String, TokenHostConnectionPoolPartition<CL>> getPartitions() {
Map<String, TokenHostConnectionPoolPartition<CL>> result = Maps.newHashMap();
for (Entry<BigInteger, TokenHostConnectionPoolPartition<CL>> entry : tokenToPartitionMap.entrySet()) {
result.put(entry.getKey().toString(), entry.getValue());
}
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TokenPartitionTopology[");
sb.append(StringUtils.join(Lists.transform(this.sortedRing.get(), new Function<TokenHostConnectionPoolPartition<CL>, String>() {
@Override
public String apply(TokenHostConnectionPoolPartition<CL> input) {
return input.id().toString() + "\n";
}
}), ","));
sb.append("]");
return sb.toString();
}
}
| 7,707 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/OldHostSupplierAdapter.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.astyanax.connectionpool.Host;
public class OldHostSupplierAdapter implements Supplier<List<Host>> {
private final Supplier<Map<BigInteger, List<Host>>> source;
public OldHostSupplierAdapter(Supplier<Map<BigInteger, List<Host>>> source) {
this.source = source;
}
@Override
public List<Host> get() {
Map<BigInteger, List<Host>> tokenHostMap = source.get();
Set<Host> hosts = Sets.newHashSet();
for (Entry<BigInteger, List<Host>> entry : tokenHostMap.entrySet()) {
for (Host host : entry.getValue()) {
if (!hosts.contains(host)) {
hosts.add(host);
}
String token = entry.getKey().toString();
host.getTokenRanges().add(new TokenRangeImpl(token, token, null));
}
}
return Lists.newArrayList(hosts);
}
}
| 7,708 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/ConnectionPoolType.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import com.netflix.astyanax.connectionpool.ConnectionPool;
/**
* This is referenced from the AstyanaxContext.Builder class for instantiating the right {@link ConnectionPool}
* @author elandau
*
* @see {@link RoundRobinConnectionPoolImpl} {@link BagOfConnectionsConnectionPoolImpl} {@link TokenAwareConnectionPoolImpl} for different pool impls
* that correspond to this enum.
*/
public enum ConnectionPoolType {
TOKEN_AWARE, ROUND_ROBIN, BAG;
}
| 7,709 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/HostConnectionPoolPartition.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang.StringUtils;
import org.cliffc.high_scale_lib.NonBlockingHashSet;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
/**
* Collection of hosts that are grouped by a certain criteria (such as token or rack)
* The class maintains the list of active pools for the given criteria (such as a token range in a ring)
* Any changes to the pools in this partition causes the active set to be revised and sorted according to the latency score strategy provided. <br/> <br/>
*
* Note that an instance of this class is maintained / referenced for each token range partition by the {@link TokenPartitionedTopology} instance
*
* @author elandau
*
* @param <CL>
*
* @see {@link TokenPartitionedTopology} for details on how this class is referenced.
*/
public class HostConnectionPoolPartition<CL> {
protected final AtomicBoolean prioritize = new AtomicBoolean(false);
protected final NonBlockingHashSet<HostConnectionPool<CL>> pools = new NonBlockingHashSet<HostConnectionPool<CL>>();
protected final AtomicReference<List<HostConnectionPool<CL>>> activePools = new AtomicReference<List<HostConnectionPool<CL>>>();
protected final LatencyScoreStrategy strategy;
public HostConnectionPoolPartition(LatencyScoreStrategy strategy) {
this.strategy = strategy;
this.activePools.set(Lists.<HostConnectionPool<CL>>newArrayList());
}
/**
* Sets all pools for this partition. Removes old partitions and adds new
* one.
*
* @param newPools
*/
public synchronized boolean setPools(Collection<HostConnectionPool<CL>> newPools) {
Set<HostConnectionPool<CL>> toRemove = Sets.newHashSet(this.pools);
// Add new pools not previously seen
boolean didChange = false;
for (HostConnectionPool<CL> pool : newPools) {
if (this.pools.add(pool))
didChange = true;
toRemove.remove(pool);
}
// Remove pools for hosts that no longer exist
for (HostConnectionPool<CL> pool : toRemove) {
if (this.pools.remove(pool))
didChange = true;
}
if (didChange)
refresh();
return didChange;
}
/**
* Add a new pool to the partition. Checks to see if the pool already
* existed. If so then there is no need to refresh the pool.
* @param pool
* @return True if anything changed
*/
public synchronized boolean addPool(HostConnectionPool<CL> pool) {
if (this.pools.add(pool)) {
refresh();
return true;
}
return false;
}
public synchronized boolean removePool(HostConnectionPool<CL> pool) {
if (this.pools.remove(pool)) {
refresh();
return true;
}
return false;
}
/**
* @return Return the list of active hosts. Active hosts are those deemed by the
* latency score strategy to be alive and responsive.
*/
public List<HostConnectionPool<CL>> getPools() {
return activePools.get();
}
/**
* If true the the hosts are sorted by order of priority where the
* first host gives the best performance
*/
public boolean isSorted() {
return prioritize.get();
}
/**
* Returns true if a pool is contained in this partition
* @param pool
*/
public boolean hasPool(HostConnectionPool<CL> pool) {
return pools.contains(pool);
}
/**
* Refresh the partition
*/
public synchronized void refresh() {
List<HostConnectionPool<CL>> pools = Lists.newArrayList();
for (HostConnectionPool<CL> pool : this.pools) {
if (!pool.isReconnecting()) {
pools.add(pool);
}
}
this.activePools.set(strategy.sortAndfilterPartition(pools, prioritize));
}
public String toString() {
return new StringBuilder()
.append("BaseHostConnectionPoolPartition[")
.append(StringUtils.join(Collections2.transform(getPools(), new Function<HostConnectionPool<CL>, String>() {
@Override
public String apply(HostConnectionPool<CL> host) {
return host.getHost().getHostName();
}
}), ","))
.append("]")
.toString();
}
}
| 7,710 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/FixedRetryBackoffStrategy.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.RetryBackoffStrategy;
/**
* Impl for {@link RetryBackoffStrategy} that is used to reconnect a {@link HostConnectionPool} when a host is marked as down.
*
* @author elandau
* @see {@link SimpleHostConnectionPool#markAsDown(com.netflix.astyanax.connectionpool.exceptions.ConnectionException)} for details on how this class
* could be referenced (if needed)
*/
public class FixedRetryBackoffStrategy implements RetryBackoffStrategy {
private final int interval;
private final int suspendTime;
public FixedRetryBackoffStrategy(int interval, int suspendTime) {
this.interval = interval;
this.suspendTime = suspendTime;
}
@Override
public Instance createInstance() {
return new RetryBackoffStrategy.Instance() {
private boolean isSuspended = false;
private int attemptCount = 0;
@Override
public long getNextDelay() {
if (isSuspended) {
isSuspended = false;
return suspendTime;
}
return interval;
}
@Override
public int getAttemptCount() {
return attemptCount;
}
@Override
public void begin() {
attemptCount = 0;
}
@Override
public void success() {
}
@Override
public void suspend() {
}
};
}
}
| 7,711 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/Slf4jConnectionPoolMonitorImpl.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.exceptions.HostDownException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException;
/**
*
* Impl for {@link CountingConnectionPoolMonitor} that does not track any internal state / counters. It simply uses a logger to log out the events.
* Useful for debugging and basic event tracking.
*
* @author elandau
*
*/
public class Slf4jConnectionPoolMonitorImpl extends CountingConnectionPoolMonitor {
private static final Logger LOG = LoggerFactory.getLogger(Slf4jConnectionPoolMonitorImpl.class);
@Override
public void incOperationFailure(Host host, Exception reason) {
if (reason instanceof NotFoundException) {
// Ignore this
return;
}
super.incOperationFailure(host, reason);
LOG.warn(reason.getMessage());
}
@Override
public void incConnectionClosed(Host host, Exception reason) {
super.incConnectionClosed(host, reason);
if (reason != null) {
LOG.info(reason.getMessage());
}
}
@Override
public void incConnectionCreateFailed(Host host, Exception reason) {
super.incConnectionCreateFailed(host, reason);
if (reason != null) {
LOG.info(reason.getMessage());
}
}
@Override
public void incFailover(Host host, Exception reason) {
if (reason != null) {
if (reason instanceof HostDownException || reason instanceof PoolTimeoutException) {
// we don't need to log these
}
else {
LOG.warn(reason.getMessage());
}
}
super.incFailover(host, reason);
}
@Override
public void onHostAdded(Host host, HostConnectionPool<?> pool) {
super.onHostAdded(host, pool);
LOG.info("HostAdded: " + host);
}
@Override
public void onHostRemoved(Host host) {
super.onHostRemoved(host);
LOG.info("HostRemoved: " + host);
}
@Override
public void onHostDown(Host host, Exception reason) {
super.onHostDown(host, reason);
LOG.info("HostDown: " + host);
}
@Override
public void onHostReactivated(Host host, HostConnectionPool<?> pool) {
super.onHostReactivated(host, pool);
LOG.info("HostReactivated: " + host);
}
}
| 7,712 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractHostPartitionConnectionPool.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.ExecuteWithFailover;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy.Listener;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.TokenRange;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.OperationException;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.tracing.AstyanaxContext;
import com.netflix.astyanax.tracing.OperationTracer;
/**
* Base for all connection pools that keep a separate pool of connections for
* each host. <br/> <br/>
*
* <p>
* <b> Set of host connection pools </b> <br/>
* The class maintains the set of all {@link HostConnectionPool}s for all hosts in the token ring using a non blocking hashmap and a {@link Topology}
* The hashmap tracks the basic set of hosts and their corresponding connection pools. The topology is used to track the internal state of the token ring
* for the cassandra cluster. <br/>
* The class uses these 2 structures to determine whether there has been a change to the system when a host joins or leaves the ring,
* or even if an existing host just receives an update for the token ring partition that it owns. Hence the class can actively rebuild all the partitions
* associated with each as and when there is a change. <br/>
*
* See {@link #addHost(Host, boolean)} {@link #removeHost(Host, boolean)} {@link #setHosts(Collection)} for host changes and the corresponding trigger to {@link #rebuildPartitions()}
* when this happens. <br/>
*
* Note that when the connection pool is started it fetches the list of seed hosts from config (if any) and then inits it's data structures using these seed hosts. <br/>
* It also employs a listener to the latency score updates so that it can rebuild partitions as and when it receives updates
* </p>
*
* <p>
* <b> Execute with failover </b> <br/>
*
* The class also provides a basic implementation of {@link #executeWithFailover(Operation, RetryPolicy)} by repeatedly consulting the {@link RetryPolicy}. Note that extending classes
* must provide impl for the actual execute with failover. e.g the {@link RoundRobinConnectionPoolImpl} fails over to the next {@link HostConnectionPool} in the list.
* </p>
*
* @author elandau
*
* @param <CL>
*
* @see {@link RoundRobinConnectionPoolImpl} {@link BagOfConnectionsConnectionPoolImpl} {@link TokenAwareConnectionPoolImpl} for details on impls that extend this class
* @see {@link TokenPartitionedTopology} for how the internal topology structure is maintained across the set of hosts
*/
public abstract class AbstractHostPartitionConnectionPool<CL> implements ConnectionPool<CL>,
SimpleHostConnectionPool.Listener<CL> {
private static Logger LOG = LoggerFactory.getLogger(AbstractHostPartitionConnectionPool.class);
protected final NonBlockingHashMap<Host, HostConnectionPool<CL>> hosts;
protected final ConnectionPoolConfiguration config;
protected final ConnectionFactory<CL> factory;
protected final ConnectionPoolMonitor monitor;
protected final Topology<CL> topology;
protected final Partitioner partitioner;
/**
* @param config
* @param factory
* @param monitor
*/
public AbstractHostPartitionConnectionPool(ConnectionPoolConfiguration config, ConnectionFactory<CL> factory,
ConnectionPoolMonitor monitor) {
this.config = config;
this.factory = factory;
this.monitor = monitor;
this.hosts = new NonBlockingHashMap<Host, HostConnectionPool<CL>>();
this.topology = new TokenPartitionedTopology<CL>(config.getPartitioner(), config.getLatencyScoreStrategy());
this.partitioner = config.getPartitioner();
}
/**
* Starts the conn pool and resources associated with it
*/
@Override
public void start() {
ConnectionPoolMBeanManager.getInstance().registerMonitor(config.getName(), this);
String seeds = config.getSeeds();
if (seeds != null && !seeds.isEmpty()) {
setHosts(config.getSeedHosts());
}
config.getLatencyScoreStrategy().start(new Listener() {
@Override
public void onUpdate() {
rebuildPartitions();
}
@Override
public void onReset() {
rebuildPartitions();
}
});
}
/**
* Clean up resources associated with the conn pool
*/
@Override
public void shutdown() {
ConnectionPoolMBeanManager.getInstance().unregisterMonitor(config.getName(), this);
for (Entry<Host, HostConnectionPool<CL>> pool : hosts.entrySet()) {
pool.getValue().shutdown();
}
config.getLatencyScoreStrategy().shutdown();
config.shutdown();
}
protected HostConnectionPool<CL> newHostConnectionPool(Host host, ConnectionFactory<CL> factory,
ConnectionPoolConfiguration config) {
return new SimpleHostConnectionPool<CL>(host, factory, monitor, config, this);
}
/**
* Host is marked as down
* @param pool
*/
@Override
public void onHostDown(HostConnectionPool<CL> pool) {
topology.suspendPool(pool);
}
/**
* Host is marked as up
* @param pool
*/
@Override
public void onHostUp(HostConnectionPool<CL> pool) {
topology.resumePool(pool);
}
private static Comparator<TokenRange> compareByStartToken = new Comparator<TokenRange>() {
@Override
public int compare(TokenRange p1, TokenRange p2) {
return p1.getStartToken().compareTo(p2.getStartToken());
}
};
/**
* Add host to the system. May need to rebuild the partition map of the system
* @param host
* @param refresh
*/
@Override
public final synchronized boolean addHost(Host host, boolean refresh) {
// Already exists
if (hosts.containsKey(host)) {
// Check to see if we are adding token ranges or if the token ranges changed
// which will force a rebuild of the token topology
Host existingHost = hosts.get(host).getHost();
if (existingHost.getTokenRanges().size() != host.getTokenRanges().size()) {
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
ArrayList<TokenRange> currentTokens = Lists.newArrayList(existingHost.getTokenRanges());
ArrayList<TokenRange> newTokens = Lists.newArrayList(host.getTokenRanges());
Collections.sort(currentTokens, compareByStartToken);
Collections.sort(newTokens, compareByStartToken);
for (int i = 0; i < currentTokens.size(); i++) {
if (!currentTokens.get(i).getStartToken().equals(newTokens.get(i).getStartToken()) ||
!currentTokens.get(i).getEndToken().equals(newTokens.get(i).getEndToken())) {
return false;
}
}
existingHost.setTokenRanges(host.getTokenRanges());
return true;
}
else {
HostConnectionPool<CL> pool = newHostConnectionPool(host, factory, config);
if (null == hosts.putIfAbsent(host, pool)) {
try {
monitor.onHostAdded(host, pool);
if (refresh) {
topology.addPool(pool);
rebuildPartitions();
}
pool.primeConnections(config.getInitConnsPerHost());
}
catch (Exception e) {
// Ignore, pool will have been marked down internally
}
return true;
}
else {
return false;
}
}
}
/**
* @return boolean
*/
@Override
public boolean isHostUp(Host host) {
HostConnectionPool<CL> pool = hosts.get(host);
if (pool != null) {
return !pool.isReconnecting();
}
return false;
}
/**
* @return boolean
*/
@Override
public boolean hasHost(Host host) {
return hosts.containsKey(host);
}
/**
* list of all active pools
* @return {@link List<HostConnectionPool>}
*/
@Override
public List<HostConnectionPool<CL>> getActivePools() {
return ImmutableList.copyOf(topology.getAllPools().getPools());
}
/**
* @return {@link List<HostConnectionPool>}
*/
@Override
public List<HostConnectionPool<CL>> getPools() {
return ImmutableList.copyOf(hosts.values());
}
/**
* Remove host from the system. Shuts down pool associated with the host and rebuilds partition map
* @param host
* @param refresh
*/
@Override
public synchronized boolean removeHost(Host host, boolean refresh) {
HostConnectionPool<CL> pool = hosts.remove(host);
if (pool != null) {
topology.removePool(pool);
rebuildPartitions();
monitor.onHostRemoved(host);
pool.shutdown();
return true;
}
else {
return false;
}
}
/**
* @param host
* @return {@link HostConnectionPool}
*/
@Override
public HostConnectionPool<CL> getHostPool(Host host) {
return hosts.get(host);
}
/**
* @param ring
*/
@Override
public synchronized void setHosts(Collection<Host> ring) {
// Temporary list of hosts to remove. Any host not in the new ring will
// be removed
Set<Host> hostsToRemove = Sets.newHashSet(hosts.keySet());
// Add new hosts.
boolean changed = false;
for (Host host : ring) {
if (addHost(host, false))
changed = true;
hostsToRemove.remove(host);
}
// Remove any hosts that are no longer in the ring
for (Host host : hostsToRemove) {
removeHost(host, false);
changed = true;
}
if (changed) {
topology.setPools(hosts.values());
rebuildPartitions();
}
}
/**
* Executes the operation using failover and retry strategy
* @param op
* @param retry
* @return {@link OperationResult}
*/
@Override
public <R> OperationResult<R> executeWithFailover(Operation<CL, R> op, RetryPolicy retry)
throws ConnectionException {
//Tracing operation
OperationTracer opsTracer = config.getOperationTracer();
final AstyanaxContext context = opsTracer.getAstyanaxContext();
if(context != null) {
opsTracer.onCall(context, op);
}
retry.begin();
ConnectionException lastException = null;
do {
try {
OperationResult<R> result = newExecuteWithFailover(op).tryOperation(op);
retry.success();
if(context != null)
opsTracer.onSuccess(context, op);
return result;
}
catch (OperationException e) {
if(context != null)
opsTracer.onException(context, op, e);
retry.failure(e);
throw e;
}
catch (ConnectionException e) {
lastException = e;
}
if (retry.allowRetry()) {
LOG.debug("Retry policy[" + retry.toString() + "] will allow a subsequent retry for operation [" + op.getClass() +
"] on keyspace [" + op.getKeyspace() + "] on pinned host[" + op.getPinnedHost() + "]");
}
} while (retry.allowRetry());
if(context != null && lastException != null)
opsTracer.onException(context, op, lastException);
retry.failure(lastException);
throw lastException;
}
/**
* Return a new failover context. The context captures the connection pool
* state and implements the necessary failover logic.
*
* @param <R>
* @return
* @throws ConnectionException
*/
protected abstract <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> op)
throws ConnectionException;
/**
* Called every time a host is added, removed or is marked as down
*/
protected void rebuildPartitions() {
topology.refresh();
}
/**
* @return {@link Topology}
*/
public Topology<CL> getTopology() {
return topology;
}
/**
* @return {@link Partitioner}
*/
public Partitioner getPartitioner() {
return this.partitioner;
}
}
| 7,713 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleHostConnectionPool.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.netflix.astyanax.connectionpool.BadHostDetector;
import com.netflix.astyanax.connectionpool.Connection;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
import com.netflix.astyanax.connectionpool.RetryBackoffStrategy;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.InterruptedOperationException;
import com.netflix.astyanax.connectionpool.exceptions.HostDownException;
import com.netflix.astyanax.connectionpool.exceptions.IsDeadConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.ThrottledException;
import com.netflix.astyanax.connectionpool.exceptions.TimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.UnknownException;
/**
* Pool of connections for a single host and implements the {@link HostConnectionPool} interface
*
* <p>
* <b>Salient Features </b> <br/> <br/>
*
* The class provides a bunch of counters for visibility into the connection pool status e.g no of
* that are available / active / pending / blocked etc. </br> </br>
*
* This class also provides an async mechanism to create / prime and borrow {@link Connection}(s) using a {@link LinkedBlockingQueue} <br/>
* Clients borrowing connections can wait at the end of the queue for a connection to be available. They send a {@link SimpleHostConnectionPool#tryOpenAsync()} request
* to create a new connection before waiting, but don't necessarily wait for the same connection to be opened, since they could be unblocked by
* another client returning a previously used {@link Connection}
*
* The class also provides a {@link SimpleHostConnectionPool#markAsDown(ConnectionException)} method which helps purge all connections and then
* attempts to init a new set of connections to the host.
*
* </p>
*
* @author elandau
*
*/
public class SimpleHostConnectionPool<CL> implements HostConnectionPool<CL> {
private final static Logger LOG = LoggerFactory.getLogger(SimpleHostConnectionPool.class);
private final static int MAX_PRIME_CONNECTIONS_RETRY_ATTEMPT = 2;
private final static int PRIME_CONNECTION_DELAY = 100;
/**
* Interface to notify the owning connection pool of up/down state changes.
* This give the owning connection pool a chance to remove a downed host
* from its internal state until it's back up.
*
* @author elandau
*
* @param <CL>
*/
public interface Listener<CL> {
void onHostDown(HostConnectionPool<CL> pool);
void onHostUp(HostConnectionPool<CL> pool);
}
private static final AtomicLong poolIdCounter = new AtomicLong(0);
private final long id = poolIdCounter.incrementAndGet();
private final BlockingQueue<Connection<CL>> availableConnections;
private final AtomicInteger activeCount = new AtomicInteger(0);
private final AtomicInteger pendingConnections = new AtomicInteger(0);
private final AtomicInteger blockedThreads = new AtomicInteger(0);
private final AtomicInteger openConnections = new AtomicInteger(0);
private final AtomicInteger failedOpenConnections= new AtomicInteger(0);
private final AtomicInteger closedConnections = new AtomicInteger(0);
private final AtomicLong borrowedCount = new AtomicLong(0);
private final AtomicLong returnedCount = new AtomicLong(0);
private final AtomicInteger connectAttempt = new AtomicInteger(0);
private final AtomicInteger markedDownCount = new AtomicInteger(0);
private final AtomicInteger errorsSinceLastSuccess = new AtomicInteger(0);
private final ConnectionFactory<CL> factory;
private final Host host;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);
private final AtomicBoolean isReconnecting = new AtomicBoolean(false);
private final ScheduledExecutorService executor;
private final RetryBackoffStrategy.Instance retryContext;
private final BadHostDetector.Instance badHostDetector;
private final LatencyScoreStrategy.Instance latencyStrategy;
private final Listener<CL> listener;
private final ConnectionPoolMonitor monitor;
protected final ConnectionPoolConfiguration config;
public SimpleHostConnectionPool(Host host, ConnectionFactory<CL> factory, ConnectionPoolMonitor monitor,
ConnectionPoolConfiguration config, Listener<CL> listener) {
this.host = host;
this.config = config;
this.factory = factory;
this.listener = listener;
this.retryContext = config.getRetryBackoffStrategy().createInstance();
this.latencyStrategy = config.getLatencyScoreStrategy().createInstance();
this.badHostDetector = config.getBadHostDetector().createInstance();
this.monitor = monitor;
this.availableConnections = new LinkedBlockingQueue<Connection<CL>>();
this.executor = config.getHostReconnectExecutor();
Preconditions.checkNotNull(config.getHostReconnectExecutor(), "HostReconnectExecutor cannot be null");
}
@Override
public int primeConnections(int numConnections) throws ConnectionException, InterruptedException {
if (isReconnecting()) {
throw new HostDownException("Can't prime connections on downed host.");
}
// Don't try to create more than we're allowed
int remaining = Math.min(numConnections, config.getMaxConnsPerHost() - getActiveConnectionCount());
// Attempt to open 'count' connections and allow for MAX_PRIME_CONNECTIONS_RETRY_ATTEMPT
// retries before giving up if we can't open more.
int opened = 0;
Exception lastException = null;
for (int i = 0; opened < remaining && i < MAX_PRIME_CONNECTIONS_RETRY_ATTEMPT;) {
try {
reconnect();
opened++;
}
catch (Exception e) {
lastException = e;
Thread.sleep(PRIME_CONNECTION_DELAY);
i++;
}
}
// If no connection was opened then mark this host as down
if (remaining > 0 && opened == 0) {
this.markAsDown(null);
throw new HostDownException("Failed to prime connections", lastException);
}
return opened;
}
/**
* Create a connection as long the max hasn't been reached
*
* @param timeout
* - Max wait timeout if max connections have been allocated and
* pool is empty. 0 to throw a MaxConnsPerHostReachedException.
* @return
* @throws TimeoutException
* if timeout specified and no new connection is available
* MaxConnsPerHostReachedException if max connections created
* and no timeout was specified
*/
@Override
public Connection<CL> borrowConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
// Try to get a free connection without blocking.
connection = availableConnections.poll();
if (connection != null) {
return connection;
}
boolean isOpenning = tryOpenAsync();
// Wait for a connection to free up or a new one to be opened
if (timeout > 0) {
connection = waitForConnection(isOpenning ? config.getConnectTimeout() : timeout);
return connection;
}
else
throw new PoolTimeoutException("Fast fail waiting for connection from pool")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
if (connection != null) {
borrowedCount.incrementAndGet();
monitor.incConnectionBorrowed(host, System.currentTimeMillis() - startTime);
}
}
}
/**
* Internal method to wait for a connection from the available connection
* pool.
*
* @param timeout
* @return
* @throws ConnectionException
*/
private Connection<CL> waitForConnection(int timeout) throws ConnectionException {
Connection<CL> connection = null;
long startTime = System.currentTimeMillis();
try {
blockedThreads.incrementAndGet();
connection = availableConnections.poll(timeout, TimeUnit.MILLISECONDS);
if (connection != null)
return connection;
throw new PoolTimeoutException("Timed out waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedOperationException("Thread interrupted waiting for connection")
.setHost(getHost())
.setLatency(System.currentTimeMillis() - startTime);
}
finally {
blockedThreads.decrementAndGet();
}
}
/**
* Return a connection to this host
*
* @param connection
*/
@Override
public boolean returnConnection(Connection<CL> connection) {
returnedCount.incrementAndGet();
monitor.incConnectionReturned(host);
ConnectionException ce = connection.getLastException();
if (ce != null) {
if (ce instanceof IsDeadConnectionException) {
noteError(ce);
internalCloseConnection(connection);
return true;
}
}
errorsSinceLastSuccess.set(0);
// Still within the number of max active connection
if (activeCount.get() <= config.getMaxConnsPerHost()) {
availableConnections.add(connection);
if (isShutdown()) {
discardIdleConnections();
return true;
}
}
else {
// maxConnsPerHost was reduced. This may end up closing too many
// connections, but that's ok. We'll open them later.
internalCloseConnection(connection);
return true;
}
return false;
}
@Override
public boolean closeConnection(Connection<CL> connection) {
returnedCount.incrementAndGet();
monitor.incConnectionReturned(host);
internalCloseConnection(connection);
return true;
}
private void internalCloseConnection(Connection<CL> connection) {
try {
closedConnections.incrementAndGet();
connection.close();
}
finally {
activeCount.decrementAndGet();
}
}
private void noteError(ConnectionException reason) {
if (errorsSinceLastSuccess.incrementAndGet() > 3)
markAsDown(reason);
}
/**
* Mark the host as down. No new connections will be created from this host.
* Connections currently in use will be allowed to continue processing.
*/
@Override
public void markAsDown(ConnectionException reason) {
// Make sure we're not triggering the reconnect process more than once
if (isReconnecting.compareAndSet(false, true)) {
markedDownCount.incrementAndGet();
if (reason != null && !(reason instanceof TimeoutException)) {
discardIdleConnections();
}
listener.onHostDown(this);
monitor .onHostDown(getHost(), reason);
retryContext.begin();
try {
long delay = retryContext.getNextDelay();
executor.schedule(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("RetryService : " + host.getName());
try {
if (activeCount.get() == 0)
reconnect();
// Created a new connection successfully.
try {
retryContext.success();
if (isReconnecting.compareAndSet(true, false)) {
monitor .onHostReactivated(host, SimpleHostConnectionPool.this);
listener.onHostUp(SimpleHostConnectionPool.this);
}
}
catch (Throwable t) {
LOG.error("Error reconnecting client", t);
}
return;
}
catch (Throwable t) {
// Ignore
//t.printStackTrace();
}
if (!isShutdown()) {
long delay = retryContext.getNextDelay();
executor.schedule(this, delay, TimeUnit.MILLISECONDS);
}
}
}, delay, TimeUnit.MILLISECONDS);
}
catch (Exception e) {
LOG.error("Failed to schedule retry task for " + host.getHostName(), e);
}
}
}
private void reconnect() throws Exception {
try {
if (activeCount.get() < config.getMaxConnsPerHost()) {
if (activeCount.incrementAndGet() <= config.getMaxConnsPerHost()) {
connectAttempt.incrementAndGet();
Connection<CL> connection = factory.createConnection(SimpleHostConnectionPool.this);
connection.open();
errorsSinceLastSuccess.set(0);
availableConnections.add(connection);
openConnections.incrementAndGet();
}
else {
activeCount.decrementAndGet();
}
}
}
catch (ConnectionException e) {
failedOpenConnections.incrementAndGet();
activeCount.decrementAndGet();
noteError(e);
throw e;
}
catch (Throwable t) {
failedOpenConnections.incrementAndGet();
activeCount.decrementAndGet();
ConnectionException ce = new UnknownException(t);
noteError(ce);
throw ce;
}
}
@Override
public void shutdown() {
isReconnecting.set(true);
isShutdown.set(true);
discardIdleConnections();
config.getLatencyScoreStrategy().removeInstance(this.latencyStrategy);
config.getBadHostDetector().removeInstance(this.badHostDetector);
}
/**
* Try to open a new connection asynchronously. We don't actually return a
* connection here. Instead, the connection will be added to idle queue when
* it's ready.
*/
private boolean tryOpenAsync() {
Connection<CL> connection = null;
// Try to open a new connection, as long as we haven't reached the max
if (activeCount.get() < config.getMaxConnsPerHost()) {
try {
if (activeCount.incrementAndGet() <= config.getMaxConnsPerHost()) {
// Don't try to open too many connections at the same time.
if (pendingConnections.incrementAndGet() > config.getMaxPendingConnectionsPerHost()) {
pendingConnections.decrementAndGet();
}
else {
try {
connectAttempt.incrementAndGet();
connection = factory.createConnection(this);
connection.openAsync(new Connection.AsyncOpenCallback<CL>() {
@Override
public void success(Connection<CL> connection) {
openConnections.incrementAndGet();
pendingConnections.decrementAndGet();
availableConnections.add(connection);
// Sanity check in case the connection
// pool was closed
if (isShutdown()) {
discardIdleConnections();
}
}
@Override
public void failure(Connection<CL> conn, ConnectionException e) {
failedOpenConnections.incrementAndGet();
pendingConnections.decrementAndGet();
activeCount.decrementAndGet();
if (e instanceof IsDeadConnectionException) {
noteError(e);
}
}
});
return true;
}
catch (ThrottledException e) {
// Trying to open way too many connections here
}
finally {
if (connection == null)
pendingConnections.decrementAndGet();
}
}
}
}
finally {
if (connection == null) {
activeCount.decrementAndGet();
}
}
}
return false;
}
@Override
public boolean isShutdown() {
return isShutdown.get();
}
public boolean isReconnecting() {
return isReconnecting.get();
}
@Override
public Host getHost() {
return host;
}
@Override
public int getActiveConnectionCount() {
return activeCount.get();
}
@Override
public int getIdleConnectionCount() {
return availableConnections.size();
}
@Override
public int getPendingConnectionCount() {
return pendingConnections.get();
}
@Override
public int getBlockedThreadCount() {
return blockedThreads.get();
}
@Override
public int getOpenedConnectionCount() {
return openConnections.get();
}
@Override
public int getFailedOpenConnectionCount() {
return failedOpenConnections.get();
}
@Override
public int getClosedConnectionCount() {
return closedConnections.get();
}
@Override
public int getConnectAttemptCount() {
return this.connectAttempt.get();
}
@Override
public int getBusyConnectionCount() {
return getActiveConnectionCount() - getIdleConnectionCount() - getPendingConnectionCount();
}
@Override
public double getScore() {
return latencyStrategy.getScore();
}
@Override
public void addLatencySample(long latency, long now) {
latencyStrategy.addSample(latency);
}
@Override
public int getErrorsSinceLastSuccess() {
return errorsSinceLastSuccess.get();
}
/**
* Drain all idle connections and close them. Connections that are currently borrowed
* will not be closed here.
*/
private void discardIdleConnections() {
List<Connection<CL>> connections = Lists.newArrayList();
availableConnections.drainTo(connections);
activeCount.addAndGet(-connections.size());
for (Connection<CL> connection : connections) {
try {
closedConnections.incrementAndGet();
connection.close(); // This is usually an async operation
}
catch (Throwable t) {
// TODO
}
}
}
public String toString() {
int idle = getIdleConnectionCount();
int open = getActiveConnectionCount();
return new StringBuilder()
.append("SimpleHostConnectionPool[")
.append("host=" ).append(host).append("-").append(id)
.append(",down=" ).append(markedDownCount.get())
.append(",active=" ).append(!isShutdown())
.append(",recon=" ).append(isReconnecting())
.append(",connections(")
.append( "open=" ).append(open)
.append( ",idle=" ).append(idle)
.append( ",busy=" ).append(open - idle)
.append( ",closed=").append(closedConnections.get())
.append( ",failed=").append(failedOpenConnections.get())
.append(")")
.append(",borrow=" ).append(borrowedCount.get())
.append(",return=" ).append(returnedCount.get())
.append(",blocked=").append(getBlockedThreadCount())
.append(",pending=").append(getPendingConnectionCount())
.append(",score=" ).append(TimeUnit.MILLISECONDS.convert((long)getScore(), TimeUnit.NANOSECONDS))
.append("]").toString();
}
@Override
public boolean isActive() {
return !this.isShutdown.get();
}
}
| 7,714 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/CountingConnectionPoolMonitor.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.HostStats;
import com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.TimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.BadRequestException;
import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException;
import com.netflix.astyanax.connectionpool.exceptions.OperationTimeoutException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.connectionpool.exceptions.HostDownException;
import com.netflix.astyanax.connectionpool.exceptions.TransportException;
import com.netflix.astyanax.connectionpool.exceptions.InterruptedOperationException;
/**
*
* Impl for {@link ConnectionPoolMonitor} that employs counters to track stats such as
*
* <ol>
* <li> operation success / failures / timeouts / socket timeouts / interrupted </li>
* <li> connection created / borrowed / returned / closed / create failures </li>
* <li> hosts added / removed / marked as down / reactivated </li>
* <li> transport failures and other useful stats </li>
* </ol>
*
* @author elandau
*/
public class CountingConnectionPoolMonitor implements ConnectionPoolMonitor {
private static Logger LOG = LoggerFactory.getLogger(CountingConnectionPoolMonitor.class);
private AtomicLong operationFailureCount = new AtomicLong();
private AtomicLong operationSuccessCount = new AtomicLong();
private AtomicLong connectionCreateCount = new AtomicLong();
private AtomicLong connectionClosedCount = new AtomicLong();
private AtomicLong connectionCreateFailureCount = new AtomicLong();
private AtomicLong connectionBorrowCount = new AtomicLong();
private AtomicLong connectionReturnCount = new AtomicLong();
private AtomicLong operationFailoverCount = new AtomicLong();
private AtomicLong hostAddedCount = new AtomicLong();
private AtomicLong hostRemovedCount = new AtomicLong();
private AtomicLong hostDownCount = new AtomicLong();
private AtomicLong hostReactivatedCount = new AtomicLong();
private AtomicLong poolExhastedCount = new AtomicLong();
private AtomicLong operationTimeoutCount = new AtomicLong();
private AtomicLong socketTimeoutCount = new AtomicLong();
private AtomicLong noHostsCount = new AtomicLong();
private AtomicLong unknownErrorCount = new AtomicLong();
private AtomicLong badRequestCount = new AtomicLong();
private AtomicLong interruptedCount = new AtomicLong();
private AtomicLong transportErrorCount = new AtomicLong();
private AtomicLong notFoundCounter = new AtomicLong();
public CountingConnectionPoolMonitor() {
}
private void trackError(Host host, Exception reason) {
if (reason instanceof PoolTimeoutException) {
this.poolExhastedCount.incrementAndGet();
}
else if (reason instanceof TimeoutException) {
this.socketTimeoutCount.incrementAndGet();
}
else if (reason instanceof OperationTimeoutException) {
this.operationTimeoutCount.incrementAndGet();
}
else if (reason instanceof BadRequestException) {
this.badRequestCount.incrementAndGet();
}
else if (reason instanceof NoAvailableHostsException ) {
this.noHostsCount.incrementAndGet();
}
else if (reason instanceof InterruptedOperationException) {
this.interruptedCount.incrementAndGet();
}
else if (reason instanceof HostDownException) {
this.hostDownCount.incrementAndGet();
}
else if (reason instanceof TransportException) {
this.transportErrorCount.incrementAndGet();
}
else {
LOG.error(reason.toString(), reason);
this.unknownErrorCount.incrementAndGet();
}
}
@Override
public void incOperationFailure(Host host, Exception reason) {
if (reason instanceof NotFoundException) {
this.notFoundCounter.incrementAndGet();
return;
}
this.operationFailureCount.incrementAndGet();
trackError(host, reason);
}
public long getOperationFailureCount() {
return this.operationFailureCount.get();
}
@Override
public void incOperationSuccess(Host host, long latency) {
this.operationSuccessCount.incrementAndGet();
}
public long getOperationSuccessCount() {
return this.operationSuccessCount.get();
}
@Override
public void incConnectionCreated(Host host) {
this.connectionCreateCount.incrementAndGet();
}
public long getConnectionCreatedCount() {
return this.connectionCreateCount.get();
}
@Override
public void incConnectionClosed(Host host, Exception reason) {
this.connectionClosedCount.incrementAndGet();
}
public long getConnectionClosedCount() {
return this.connectionClosedCount.get();
}
@Override
public void incConnectionCreateFailed(Host host, Exception reason) {
this.connectionCreateFailureCount.incrementAndGet();
}
public long getConnectionCreateFailedCount() {
return this.connectionCreateFailureCount.get();
}
@Override
public void incConnectionBorrowed(Host host, long delay) {
this.connectionBorrowCount.incrementAndGet();
}
public long getConnectionBorrowedCount() {
return this.connectionBorrowCount.get();
}
@Override
public void incConnectionReturned(Host host) {
this.connectionReturnCount.incrementAndGet();
}
public long getConnectionReturnedCount() {
return this.connectionReturnCount.get();
}
public long getPoolExhaustedTimeoutCount() {
return this.poolExhastedCount.get();
}
@Override
public long getSocketTimeoutCount() {
return this.socketTimeoutCount.get();
}
public long getOperationTimeoutCount() {
return this.operationTimeoutCount.get();
}
@Override
public void incFailover(Host host, Exception reason) {
this.operationFailoverCount.incrementAndGet();
trackError(host, reason);
}
@Override
public long getFailoverCount() {
return this.operationFailoverCount.get();
}
@Override
public void onHostAdded(Host host, HostConnectionPool<?> pool) {
LOG.info("AddHost: " + host.getHostName());
this.hostAddedCount.incrementAndGet();
}
@Override
public long getHostAddedCount() {
return this.hostAddedCount.get();
}
@Override
public void onHostRemoved(Host host) {
LOG.info("RemoveHost: " + host.getHostName());
this.hostRemovedCount.incrementAndGet();
}
@Override
public long getHostRemovedCount() {
return this.hostRemovedCount.get();
}
@Override
public void onHostDown(Host host, Exception reason) {
this.hostDownCount.incrementAndGet();
}
@Override
public long getHostDownCount() {
return this.hostDownCount.get();
}
@Override
public void onHostReactivated(Host host, HostConnectionPool<?> pool) {
LOG.info("Reactivating " + host.getHostName());
this.hostReactivatedCount.incrementAndGet();
}
public long getHostReactivatedCount() {
return this.hostReactivatedCount.get();
}
@Override
public long getNoHostCount() {
return this.noHostsCount.get();
}
@Override
public long getUnknownErrorCount() {
return this.unknownErrorCount.get();
}
@Override
public long getInterruptedCount() {
return this.interruptedCount.get();
}
@Override
public long getTransportErrorCount() {
return this.transportErrorCount.get();
}
@Override
public long getBadRequestCount() {
return this.badRequestCount.get();
}
public long getNumBusyConnections() {
return this.connectionBorrowCount.get() - this.connectionReturnCount.get();
}
public long getNumOpenConnections() {
return this.connectionCreateCount.get() - this.connectionClosedCount.get();
}
@Override
public long notFoundCount() {
return this.notFoundCounter.get();
}
@Override
public long getHostCount() {
return getHostAddedCount() - getHostRemovedCount();
}
@Override
public long getHostActiveCount() {
return hostAddedCount.get() - hostRemovedCount.get() + hostReactivatedCount.get() - hostDownCount.get();
}
public String toString() {
// Build the complete status string
return new StringBuilder()
.append("CountingConnectionPoolMonitor(")
.append("Connections[" )
.append( "open=" ).append(getNumOpenConnections())
.append(",busy=" ).append(getNumBusyConnections())
.append(",create=" ).append(connectionCreateCount.get())
.append(",close=" ).append(connectionClosedCount.get())
.append(",failed=" ).append(connectionCreateFailureCount.get())
.append(",borrow=" ).append(connectionBorrowCount.get())
.append(",return=" ).append(connectionReturnCount.get())
.append("], Operations[")
.append( "success=" ).append(operationSuccessCount.get())
.append(",failure=" ).append(operationFailureCount.get())
.append(",optimeout=" ).append(operationTimeoutCount.get())
.append(",timeout=" ).append(socketTimeoutCount.get())
.append(",failover=" ).append(operationFailoverCount.get())
.append(",nohosts=" ).append(noHostsCount.get())
.append(",unknown=" ).append(unknownErrorCount.get())
.append(",interrupted=").append(interruptedCount.get())
.append(",exhausted=" ).append(poolExhastedCount.get())
.append(",transport=" ).append(transportErrorCount.get())
.append("], Hosts[")
.append( "add=" ).append(hostAddedCount.get())
.append(",remove=" ).append(hostRemovedCount.get())
.append(",down=" ).append(hostDownCount.get())
.append(",reactivate=" ).append(hostReactivatedCount.get())
.append(",active=" ).append(getHostActiveCount())
.append("])").toString();
}
@Override
public Map<Host, HostStats> getHostStats() {
throw new UnsupportedOperationException("Not supported");
}
}
| 7,715 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/BadHostDetectorImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.concurrent.LinkedBlockingQueue;
import com.netflix.astyanax.connectionpool.BadHostDetector;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
/**
* BadHostDetector which marks the host as failed if there is a transport
* exception or if it timed out too many times within a certain time window
*
* @author elandau
*
*/
public class BadHostDetectorImpl implements BadHostDetector {
private final LinkedBlockingQueue<Long> timeouts;
private final ConnectionPoolConfiguration config;
public BadHostDetectorImpl(ConnectionPoolConfiguration config) {
this.timeouts = new LinkedBlockingQueue<Long>();
this.config = config;
}
public String toString() {
return new StringBuilder()
.append("BadHostDetectorImpl[")
.append("count=").append(config.getMaxTimeoutCount())
.append(",window=").append(config.getTimeoutWindow())
.append("]")
.toString();
}
@Override
public Instance createInstance() {
return new Instance() {
@Override
public boolean addTimeoutSample() {
long currentTimeMillis = System.currentTimeMillis();
timeouts.add(currentTimeMillis);
// Determine if the host exceeded timeoutCounter exceptions in
// the timeoutWindow, in which case this is determined to be a
// failure
if (timeouts.size() > config.getMaxTimeoutCount()) {
Long last = timeouts.remove();
if ((currentTimeMillis - last.longValue()) < config.getTimeoutWindow()) {
return true;
}
}
return false;
}
};
}
@Override
public void removeInstance(Instance instance) {
// NOOP
}
}
| 7,716 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractLatencyScoreStrategyImpl.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.cliffc.high_scale_lib.NonBlockingHashSet;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.LatencyScoreStrategy;
/**
* @author elandau
*/
public abstract class AbstractLatencyScoreStrategyImpl implements LatencyScoreStrategy {
public static final int DEFAULT_UPDATE_INTERVAL = 1000;
public static final int DEFAULT_RESET_INTERVAL = 0;
public static final int DEFAULT_BLOCKED_THREAD_THRESHOLD = 10;
public static final double DEFAULT_KEEP_RATIO = 0.65;
public static final double DEFAULT_SCORE_THRESHOLD = 2.0;
private final ScheduledExecutorService executor;
private final Set<Instance> instances;
private final int updateInterval;
private final int resetInterval;
private final double scoreThreshold;
private final int blockedThreshold;
private final String name;
private final double keepRatio;
private boolean bOwnedExecutor = false;
public AbstractLatencyScoreStrategyImpl(String name, int updateInterval, int resetInterval, int blockedThreshold, double keepRatio, double scoreThreshold, ScheduledExecutorService executor) {
this.updateInterval = updateInterval;
this.resetInterval = resetInterval;
this.name = name;
this.scoreThreshold = scoreThreshold;
this.blockedThreshold = blockedThreshold;
this.keepRatio = keepRatio;
this.executor = executor;
this.instances = new NonBlockingHashSet<Instance>();
}
/**
*
* @param name
* @param updateInterval In milliseconds
* @param resetInterval In milliseconds
*/
public AbstractLatencyScoreStrategyImpl(String name, int updateInterval, int resetInterval, int blockedThreshold, double keepRatio, double scoreThreshold) {
this(name, updateInterval, resetInterval, blockedThreshold, keepRatio, scoreThreshold, Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).build()));
bOwnedExecutor = true;
}
public AbstractLatencyScoreStrategyImpl(String name, int updateInterval, int resetInterval) {
this(name, updateInterval, resetInterval, DEFAULT_BLOCKED_THREAD_THRESHOLD, DEFAULT_KEEP_RATIO, DEFAULT_SCORE_THRESHOLD);
}
public AbstractLatencyScoreStrategyImpl(String name) {
this(name, DEFAULT_UPDATE_INTERVAL, DEFAULT_RESET_INTERVAL, DEFAULT_BLOCKED_THREAD_THRESHOLD, DEFAULT_KEEP_RATIO, DEFAULT_SCORE_THRESHOLD);
}
public final Instance createInstance() {
Instance instance = newInstance();
instances.add(instance);
return instance;
}
/**
* Template method for creating a new latency tracking instance for a host
* @return
*/
protected abstract Instance newInstance();
@Override
public void start(final Listener listener) {
if (updateInterval > 0) {
executor.schedule(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(name + "_ScoreUpdate");
update();
listener.onUpdate();
executor.schedule(this, getUpdateInterval(), TimeUnit.MILLISECONDS);
}
}, new Random().nextInt(getUpdateInterval()), TimeUnit.MILLISECONDS);
}
if (resetInterval > 0) {
executor.schedule(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName(name + "_ScoreReset");
reset();
listener.onReset();
executor.schedule(this, getResetInterval(), TimeUnit.MILLISECONDS);
}
}, new Random().nextInt(getResetInterval()), TimeUnit.MILLISECONDS);
}
}
@Override
public void shutdown() {
if (bOwnedExecutor)
executor.shutdown();
}
@Override
public void removeInstance(Instance instance) {
instances.remove(instance);
}
/**
* Comparator used to sort hosts by score
*/
private Comparator<HostConnectionPool<?>> scoreComparator = new Comparator<HostConnectionPool<?>>() {
@Override
public int compare(HostConnectionPool<?> p1, HostConnectionPool<?> p2) {
double score1 = p1.getScore();
double score2 = p2.getScore();
if (score1 < score2) {
return -1;
}
else if (score1 > score2) {
return 1;
}
return 0;
}
};
/**
* Comparator used to sort hosts by number of buys + blocked operations
*/
private Comparator<HostConnectionPool<?>> busyComparator = new Comparator<HostConnectionPool<?>>() {
@Override
public int compare(HostConnectionPool<?> p1, HostConnectionPool<?> p2) {
return p1.getBusyConnectionCount() + p1.getBlockedThreadCount() - p2.getBusyConnectionCount() - p2.getBlockedThreadCount();
}
};
@Override
public <CL> List<HostConnectionPool<CL>> sortAndfilterPartition(List<HostConnectionPool<CL>> srcPools,
AtomicBoolean prioritized) {
List<HostConnectionPool<CL>> pools = Lists.newArrayList(srcPools);
Collections.sort(pools, scoreComparator);
prioritized.set(false);
int poolSize = pools.size();
int keep = (int) Math.max(1, Math.ceil(poolSize * getKeepRatio()));
// Step 1: Remove any host that is current reconnecting
Iterator<HostConnectionPool<CL>> iter = pools.iterator();
while (iter.hasNext()) {
HostConnectionPool<CL> pool = iter.next();
if (pool.isReconnecting()) {
// System.out.println("**** Removing host (reconnecting) : " + pool.toString());
iter.remove();
}
}
//step 2
if (pools.size() > 0) {
// Step 3: Filter out hosts that are too slow and keep at least the best keepRatio hosts
int first = 0;
for (; pools.get(0).getScore() == 0.0 && first < pools.size(); first++);
if (first < pools.size()) {
double scoreFirst = pools.get(first).getScore();
// System.out.println("First : " + scoreFirst);
if (scoreFirst > 0.0) {
for (int i = pools.size() - 1; i >= keep && i > first; i--) {
HostConnectionPool<CL> pool = pools.get(i);
// System.out.println(i + " : " + pool.getScore() + " threshold:" + getScoreThreshold());
if ((pool.getScore() / scoreFirst) > getScoreThreshold()) {
// System.out.println("**** Removing host (score) : " + pool.toString());
pools.remove(i);
}
else {
break;
}
}
}
}
}
// Step 3: Filter out hosts that are too slow and keep at least the best keepRatio hosts
if (pools.size() > keep) {
Collections.sort(pools, busyComparator);
HostConnectionPool<CL> poolFirst = pools.get(0);
int firstBusy = poolFirst.getBusyConnectionCount() - poolFirst.getBlockedThreadCount();
for (int i = pools.size() - 1; i >= keep; i--) {
HostConnectionPool<CL> pool = pools.get(i);
int busy = pool.getBusyConnectionCount() + pool.getBlockedThreadCount();
if ( (busy - firstBusy) > getBlockedThreshold()) {
// System.out.println("**** Removing host (blocked) : " + pool.toString());
pools.remove(i);
}
}
}
// Step 4: Shuffle the hosts
Collections.shuffle(pools);
return pools;
}
@Override
public void update() {
for (Instance inst : instances) {
inst.update();
}
}
@Override
public void reset() {
for (Instance inst : instances) {
inst.reset();
}
}
@Override
public int getUpdateInterval() {
return this.updateInterval;
}
@Override
public int getResetInterval() {
return this.resetInterval;
}
@Override
public double getScoreThreshold() {
return scoreThreshold;
}
@Override
public int getBlockedThreshold() {
return this.blockedThreshold;
}
@Override
public double getKeepRatio() {
return this.keepRatio;
}
}
| 7,717 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractExecuteWithFailoverImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import com.netflix.astyanax.connectionpool.Connection;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.ExecuteWithFailover;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.IsRetryableException;
import com.netflix.astyanax.connectionpool.exceptions.UnknownException;
/**
* Abstract class that provides a basic impl of {@link ExecuteWithFailover}.
*
* This is used within the context of a {@link AbstractHostPartitionConnectionPool} implementation, where
* the abstract failover class repeatedly attempts to borrow a connection from the implementing {@link ConnectionPool}
* and also releases the connection as cleanup. It also maintains stats about the attempts and informs latency metrics
* on the exceptions when executing {@link Operation}s or borrowing {@link Connection}s from the pool. <br/> <br/>
*
* Note that extending classes need to implement functionality to {@link AbstractExecuteWithFailoverImpl#borrowConnection(Operation)} that must be used
* to execute the operation. They also need to implement {@link AbstractExecuteWithFailoverImpl#canRetry()} to tell this class
* when to stop borrowing connections on failed attempts.
*
* @param <CL>
* @param <R>
*
* @author elandau
*
* @see {@link AbstractHostPartitionConnectionPool#executeWithFailover(Operation, com.netflix.astyanax.retry.RetryPolicy)} for references to this.
* @see {@link RoundRobinExecuteWithFailover} as an example class that extends the functionality.
* @see {@link RoundRobinConnectionPoolImpl} as an example of a {@link ConnectionPool} that employs the {@link RoundRobinExecuteWithFailover} for it's failover impl
*
*/
public abstract class AbstractExecuteWithFailoverImpl<CL, R> implements ExecuteWithFailover<CL, R> {
protected Connection<CL> connection = null;
private long startTime;
private long poolStartTime;
private int attemptCounter = 0;
private final ConnectionPoolMonitor monitor;
protected final ConnectionPoolConfiguration config;
/**
* Public constructor
* @param config
* @param monitor
* @throws ConnectionException
*/
public AbstractExecuteWithFailoverImpl(ConnectionPoolConfiguration config, ConnectionPoolMonitor monitor)
throws ConnectionException {
this.monitor = monitor;
this.config = config;
startTime = poolStartTime = System.currentTimeMillis();
}
/**
* @return {@link Host}
*/
final public Host getCurrentHost() {
HostConnectionPool<CL> pool = getCurrentHostConnectionPool();
if (pool != null)
return pool.getHost();
else
return Host.NO_HOST;
}
/**
* @return {@link HostConnectionPool}
*/
abstract public HostConnectionPool<CL> getCurrentHostConnectionPool();
/**
* @param operation
* @return {@link Connection}
* @throws ConnectionException
*/
abstract public Connection<CL> borrowConnection(Operation<CL, R> operation) throws ConnectionException;
/**
* @return boolean
*/
abstract public boolean canRetry();
/**
* Basic impl that repeatedly borrows a conn and tries to execute the operation while maintaining metrics for
* success, conn attempts, failures and latencies for operation executions
*
* @param operation
* @return {@link OperationResult}
*/
@Override
public OperationResult<R> tryOperation(Operation<CL, R> operation) throws ConnectionException {
Operation<CL, R> filteredOperation = config.getOperationFilterFactory().attachFilter(operation);
while (true) {
attemptCounter++;
try {
connection = borrowConnection(filteredOperation);
startTime = System.currentTimeMillis();
OperationResult<R> result = connection.execute(filteredOperation);
result.setAttemptsCount(attemptCounter);
monitor.incOperationSuccess(getCurrentHost(), result.getLatency());
return result;
}
catch (Exception e) {
ConnectionException ce = (e instanceof ConnectionException) ? (ConnectionException) e
: new UnknownException(e);
try {
informException(ce);
monitor.incFailover(ce.getHost(), ce);
}
catch (ConnectionException ex) {
monitor.incOperationFailure(getCurrentHost(), ex);
throw ex;
}
}
finally {
releaseConnection();
}
}
}
protected void releaseConnection() {
if (connection != null) {
connection.getHostConnectionPool().returnConnection(connection);
connection = null;
}
}
private void informException(ConnectionException connectionException) throws ConnectionException {
connectionException
.setHost(getCurrentHost())
.setLatency(System.currentTimeMillis() - startTime)
.setAttempt(this.attemptCounter)
.setLatencyWithPool(System.currentTimeMillis() - poolStartTime);
if (connectionException instanceof IsRetryableException) {
if (!canRetry()) {
throw connectionException;
}
}
else {
// Most likely an operation error
throw connectionException;
}
}
}
| 7,718 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/TokenAwareConnectionPoolImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.ExecuteWithFailover;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException;
/**
* Connection pool that partitions connections by the hosts which own the token
* being operated on. When a token is not available or an operation is known to
* span multiple tokens (such as a batch mutate or an index query) host pools
* are picked using round robin.
*
* This implementation takes an optimistic approach which is optimized for a
* well functioning ring with all nodes up and keeps downed hosts in the
* internal data structures.
*
* @author elandau
*
* @param <CL>
*/
public class TokenAwareConnectionPoolImpl<CL> extends AbstractHostPartitionConnectionPool<CL> {
private AtomicInteger roundRobinCounter = new AtomicInteger(new Random().nextInt(997));
private static final int MAX_RR_COUNTER = Integer.MAX_VALUE/2;
public TokenAwareConnectionPoolImpl(ConnectionPoolConfiguration configuration, ConnectionFactory<CL> factory,
ConnectionPoolMonitor monitor) {
super(configuration, factory, monitor);
}
@SuppressWarnings("unchecked")
public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> op) throws ConnectionException {
try {
List<HostConnectionPool<CL>> pools;
boolean isSorted = false;
if (op.getPinnedHost() != null) {
HostConnectionPool<CL> pool = hosts.get(op.getPinnedHost());
if (pool == null) {
throw new NoAvailableHostsException("Host " + op.getPinnedHost() + " not active");
}
pools = Arrays.<HostConnectionPool<CL>> asList(pool);
}
else {
TokenHostConnectionPoolPartition<CL> partition = topology.getPartition(op.getRowKey());
pools = partition.getPools();
isSorted = partition.isSorted();
}
int index = roundRobinCounter.incrementAndGet();
if (index > MAX_RR_COUNTER) {
roundRobinCounter.set(0);
}
AbstractExecuteWithFailoverImpl executeWithFailover = null;
switch (config.getHostSelectorStrategy()) {
case ROUND_ROBIN:
executeWithFailover = new RoundRobinExecuteWithFailover<CL, R>(config, monitor, pools, isSorted ? 0 : index);
break;
case LEAST_OUTSTANDING:
executeWithFailover = new LeastOutstandingExecuteWithFailover<CL, R>(config, monitor, pools);
break;
default:
executeWithFailover = new RoundRobinExecuteWithFailover<CL, R>(config, monitor, pools, isSorted ? 0 : index);
break;
}
return executeWithFailover;
}
catch (ConnectionException e) {
monitor.incOperationFailure(e.getHost(), e);
throw e;
}
}
}
| 7,719 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/ExponentialRetryBackoffStrategy.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.HostConnectionPool;
import com.netflix.astyanax.connectionpool.RetryBackoffStrategy;
/**
* Impl for {@link RetryBackoffStrategy} that is used to reconnect a {@link HostConnectionPool} when a host is marked as down.
*
* @author elandau
* @see {@link SimpleHostConnectionPool#markAsDown(com.netflix.astyanax.connectionpool.exceptions.ConnectionException)} for details on how this class is referenced
*/
public class ExponentialRetryBackoffStrategy implements RetryBackoffStrategy {
private final ConnectionPoolConfiguration config;
/**
* @param config
*/
public ExponentialRetryBackoffStrategy(ConnectionPoolConfiguration config) {
this.config = config;
}
/**
* @return String
*/
public String toString() {
return new StringBuilder().append("ExpRetry[").append("max=").append(config.getRetryMaxDelaySlice())
.append(",slot=").append(config.getRetryDelaySlice()).append(",suspend=")
.append(config.getRetrySuspendWindow()).append("]").toString();
}
/**
* @return {@link Instance}
*/
@Override
public Instance createInstance() {
return new RetryBackoffStrategy.Instance() {
private int c = 1;
private AtomicBoolean isSuspended = new AtomicBoolean(false);
private int attemptCount = 0;
private long lastReconnectTime = 0;
@Override
public long getNextDelay() {
if (isSuspended.get()) {
isSuspended.set(false);
return config.getRetrySuspendWindow();
}
attemptCount++;
if (attemptCount == 1) {
if (System.currentTimeMillis() - lastReconnectTime < config.getRetrySuspendWindow()) {
return config.getRetrySuspendWindow();
}
}
c *= 2;
if (c > config.getRetryMaxDelaySlice())
c = config.getRetryMaxDelaySlice();
return (new Random().nextInt(c) + 1) * config.getRetryDelaySlice();
}
@Override
public int getAttemptCount() {
return attemptCount;
}
public String toString() {
return new StringBuilder().append("ExpRetry.Instance[").append(c).append(",").append(isSuspended)
.append(",").append(attemptCount).append("]").toString();
}
@Override
public void begin() {
this.attemptCount = 0;
this.c = 1;
}
@Override
public void success() {
this.lastReconnectTime = System.currentTimeMillis();
}
@Override
public void suspend() {
this.isSuspended.set(true);
}
};
}
}
| 7,720 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/OperationFilterFactoryList.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.List;
import com.google.common.collect.Lists;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.OperationFilterFactory;
/**
* Uses the decorator pattern to maintain a list of {@link OperationFilterFactory} for the specified {@link Operation}
* @author elandau
*
*/
public class OperationFilterFactoryList implements OperationFilterFactory {
private final List<OperationFilterFactory> filters = Lists.newArrayList();
@Override
public <R, CL> Operation<R, CL> attachFilter(Operation<R, CL> operation) {
for (OperationFilterFactory factory : filters) {
operation = factory.attachFilter(operation);
}
return operation;
}
public OperationFilterFactoryList addFilterFactory(OperationFilterFactory factory) {
filters.add(factory);
return this;
}
}
| 7,721 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/HostStats.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.impl;
public interface HostStats {
/**
* Get number of borrowed connections
* @return
*/
long getBorrowedCount();
/**
* Get number of returned connections
* @return
*/
long getReturnedCount();
/**
* Get number of successful operations
* @return
*/
long getSuccessCount();
/**
* Get number of failed operations
* @return
*/
long getErrorCount();
}
| 7,722 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleAuthenticationCredentials.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.connectionpool.impl;
import java.util.Map;
import com.google.common.collect.Maps;
import com.netflix.astyanax.AuthenticationCredentials;
public class SimpleAuthenticationCredentials implements AuthenticationCredentials {
private String username;
private String password;
private final Map<String, Object> attributes = Maps.newHashMap();
public SimpleAuthenticationCredentials(String username, String password) {
this.username = username;
this.password = password;
}
public SimpleAuthenticationCredentials setUsername(String username) {
this.username = username;
return this;
}
public SimpleAuthenticationCredentials setPassword(String password) {
this.password = password;
return this;
}
public SimpleAuthenticationCredentials setAttribute(String name, Object value) {
this.attributes.put(name, value);
return this;
}
public SimpleAuthenticationCredentials removeAttribute(String name) {
this.attributes.remove(name);
return this;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public String[] getAttributeNames() {
return attributes.keySet().toArray(new String[attributes.size()]);
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
}
| 7,723 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/TransportException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class TransportException extends ConnectionException implements IsRetryableException, IsDeadConnectionException {
/**
*
*/
private static final long serialVersionUID = -1086321632073952243L;
public TransportException(String message) {
super(message);
}
public TransportException(Throwable t) {
super(t);
}
public TransportException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,724 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/OperationException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* Application exception for an operation executed within the context of the
* connection pool. An application exception varies from other
* ConnectionException in that it will immediately roll up to the client and
* cannot fail over. Examples of application exceptions are invalid request
* formats.
*
* @author elandau
*
*/
public class OperationException extends ConnectionException {
/**
*
*/
private static final long serialVersionUID = -369210846483113052L;
public OperationException(String message) {
super(message);
}
public OperationException(Throwable t) {
super(t);
}
public OperationException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,725 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/ThrottledException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class ThrottledException extends ConnectionException implements IsRetryableException {
private static final long serialVersionUID = 1257641642867458438L;
public ThrottledException(String message) {
super(message);
}
public ThrottledException(Throwable t) {
super(t);
}
public ThrottledException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,726 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/OperationTimeoutException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class OperationTimeoutException extends ConnectionException implements IsTimeoutException, IsRetryableException {
/**
*
*/
private static final long serialVersionUID = 5676170035940390111L;
public OperationTimeoutException(String message) {
super(message);
}
public OperationTimeoutException(Throwable t) {
super(t);
}
public OperationTimeoutException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,727 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/NoAvailableHostsException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class NoAvailableHostsException extends ConnectionException {
/**
*
*/
private static final long serialVersionUID = 6567371094004403691L;
public NoAvailableHostsException(String message) {
super(message);
}
public NoAvailableHostsException(Throwable t) {
super(t);
}
public NoAvailableHostsException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,728 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/IsRetryableException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* Defines that an exception is retryable for the context of a single execute
* with failover.
*
* @author elandau
*
*/
public interface IsRetryableException {
}
| 7,729 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/PoolTimeoutException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class PoolTimeoutException extends ConnectionException implements IsRetryableException {
/**
*
*/
private static final long serialVersionUID = -8579946319118318717L;
public PoolTimeoutException(String message) {
super(message);
}
public PoolTimeoutException(Throwable t) {
super(t);
}
public PoolTimeoutException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,730 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/SchemaDisagreementException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class SchemaDisagreementException extends OperationException {
/**
*
*/
private static final long serialVersionUID = 8769688825913183141L;
public SchemaDisagreementException(Throwable t) {
super(t);
}
public SchemaDisagreementException(String str) {
super(str);
}
}
| 7,731 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/InterruptedOperationException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class InterruptedOperationException extends ConnectionException {
/**
*
*/
private static final long serialVersionUID = -1983353895015277466L;
public InterruptedOperationException(String message) {
super(message);
}
public InterruptedOperationException(Throwable t) {
super(t);
}
public InterruptedOperationException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,732 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/TokenRangeOfflineException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class TokenRangeOfflineException extends ConnectionException {
/**
*
*/
private static final long serialVersionUID = 4269482200208592843L;
public TokenRangeOfflineException(String message) {
super(message);
}
public TokenRangeOfflineException(Throwable cause) {
super(cause);
}
public TokenRangeOfflineException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,733 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/BadRequestException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class BadRequestException extends OperationException {
private static final long serialVersionUID = -6046784540431794568L;
private static final String WHY_UNCONFIGURED_COLUMNFAMILY = "unconfigured columnfamily";
private static final String KEYSPACE = "Keyspace";
private static final String DOES_NOT_EXIST = "does not exist";
public BadRequestException(String message) {
super(message);
}
public BadRequestException(Throwable t) {
super(t);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
public boolean isUnconfiguredColumnFamilyError() {
return getMessage().contains(WHY_UNCONFIGURED_COLUMNFAMILY);
}
public boolean isKeyspaceDoestNotExist() {
String message = getMessage();
return message.contains(KEYSPACE) && message.contains(DOES_NOT_EXIST);
}
}
| 7,734 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/MaxConnsPerHostReachedException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* No more connections may be opened on a host and no timeout was specified.
*
* @author elandau
*
*/
public class MaxConnsPerHostReachedException extends ConnectionException implements IsRetryableException {
/**
*
*/
private static final long serialVersionUID = 3153033457028147246L;
public MaxConnsPerHostReachedException(String message) {
super(message);
}
public MaxConnsPerHostReachedException(Throwable t) {
super(t);
}
public MaxConnsPerHostReachedException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,735 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/ThriftStateException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class ThriftStateException extends ConnectionException implements IsDeadConnectionException,
IsRetryableException {
/**
*
*/
private static final long serialVersionUID = -7163779789960683466L;
public ThriftStateException(String message) {
super(message);
}
public ThriftStateException(Throwable t) {
super(t);
}
public ThriftStateException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,736 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/IsDeadConnectionException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* Describes an exception after which a connection is no longer usable.
*
* @author elandau
*
*/
public interface IsDeadConnectionException {
}
| 7,737 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/ConnectionException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
import java.util.concurrent.TimeUnit;
import com.netflix.astyanax.connectionpool.Host;
/**
* Connection exception caused by an error in the connection pool or a transport
* error related to the connection itself. Application errors are derived from
* OperationException.
*
* @author elandau
*
*/
public abstract class ConnectionException extends Exception {
/**
*
*/
private static final long serialVersionUID = -3476496346094715988L;
private Host host = Host.NO_HOST;
private long latency = 0;
private long latencyWithPool = 0;
private int attemptCount = 0;
public ConnectionException(String message) {
super(message);
}
public ConnectionException(Throwable t) {
super(t);
}
public ConnectionException(String message, Throwable cause) {
super(message, cause);
}
public ConnectionException setHost(Host host) {
this.host = host;
return this;
}
public Host getHost() {
return this.host;
}
public ConnectionException setLatency(long latency) {
this.latency = latency;
return this;
}
public long getLatency() {
return this.latency;
}
public long getLatency(TimeUnit units) {
return units.convert(this.latency, TimeUnit.NANOSECONDS);
}
public ConnectionException setLatencyWithPool(long latency) {
this.latencyWithPool = latency;
return this;
}
public long getLatencyWithPool() {
return this.latencyWithPool;
}
@Override
public String getMessage() {
return new StringBuilder()
.append(getClass().getSimpleName())
.append(": [")
.append( "host=" ).append(host.toString())
.append(", latency=" ).append(latency).append("(").append(latencyWithPool).append(")")
.append(", attempts=").append(attemptCount)
.append("]")
.append(super.getMessage())
.toString();
}
public String getOriginalMessage() {
return super.getMessage();
}
public ConnectionException setAttempt(int attemptCount) {
this.attemptCount = attemptCount;
return this;
}
}
| 7,738 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/SerializationException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class SerializationException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 9055130045549798400L;
public SerializationException(String message) {
super(message);
}
public SerializationException(Throwable cause) {
super(cause);
}
public SerializationException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,739 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/BadConfigurationException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class BadConfigurationException extends OperationException {
/**
*
*/
private static final long serialVersionUID = -5029835858453307841L;
private String parameter;
private String value;
private String expected;
public BadConfigurationException(String parameter, String value, String expected) {
super("Bad configuration " + parameter + "=" + value + " (expected: " + expected + ")");
}
public BadConfigurationException(Throwable cause) {
super(cause);
}
public BadConfigurationException(String parameter, String value, String expected, Throwable cause) {
super("Bad configuration " + parameter + "=" + value + " (expected: " + expected + ")", cause);
}
public BadConfigurationException(String parameter, String value, Throwable cause) {
super("Bad configuration " + parameter + "=" + value, cause);
}
public String getParameter() {
return parameter;
}
public String getValue() {
return value;
}
public String getExpected() {
return expected;
}
@Override
public String getMessage() {
return this.getOriginalMessage();
}
}
| 7,740 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/HostDownException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* No more connections may be opened on a host and no timeout was specified.
*
* @author elandau
*
*/
public class HostDownException extends ConnectionException implements IsRetryableException {
/**
*
*/
private static final long serialVersionUID = 6081587518856031437L;
public HostDownException(String message) {
super(message);
}
public HostDownException(Throwable t) {
super(t);
}
public HostDownException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,741 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/ConnectionAbortedException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class ConnectionAbortedException extends TransportException {
/**
*
*/
private static final long serialVersionUID = 6918220226977765595L;
public ConnectionAbortedException(String message) {
super(message);
}
public ConnectionAbortedException(Throwable t) {
super(t);
}
public ConnectionAbortedException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,742 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/UnknownException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class UnknownException extends OperationException implements IsDeadConnectionException {
/**
*
*/
private static final long serialVersionUID = -6204702276016512865L;
public UnknownException(String message) {
super(message);
}
public UnknownException(Throwable t) {
super(t);
}
public UnknownException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,743 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/TimeoutException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
/**
* This is actually a socket timeout
* @author elandau
*
*/
public class TimeoutException extends ConnectionException implements IsRetryableException, IsDeadConnectionException,
IsTimeoutException {
/**
*
*/
private static final long serialVersionUID = -3485969997380336227L;
public TimeoutException(String message) {
super(message);
}
public TimeoutException(Throwable t) {
super(t);
}
public TimeoutException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,744 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/AuthenticationException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class AuthenticationException extends OperationException {
/**
*
*/
private static final long serialVersionUID = -1376061218661301537L;
/**
*
*/
public AuthenticationException(String message) {
super(message);
}
public AuthenticationException(Throwable t) {
super(t);
}
public AuthenticationException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,745 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/WalException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class WalException extends ConnectionException {
private static final long serialVersionUID = -1556352199503400553L;
public WalException(String message) {
super(message);
}
public WalException(Throwable cause) {
super(cause);
}
public WalException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,746 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/NotFoundException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public class NotFoundException extends OperationException {
/**
*
*/
private static final long serialVersionUID = -575277476194276973L;
public NotFoundException(String message) {
super(message);
}
public NotFoundException(Throwable cause) {
super(cause);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| 7,747 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/exceptions/IsTimeoutException.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.connectionpool.exceptions;
public interface IsTimeoutException {
}
| 7,748 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/MicrosecondsSyncClock.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.clock;
import com.netflix.astyanax.Clock;
/**
* Clock which uses a rolling counter to avoid duplicates.
*
* @author Patricio Echague (pechague@gmail.com)
*/
public class MicrosecondsSyncClock implements Clock {
private static final long serialVersionUID = -4671061000963496156L;
private static long lastTime = -1;
private static final long ONE_THOUSAND = 1000L;
@Override
public long getCurrentTime() {
// The following simulates a microseconds resolution by advancing a
// static counter
// every time a client calls the createClock method, simulating a tick.
long us = System.currentTimeMillis() * ONE_THOUSAND;
// Synchronized to guarantee unique time within and across threads.
synchronized (MicrosecondsSyncClock.class) {
if (us > lastTime) {
lastTime = us;
}
else {
// the time i got from the system is equals or less
// (hope not - clock going backwards)
// One more "microsecond"
us = ++lastTime;
}
}
return us;
}
public String toString() {
return "MicrosecondsSyncClock";
}
}
| 7,749 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/ConstantClock.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.clock;
import com.netflix.astyanax.Clock;
public class ConstantClock implements Clock {
private final long timestamp;
public ConstantClock(long timestamp) {
this.timestamp = timestamp;
}
@Override
public long getCurrentTime() {
return timestamp;
}
}
| 7,750 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/ClockType.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.clock;
import com.netflix.astyanax.Clock;
public enum ClockType {
MSEC(new MillisecondsClock()), MICRO(new MicrosecondsSyncClock()), ASYNC_MICRO(new MicrosecondsAsyncClock());
Clock clock;
public Clock get() {
return clock;
}
ClockType(Clock clock) {
this.clock = clock;
}
}
| 7,751 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/MillisecondsClock.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.clock;
import com.netflix.astyanax.Clock;
/**
*
* @author Patricio Echague (pechague@gmail.com)
*/
public class MillisecondsClock implements Clock {
@Override
public long getCurrentTime() {
return System.currentTimeMillis();
}
public String toString() {
return "MillisecondsClock";
}
}
| 7,752 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/MicrosecondsAsyncClock.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.clock;
import java.util.concurrent.atomic.AtomicInteger;
import com.netflix.astyanax.Clock;
public class MicrosecondsAsyncClock implements Clock {
private static final long serialVersionUID = -4671061000963496156L;
private static final long ONE_THOUSAND = 1000L;
private static AtomicInteger counter = new AtomicInteger(0);
public MicrosecondsAsyncClock() {
}
@Override
public long getCurrentTime() {
// The following simulates a microseconds resolution by advancing a
// static counter
// every time a client calls the createClock method, simulating a tick.
long us = System.currentTimeMillis() * ONE_THOUSAND;
return us + counter.getAndIncrement() % ONE_THOUSAND;
}
public String toString() {
return "MicrosecondsAsyncClock";
}
}
| 7,753 |
0 | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/clock/MicrosecondsClock.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.clock;
import com.netflix.astyanax.Clock;
/**
*
* @author Patricio Echague (pechague@gmail.com)
*/
public class MicrosecondsClock implements Clock {
private static final long ONE_THOUSAND = 1000L;
@Override
public long getCurrentTime() {
return System.currentTimeMillis() * ONE_THOUSAND;
}
public String toString() {
return "MicrosecondsClock";
}
}
| 7,754 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/AstyanaxTypeFactory.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
/**
* Factory that groups a family of Keyspace, Client and ConnectionFactory for a
* specific RPC to cassandra (i.e. Thrift)
*
* @author elandau
*
* @param <T>
*/
public interface AstyanaxTypeFactory<T> {
Keyspace createKeyspace(String ksName, ConnectionPool<T> cp, AstyanaxConfiguration asConfig,
KeyspaceTracerFactory tracerFactory);
Cluster createCluster(ConnectionPool<T> cp, AstyanaxConfiguration asConfig,
KeyspaceTracerFactory tracerFactory);
ConnectionFactory<T> createConnectionFactory(AstyanaxConfiguration asConfig, ConnectionPoolConfiguration cfConfig,
KeyspaceTracerFactory tracerFactory, ConnectionPoolMonitor monitor);
}
| 7,755 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/MutationBatchManager.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
/**
* The mutation manager enables different recipes or entity managers to use
* the same mutation for bulk operations. In addition a mutation manager
* can be used to implement write ahead semantics for 'atomic' mutations.
*
* The mutation manager is expected to be thread safe such that all mutations
* in the same thread go to the same mutation batch. This also means that
* getMutationBatch(), the mutations and the final commit() must occur within
* the same thread.
*
* @author elandau
*
*/
public interface MutationBatchManager {
/**
* Get or create a new mutation batch.
*
* @return
*/
public MutationBatch getSharedMutationBatch();
/**
* Get a one time mutation batch
* @return
*/
public MutationBatch getNewMutationBatch();
/**
* Commit all mutations on the batch
* @throws ConnectionException
*/
public void commitSharedMutationBatch() throws ConnectionException ;
/**
* Discard all mutations on the batch
*/
public void discard();
}
| 7,756 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/MutationBatch.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Set;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.retry.RetryPolicy;
/**
* Batch mutator which operates at the row level assuming the hierarchy:
*
* RowKey -> ColumnFamily -> Mutation.
*
* This hierarchy serves two purposes. First, it makes it possible to perform
* multiple operations on the same row without having to repeat specifying the
* row key. Second, it mirrors the underlying Thrift data structure which averts
* unnecessary operations to convert from one data structure to another.
*
* The mutator is not thread safe
*
* If successful, all the mutations are cleared and new mutations may be
* created. Any previously acquired ColumnFamilyMutations are no longer valid
* and should be discarded.
*
* No data is actually returned after a mutation is executed, hence the Void
* return value type.
*
* Example:
*
* <pre>
* {
* @code
* ColumnFamily<String, String> cf = AFactory.makeColumnFamily("COLUMN_FAMILY_NAME", // Name
* // of
* // CF
* // in
* // Cassandra
* StringSerializer.get(), // Row key serializer (implies string type)
* StringSerializer.get(), // Column name serializer (implies string
* // type)
* ColumnType.STANDARD); // This is a standard row
*
* // Create a batch mutation
* RowMutationBatch m = keyspace.prepareMutationBatch();
*
* // Start mutate a column family for a specific row key
* ColumnFamilyMutation<String> cfm = m.row(cfSuper, "UserId").putColumn("Address", "976 Elm St.")
* .putColumn("Age", 50).putColumn("Gender", "Male");
*
* // To delete a row
* m.row(cfSuper, "UserId").delete();
*
* // Finally, execute the query
* m.execute();
*
* }
* </pre>
*
* @author elandau
*
* @param <K>
*/
public interface MutationBatch extends Execution<Void> {
/**
* Mutate a row. The ColumnFamilyMutation is only valid until execute() or
* discardMutations is called.
*
* @param rowKey
*/
<K, C> ColumnListMutation<C> withRow(ColumnFamily<K, C> columnFamily, K rowKey);
/**
* Delete the row for all the specified column families.
*
* @param columnFamilies
*/
<K> void deleteRow(Iterable<? extends ColumnFamily<K, ?>> columnFamilies, K rowKey);
/**
* Discard any pending mutations. All previous references returned by row
* are now invalid. Note also that this will reset the mutation timestamp
* so that the next call to withRow will set the timestamp to the current time
*/
void discardMutations();
/**
* Perform a shallow merge of mutations from another batch.
*
* @throws UnsupportedOperationException
* if the other mutation is of a different type
*/
void mergeShallow(MutationBatch other);
/**
* @return true if there are no rows in the mutation. May return a false
* true if a row() was added by calling the above row() method but no
* mutations were created.
*/
boolean isEmpty();
/**
* @return Returns the number of rows being mutated
*/
int getRowCount();
/**
* @return Return a mapping of column families to rows being modified
*/
Map<ByteBuffer, Set<String>> getRowKeys();
/**
* Pin this operation to a specific host
*
* @param host
*/
MutationBatch pinToHost(Host host);
/**
* Set the consistency level for this mutation (same as withConsistencyLevel)
*
* @param consistencyLevel
*/
MutationBatch setConsistencyLevel(ConsistencyLevel consistencyLevel);
/**
* Set the consistency level for this mutation (same as setConsistencyLevel)
*
* @param consistencyLevel
*/
MutationBatch withConsistencyLevel(ConsistencyLevel consistencyLevel);
/**
* Set the retry policy to use instead of the one specified in the
* configuration
*
* @param retry
*/
MutationBatch withRetryPolicy(RetryPolicy retry);
/**
* Specify a write ahead log implementation to use for this mutation
*
* @param manager
*/
MutationBatch usingWriteAheadLog(WriteAheadLog manager);
/**
* Force all future mutations to have the same timestamp. Make sure to call
* lockTimestamp before doing any other operations otherwise previously
* created withRow mutations will use the previous timestamp.
*/
MutationBatch lockCurrentTimestamp();
/**
* This never really did anything :)
* @param
*/
@Deprecated
MutationBatch setTimeout(long timeout);
/**
* Set the timestamp for all subsequent operations on this mutation
* (same as withTimestamp)
*
* @param timestamp in microseconds
*/
MutationBatch setTimestamp(long timestamp);
/**
* Set the timestamp for all subsequent operations on this mutation.
*
* @param timestamp in microsecond
*/
MutationBatch withTimestamp(long timestamp);
/**
* Use Atomic Batches for these updates.
* See http://www.datastax.com/dev/blog/atomic-batches-in-cassandra-1-2
* @return MutationBatch
*/
MutationBatch withAtomicBatch(boolean condition);
/**
* @return Serialize the entire mutation batch into a ByteBuffer.
* @throws Exception
*/
ByteBuffer serialize() throws Exception;
/**
* Re-recreate a mutation batch from a serialized ByteBuffer created by a
* call to serialize(). Serialization of MutationBatches from different
* implementations is not guaranteed to match.
*
* @param data
* @throws Exception
*/
void deserialize(ByteBuffer data) throws Exception;
/**
* Turn statement caching ON/OFF
* This is to be used specifically with the CQL3 driver which uses PreparedStatment(s)
* @param condition
* @return MutationBatch
*/
MutationBatch withCaching(boolean condition);
}
| 7,757 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/AbstractColumnListMutation.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import com.google.common.base.Preconditions;
import com.netflix.astyanax.serializers.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.StringUtils;
/**
* Abstract implementation of a row mutation
*
* @author lucky
*
* @param <C>
*/
public abstract class AbstractColumnListMutation<C> implements ColumnListMutation<C> {
protected long timestamp;
protected Integer defaultTtl = null;
public AbstractColumnListMutation(long timestamp) {
this.timestamp = timestamp;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, String value, Integer ttl) {
return putColumn(columnName, value, StringSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final String value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, String value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, String value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, byte[] value, Integer ttl) {
return putColumn(columnName, value, BytesArraySerializer.get(), ttl);
}
@Override
public <V> ColumnListMutation<C> putColumnIfNotNull(C columnName, V value, Serializer<V> valueSerializer, Integer ttl) {
if (value == null)
return this;
return putColumn(columnName, value, valueSerializer, ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final byte[] value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, byte[] value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, byte[] value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, byte value, Integer ttl) {
return putColumn(columnName, value, ByteSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final byte value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Byte value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Byte value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, short value, Integer ttl) {
return putColumn(columnName, value, ShortSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final short value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Short value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Short value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, int value, Integer ttl) {
return putColumn(columnName, value, IntegerSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final int value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Integer value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Integer value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, long value, Integer ttl) {
return putColumn(columnName, value, LongSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final long value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Long value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Long value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, boolean value, Integer ttl) {
return putColumn(columnName, value, BooleanSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final boolean value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Boolean value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Boolean value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, ByteBuffer value, Integer ttl) {
return putColumn(columnName, value, ByteBufferSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final ByteBuffer value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, ByteBuffer value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, ByteBuffer value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, Date value, Integer ttl) {
return putColumn(columnName, value, DateSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final Date value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Date value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Date value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, float value, Integer ttl) {
return putColumn(columnName, value, FloatSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final float value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Float value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Float value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, double value, Integer ttl) {
return putColumn(columnName, value, DoubleSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final double value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Double value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, Double value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putColumn(C columnName, UUID value, Integer ttl) {
return putColumn(columnName, value, UUIDSerializer.get(), ttl);
}
@Override
public ColumnListMutation<C> putColumn(final C columnName, final UUID value) {
return putColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, UUID value) {
if (value != null) {
return putColumn(columnName, value);
}
return this;
}
@Override
public ColumnListMutation<C> putColumnIfNotNull(C columnName, UUID value, Integer ttl) {
if (value != null) {
return putColumn(columnName, value, ttl);
}
return this;
}
@Override
public ColumnListMutation<C> putEmptyColumn(final C columnName) {
return putEmptyColumn(columnName, null);
}
@Override
public ColumnListMutation<C> setTimestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
@Override
public ColumnListMutation<C> setDefaultTtl(Integer ttl) {
this.defaultTtl = ttl;
return this;
}
@Override
public ColumnListMutation<C> putCompressedColumn(C columnName, String value, Integer ttl) {
Preconditions.checkNotNull(value, "Can't insert null value");
if (value == null) {
putEmptyColumn(columnName, ttl);
return this;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(StringUtils.getBytesUtf8(value));
gzip.close();
return this.putColumn(columnName, ByteBuffer.wrap(out.toByteArray()), ttl);
} catch (IOException e) {
throw new RuntimeException("Error compressing column " + columnName, e);
}
}
@Override
public ColumnListMutation<C> putCompressedColumn(C columnName, String value) {
return putCompressedColumn(columnName, value, null);
}
@Override
public ColumnListMutation<C> putCompressedColumnIfNotNull(C columnName, String value, Integer ttl) {
if (value == null)
return this;
return putCompressedColumn(columnName, value, ttl);
}
@Override
public ColumnListMutation<C> putCompressedColumnIfNotNull(C columnName, String value) {
if (value == null)
return this;
return putCompressedColumn(columnName, value);
}
public Integer getDefaultTtl() {
return defaultTtl;
}
public long getTimestamp() {
return timestamp;
}
}
| 7,758 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/RowCallback.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Rows;
public interface RowCallback<K, C> {
/**
* Notification for each block of rows.
*
* @param rows
*/
void success(Rows<K, C> rows);
/**
* Notification of an error calling cassandra. In your handler you can
* implement your own backoff logic and return true to retry or false to
* stop the query.
*
* @param e
* @return true to retry or false to exit
*/
boolean failure(ConnectionException e);
}
| 7,759 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/MultiMutationBatchManager.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.Maps;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ConsistencyLevel;
/**
* Extension to mutation batch which allows for multiple 'named' mutation
* batches. The purpose of this manager is to allow mutations to be executed
* in order of batch creation so that subsequent mutations aren't attempted
* if there is a failure.
*
* @author elandau
*
*/
public class MultiMutationBatchManager implements MutationBatchManager {
private final String DEFAULT_BATCH_NAME = "default";
private final ThreadLocal<Map<String, MutationBatch>> batches = new ThreadLocal<Map<String, MutationBatch>>();
private final Keyspace keyspace;
private final ConsistencyLevel cl;
public MultiMutationBatchManager(Keyspace keyspace, ConsistencyLevel cl) {
this.keyspace = keyspace;
this.cl = cl;
}
@Override
public MutationBatch getSharedMutationBatch() {
return getNamedMutationBatch(DEFAULT_BATCH_NAME);
}
public MutationBatch getNamedMutationBatch(String name) {
Map<String, MutationBatch> mbs = batches.get();
if (mbs == null) {
mbs = Maps.newLinkedHashMap();
batches.set(mbs);
}
MutationBatch mb = mbs.get(name);
if (mb == null) {
mb = getNewMutationBatch();
mbs.put(name, mb);
}
return mb;
}
@Override
public void commitSharedMutationBatch() throws ConnectionException {
Map<String, MutationBatch> mbs = batches.get();
if (mbs != null) {
for (Entry<String, MutationBatch> entry : mbs.entrySet()) {
entry.getValue().execute();
}
batches.remove();
}
}
@Override
public void discard() {
batches.remove();
}
@Override
public MutationBatch getNewMutationBatch() {
return keyspace.prepareMutationBatch().setConsistencyLevel(cl);
}
}
| 7,760 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/Cluster.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.OperationException;
import com.netflix.astyanax.ddl.ColumnDefinition;
import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
import com.netflix.astyanax.ddl.KeyspaceDefinition;
import com.netflix.astyanax.ddl.SchemaChangeResult;
/**
* Interface for cluster operations. Use the Keyspace interface to perform
* keyspace query and mutation operations.
*
* @author elandau
*
*/
public interface Cluster {
/**
* The cluster name is completely arbitrary
* @throws ConnectionException
*/
String describeClusterName() throws ConnectionException;
/**
* Return version of cassandra running on the cluster
* @throws ConnectionException
*/
String getVersion() throws ConnectionException;
/**
* Describe the snitch name used on the cluster
* @throws ConnectionException
*/
String describeSnitch() throws ConnectionException;
/**
* Describe the partitioner used by the cluster
* @throws ConnectionException
*/
String describePartitioner() throws ConnectionException;
/**
* For each schema version present in the cluster, returns a list of nodes at that
* version. Hosts that do not respond will be under the key DatabaseDescriptor.INITIAL_VERSION.
* The cluster is all on the same version if the size of the map is 1
* @throws ConnectionException
*/
Map<String, List<String>> describeSchemaVersions() throws ConnectionException;
/**
* Prepare a column family definition. Call execute() on the returned object
* to create the column family.
*/
ColumnFamilyDefinition makeColumnFamilyDefinition();
/**
* Make a column definitio to be added to a ColumnFamilyDefinition
*/
ColumnDefinition makeColumnDefinition();
/**
* Delete the column family from the keyspace
*
* @param columnFamilyName To delete
* @throws OperationException
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> dropColumnFamily(String keyspaceName, String columnFamilyName) throws ConnectionException;
/**
* Add a column family to an existing keyspace
*
* @param def - Created by calling makeColumnFamilyDefinition();
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> addColumnFamily(ColumnFamilyDefinition def) throws ConnectionException;
/**
* Update an existing column family
*
* @param def - Created by calling makeColumnFamilyDefinition();
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> updateColumnFamily(ColumnFamilyDefinition def) throws ConnectionException;
/**
* Prepare a keyspace definition. Call execute() on the returned object to
* create the keyspace.
*
* Not that column families can be added the keyspace definition here
* instead of calling makeColumnFamilyDefinition separately.
*/
KeyspaceDefinition makeKeyspaceDefinition();
/**
* Return all the keyspace definition as properties
* @param keyspace
* @return
* @throws ConnectionException
*/
Properties getAllKeyspaceProperties() throws ConnectionException;
/**
* Return the keyspace definition as a properties
* @return
*/
Properties getKeyspaceProperties(String keyspace) throws ConnectionException ;
/**
* Return the
* @return
*/
Properties getColumnFamilyProperties(String keyspace, String keyspaces) throws ConnectionException ;
/**
* Return details about all keyspaces in the cluster
* @throws ConnectionException
*/
List<KeyspaceDefinition> describeKeyspaces() throws ConnectionException;
/**
* Describe a single keyspace
*
* @param ksName - Keyspace name
* @throws ConnectionException
*/
KeyspaceDefinition describeKeyspace(String ksName) throws ConnectionException;
/**
* Return a keyspace client. Note that this keyspace will use the same
* connection pool as the cluster and any other keyspaces created from this
* cluster instance. As a result each keyspace operation is likely to have
* some overhead for switching keyspaces.
*/
Keyspace getKeyspace(String keyspace) throws ConnectionException ;
/**
* Delete a keyspace from the cluster
*
* @param keyspaceName - Keyspace to drop
* @throws OperationException
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> dropKeyspace(String keyspaceName) throws ConnectionException;
/**
* Add a new keyspace to the cluster. The keyspace object may include column
* families as well. Create a KeyspaceDefinition object by calling
* makeKeyspaceDefinition().
*
* @param def
* @return
*/
OperationResult<SchemaChangeResult> addKeyspace(KeyspaceDefinition def) throws ConnectionException;
/**
* Update a new keyspace in the cluster. The keyspace object may include
* column families as well. Create a KeyspaceDefinition object by calling
* makeKeyspaceDefinition().
*
* @param def
*/
OperationResult<SchemaChangeResult> updateKeyspace(KeyspaceDefinition def) throws ConnectionException;
/**
* Configuration object for this Cluster
*/
AstyanaxConfiguration getConfig();
/**
* Create a column family. Definition must also specify the parent keyspace.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createColumnFamily(Map<String, Object> options) throws ConnectionException ;
/**
* Create a column family. Definition must also specify the parent keyspace.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createColumnFamily(Properties props) throws ConnectionException ;
/**
* Update the column family in cassandra
*
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> updateColumnFamily(Map<String, Object> options) throws ConnectionException ;
/**
* Update the column family in cassandra
*
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> updateColumnFamily(Properties props) throws ConnectionException ;
/**
* Create the keyspace in cassandra. This call will only create the keyspace and not
* any column families. Once the keyspace has been created then call createColumnFamily
* for each CF you want to create.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createKeyspace(Map<String, Object> options) throws ConnectionException ;
/**
* Create the keyspace in cassandra. This call will only create the keyspace and any
* child column families.
*
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createKeyspace(Properties props) throws ConnectionException;
/**
* Update the keyspace in cassandra. Only the keyspace and no column family definitions will be
* updated here
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> updateKeyspace(Map<String, Object> options) throws ConnectionException ;
/**
* Update the keyspace in cassandra. Only the keyspace and no column family definitions will be
* updated here
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> updateKeyspace(Properties props) throws ConnectionException ;
}
| 7,761 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/AstyanaxContext.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.netflix.astyanax.connectionpool.ConnectionFactory;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration;
import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.ConnectionPoolProxy;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.NodeDiscovery;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.BagOfConnectionsConnectionPoolImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.connectionpool.impl.NodeDiscoveryImpl;
import com.netflix.astyanax.connectionpool.impl.RoundRobinConnectionPoolImpl;
import com.netflix.astyanax.connectionpool.impl.TokenAwareConnectionPoolImpl;
import com.netflix.astyanax.impl.FilteringHostSupplier;
import com.netflix.astyanax.impl.RingDescribeHostSupplier;
import com.netflix.astyanax.shallows.EmptyKeyspaceTracerFactory;
/**
* This object tracks the context of an astyanax instance of either a Cluster or
* Keyspace
*
* @author elandau
*
* @param <T>
*/
public class AstyanaxContext<T> {
private final ConnectionPool<?> cp;
private final NodeDiscovery discovery;
private final ConnectionPoolConfiguration cpConfig;
private final AstyanaxConfiguration asConfig;
private final String clusterName;
private final String keyspaceName;
private final T client;
private final ConnectionPoolMonitor monitor;
public static class Builder {
protected ConnectionPool<?> cp;
protected NodeDiscovery discovery;
protected ConnectionPoolConfiguration cpConfig;
protected AstyanaxConfiguration asConfig;
protected String clusterName;
protected String keyspaceName;
protected KeyspaceTracerFactory tracerFactory = EmptyKeyspaceTracerFactory.getInstance();
protected Supplier<List<Host>> hostSupplier;
protected ConnectionPoolMonitor monitor = new CountingConnectionPoolMonitor();
public Builder forCluster(String clusterName) {
this.clusterName = clusterName;
return this;
}
public Builder forKeyspace(String keyspaceName) {
this.keyspaceName = keyspaceName;
return this;
}
public Builder withConnectionPoolConfiguration(ConnectionPoolConfiguration cpConfig) {
this.cpConfig = cpConfig;
return this;
}
public Builder withAstyanaxConfiguration(AstyanaxConfiguration asConfig) {
this.asConfig = asConfig;
return this;
}
public Builder withHostSupplier(Supplier<List<Host>> supplier) {
this.hostSupplier = supplier;
return this;
}
public Builder withTracerFactory(KeyspaceTracerFactory tracerFactory) {
this.tracerFactory = tracerFactory;
return this;
}
public Builder withConnectionPoolMonitor(ConnectionPoolMonitor monitor) {
this.monitor = monitor;
return this;
}
public NodeDiscoveryType getNodeDiscoveryType() {
if (cpConfig.getSeeds() != null) {
if (asConfig.getConnectionPoolType() == ConnectionPoolType.TOKEN_AWARE)
return NodeDiscoveryType.RING_DESCRIBE;
}
else {
if (asConfig.getConnectionPoolType() == ConnectionPoolType.TOKEN_AWARE) {
return NodeDiscoveryType.TOKEN_AWARE;
}
else {
return NodeDiscoveryType.DISCOVERY_SERVICE;
}
}
return asConfig.getDiscoveryType();
}
protected <T> ConnectionPool<T> createConnectionPool(ConnectionFactory<T> connectionFactory) {
ConnectionPool<T> connectionPool = null;
// HACK to get the CqlFamilyFactory working with AstyanaxContext
if (connectionFactory.getClass().getName().contains("CqlFamilyFactory")) {
return new ConnectionPoolProxy<T>(cpConfig, connectionFactory, monitor);
}
switch (asConfig.getConnectionPoolType()) {
case TOKEN_AWARE:
connectionPool = new TokenAwareConnectionPoolImpl<T>(cpConfig, connectionFactory, monitor);
break;
case BAG:
connectionPool = new BagOfConnectionsConnectionPoolImpl<T>(cpConfig, connectionFactory, monitor);
break;
case ROUND_ROBIN:
default:
connectionPool = new RoundRobinConnectionPoolImpl<T>(cpConfig, connectionFactory, monitor);
break;
}
if (hostSupplier != null) {
connectionPool.setHosts(hostSupplier.get());
}
return connectionPool;
}
public <T> AstyanaxContext<Keyspace> buildKeyspace(AstyanaxTypeFactory<T> factory) {
this.cpConfig.initialize();
ConnectionPool<T> cp = createConnectionPool(factory.createConnectionFactory(asConfig, cpConfig, tracerFactory,
monitor));
this.cp = cp;
final Keyspace keyspace = factory.createKeyspace(keyspaceName, cp, asConfig, tracerFactory);
Supplier<List<Host>> supplier = null;
switch (getNodeDiscoveryType()) {
case DISCOVERY_SERVICE:
Preconditions.checkNotNull(hostSupplier, "Missing host name supplier");
supplier = hostSupplier;
break;
case RING_DESCRIBE:
supplier = new RingDescribeHostSupplier(keyspace, cpConfig.getPort(), cpConfig.getLocalDatacenter());
break;
case TOKEN_AWARE:
if (hostSupplier == null) {
supplier = new RingDescribeHostSupplier(keyspace, cpConfig.getPort(), cpConfig.getLocalDatacenter());
}
else {
supplier = new FilteringHostSupplier(new RingDescribeHostSupplier(keyspace, cpConfig.getPort(), cpConfig.getLocalDatacenter()),
hostSupplier);
}
break;
case NONE:
supplier = null;
break;
}
if (supplier != null) {
discovery = new NodeDiscoveryImpl(StringUtils.join(Arrays.asList(clusterName, keyspaceName), "_"),
asConfig.getDiscoveryDelayInSeconds() * 1000, supplier, cp);
}
return new AstyanaxContext<Keyspace>(this, keyspace);
}
public <T> AstyanaxContext<Cluster> buildCluster(AstyanaxTypeFactory<T> factory) {
this.cpConfig.initialize();
ConnectionPool<T> cp = createConnectionPool(factory.createConnectionFactory(asConfig, cpConfig, tracerFactory,
monitor));
this.cp = cp;
if (hostSupplier != null) {
discovery = new NodeDiscoveryImpl(clusterName, asConfig.getDiscoveryDelayInSeconds() * 1000,
hostSupplier, cp);
}
return new AstyanaxContext<Cluster>(this, factory.createCluster(cp, asConfig, tracerFactory));
}
}
private AstyanaxContext(Builder builder, T client) {
this.cpConfig = builder.cpConfig;
this.asConfig = builder.asConfig;
this.cp = builder.cp;
this.clusterName = builder.clusterName;
this.keyspaceName = builder.keyspaceName;
this.client = client;
this.discovery = builder.discovery;
this.monitor = builder.monitor;
}
/**
* @deprecated This should be called getClient
* @return
*/
public T getEntity() {
return getClient();
}
public T getClient() {
return this.client;
}
public ConnectionPool<?> getConnectionPool() {
return this.cp;
}
public ConnectionPoolConfiguration getConnectionPoolConfiguration() {
return cpConfig;
}
public AstyanaxConfiguration getAstyanaxConfiguration() {
return asConfig;
}
public NodeDiscovery getNodeDiscovery() {
return this.discovery;
}
public ConnectionPoolMonitor getConnectionPoolMonitor() {
return this.monitor;
}
public void start() {
cp.start();
if (discovery != null)
discovery.start();
}
public void shutdown() {
if (discovery != null)
discovery.shutdown();
cp.shutdown();
}
public String getClusterName() {
return this.clusterName;
}
public String getKeyspaceName() {
return this.keyspaceName;
}
}
| 7,762 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/ThreadLocalMutationBatchManager.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.retry.RetryPolicy;
/**
* Simple mutation batch using thread local storage to keeps track of one
* mutation per thread
*
* @author elandau
*
*/
public class ThreadLocalMutationBatchManager implements MutationBatchManager {
private ThreadLocal<MutationBatch> batches = new ThreadLocal<MutationBatch>();
private final Keyspace keyspace;
private final ConsistencyLevel cl;
private final RetryPolicy retryPolicy;
public ThreadLocalMutationBatchManager(Keyspace keyspace, ConsistencyLevel cl) {
this(keyspace, cl, null);
}
public ThreadLocalMutationBatchManager(Keyspace keyspace, ConsistencyLevel cl, RetryPolicy retryPolicy) {
this.keyspace = keyspace;
this.cl = cl;
this.retryPolicy = retryPolicy;
}
@Override
public MutationBatch getSharedMutationBatch() {
MutationBatch mb = batches.get();
if (mb == null) {
mb = keyspace.prepareMutationBatch().setConsistencyLevel(cl);
if (retryPolicy != null)
mb.withRetryPolicy(retryPolicy);
batches.set(mb);
}
return mb;
}
@Override
public MutationBatch getNewMutationBatch() {
return keyspace.prepareMutationBatch().setConsistencyLevel(cl);
}
@Override
public void commitSharedMutationBatch() throws ConnectionException {
MutationBatch mb = batches.get();
if (mb != null) {
mb.execute();
batches.remove();
}
}
@Override
public void discard() {
batches.remove();
}
}
| 7,763 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/WriteAheadLog.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.WalException;
/**
* Base interface for a write ahead log. The purpose of the WAL is to provide
* atomicity and durability when writing to Cassandra. Before writing to
* cassandra a record is written to the WAL which is assumed to stable storage
* able to survive from a crash or hardware failure. After a crash the system
* will inspect the WAL for records and replay them. If a record is successfully
* written to cassandra it will be removed from the WAL.
*
* @author elandau
*
*/
public interface WriteAheadLog {
/**
* Add an entry to WAL before it is sent to Cassandra.
*
* @param batch
* @return
*/
WriteAheadEntry createEntry() throws WalException;
/**
* Remove an entry from the WAL after it was successfully written to
* cassandra
*
* @param entry
*/
void removeEntry(WriteAheadEntry entry);
/**
* Read the next entry to retry from the wall. Call remove if successful or
* retryEntry if unable to write to cassandra.
*
* @return
*/
WriteAheadEntry readNextEntry();
/**
* Retry an entry retrieved by calling getNextEntry();
*
* @param entry
*/
void retryEntry(WriteAheadEntry entry);
}
| 7,764 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/KeyspaceTracerFactory.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.model.ColumnFamily;
/**
* TODO: Rename to AstyanaxTracerFactory
*
* @author elandau
*
*/
public interface KeyspaceTracerFactory {
/**
* Create a tracer for cluster level operations
*
* @param type
* @return
*/
CassandraOperationTracer newTracer(CassandraOperationType type);
/**
* Create a tracer for a column family operation
*
* @param type
* @param columnFamily
* @return
*/
CassandraOperationTracer newTracer(CassandraOperationType type, ColumnFamily<?, ?> columnFamily);
}
| 7,765 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/WriteAheadEntry.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.WalException;
/**
*
* @author elandau
*/
public interface WriteAheadEntry {
/**
* Fill a MutationBatch from the data in this entry
*
* @param mutation
*/
void readMutation(MutationBatch mutation) throws WalException;
/**
* Write the contents of this mutation to the WAL entry. Shall be called
* only once.
*
* @param mutation
* @throws WalException
*/
void writeMutation(MutationBatch mutation) throws WalException;
}
| 7,766 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/ColumnMutation.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.retry.RetryPolicy;
public interface ColumnMutation {
ColumnMutation setConsistencyLevel(ConsistencyLevel consistencyLevel);
ColumnMutation withRetryPolicy(RetryPolicy retry);
/**
* Change the default timestamp from the clock with a user supplied timestamp.
*
* @param timestamp Timestamp in microseconds
* @return
*/
ColumnMutation withTimestamp(long timestamp);
Execution<Void> putValue(String value, Integer ttl);
Execution<Void> putValue(byte[] value, Integer ttl);
Execution<Void> putValue(byte value, Integer ttl);
Execution<Void> putValue(short value, Integer ttl);
Execution<Void> putValue(int value, Integer ttl);
Execution<Void> putValue(long value, Integer ttl);
Execution<Void> putValue(boolean value, Integer ttl);
Execution<Void> putValue(ByteBuffer value, Integer ttl);
Execution<Void> putValue(Date value, Integer ttl);
Execution<Void> putValue(float value, Integer ttl);
Execution<Void> putValue(double value, Integer ttl);
Execution<Void> putValue(UUID value, Integer ttl);
<T> Execution<Void> putValue(T value, Serializer<T> serializer, Integer ttl);
Execution<Void> putEmptyColumn(Integer ttl);
Execution<Void> incrementCounterColumn(long amount);
Execution<Void> deleteColumn();
Execution<Void> deleteCounterColumn();
}
| 7,767 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/ColumnListMutation.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import com.netflix.astyanax.model.ColumnPath;
/**
* Abstraction for batching column operations on a single row.
*
* @author elandau
*
* @param <C>
*/
public interface ColumnListMutation<C> {
/**
* Generic call to insert a column value with a custom serializer. User this
* only when you need a custom serializer otherwise use the overloaded
* putColumn calls to insert common value types.
*
* @param <V> The value type
* @param columnName The column name
* @param value The value
* @param valueSerializer Serializer used to convert value to internal ByteBuffer
* @param ttl Optional TTL, null for none
*/
<V> ColumnListMutation<C> putColumn(C columnName, V value, Serializer<V> valueSerializer, Integer ttl);
<V> ColumnListMutation<C> putColumnIfNotNull(C columnName, V value, Serializer<V> valueSerializer, Integer ttl);
/**
* @deprecated Super columns are being phased out. Use composite columns
* instead.
*/
<SC> ColumnListMutation<SC> withSuperColumn(ColumnPath<SC> superColumnPath);
ColumnListMutation<C> putColumn(C columnName, String value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, String value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, String value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, String value);
ColumnListMutation<C> putCompressedColumn(C columnName, String value, Integer ttl);
ColumnListMutation<C> putCompressedColumn(C columnName, String value);
ColumnListMutation<C> putCompressedColumnIfNotNull(C columnName, String value, Integer ttl);
ColumnListMutation<C> putCompressedColumnIfNotNull(C columnName, String value);
ColumnListMutation<C> putColumn(C columnName, byte[] value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, byte[] value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, byte[] value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, byte[] value);
ColumnListMutation<C> putColumn(C columnName, byte value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, byte value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Byte value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Byte value);
ColumnListMutation<C> putColumn(C columnName, short value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, short value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Short value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Short value);
ColumnListMutation<C> putColumn(C columnName, int value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, int value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Integer value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Integer value);
ColumnListMutation<C> putColumn(C columnName, long value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, long value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Long value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Long value);
ColumnListMutation<C> putColumn(C columnName, boolean value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, boolean value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Boolean value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Boolean value);
ColumnListMutation<C> putColumn(C columnName, ByteBuffer value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, ByteBuffer value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, ByteBuffer value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, ByteBuffer value);
ColumnListMutation<C> putColumn(C columnName, Date value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, Date value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Date value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Date value);
ColumnListMutation<C> putColumn(C columnName, float value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, float value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Float value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Float value);
ColumnListMutation<C> putColumn(C columnName, double value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, double value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Double value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, Double value);
ColumnListMutation<C> putColumn(C columnName, UUID value, Integer ttl);
ColumnListMutation<C> putColumn(C columnName, UUID value);
ColumnListMutation<C> putColumnIfNotNull(C columnName, UUID value, Integer ttl);
ColumnListMutation<C> putColumnIfNotNull(C columnName, UUID value);
ColumnListMutation<C> putEmptyColumn(C columnName, Integer ttl);
ColumnListMutation<C> putEmptyColumn(C columnName);
ColumnListMutation<C> incrementCounterColumn(C columnName, long amount);
/**
* Insert a delete column mutation. Note that you must be careful when deleting
* and adding the same column on the same mutation. For the most part all columns
* will have the same timestamp so only the first operation will be performed.
* @param columnName
* @return
*/
ColumnListMutation<C> deleteColumn(C columnName);
/**
* The timestamp for all subsequent column operation in this ColumnListMutation
* This timestamp does not affect the current timestamp for the entire MutationBatch
* @param timestamp New timestamp in microseconds
*/
ColumnListMutation<C> setTimestamp(long timestamp);
/**
* Deletes all columns at the current column path location. Delete at the
* root of a row effectively deletes the entire row. This operation also
* increments the internal timestamp by 1 so new mutations can be added to
* this row.
*/
ColumnListMutation<C> delete();
/**
* Set the default TTL to use when null is specified to a column insert. The
* default TTL is null, which means no TTL.
*
* @param ttl Timeout value in seconds
*/
ColumnListMutation<C> setDefaultTtl(Integer ttl);
}
| 7,768 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/RowCopier.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
public interface RowCopier<K, C> extends Execution<Void> {
RowCopier<K,C> withOriginalTimestamp(boolean useOriginalTimestamp);
}
| 7,769 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/AstyanaxConfiguration.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.util.concurrent.ExecutorService;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.retry.RetryPolicy;
/**
* Interface defining all astyanax API configuration parameters.
*
* @author elandau
*
*/
public interface AstyanaxConfiguration {
/**
* @return
*/
RetryPolicy getRetryPolicy();
/**
* Default consistency level used when reading from the cluster. This value
* can be overwritten on the Query operations (returned by
* Keyspace.prepareXXQuery) by calling Query.setConsistencyLevel().
*/
ConsistencyLevel getDefaultReadConsistencyLevel();
/**
* Default consistency level used when reading from the cluster. This value
* can be overwritten on MutationBatch operation (returned by
* Keyspace.prepareMutationBatch) by calling
* MutationBatch.setConsistencyLevel().
*/
ConsistencyLevel getDefaultWriteConsistencyLevel();
/**
* Return clock to use when setting timestamps for column insertion and
* deletion operations.
*/
Clock getClock();
/**
* Return the maximum number of allows async threads to executeAsync()
*/
ExecutorService getAsyncExecutor();
/**
* Fixed delay for node disocvery refresh
*/
int getDiscoveryDelayInSeconds();
/**
* Get type of node discovery to perform
*/
NodeDiscoveryType getDiscoveryType();
/**
* Type of connection pool to use for this instance
*/
ConnectionPoolType getConnectionPoolType();
/**
* Get the CQL version to set when sending CQL queries
* @param cqlVersion
*/
String getCqlVersion();
/**
* @return Returns the major cassandra version (x.x) with which this client is communicating.
* This is a hack for backwards compatibility when APIs break between version
*/
String getTargetCassandraVersion();
/**
* @return Return the partitioner implementation for the specified partitioner name
* @throws Exception
*/
Partitioner getPartitioner(String partitionerName) throws Exception;
/**
* @return Return maximum thrift packet size
*/
int getMaxThriftSize();
}
| 7,770 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/CassandraOperationType.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
public enum CassandraOperationType {
ATOMIC_BATCH_MUTATE (CassandraOperationCategory.WRITE),
BATCH_MUTATE (CassandraOperationCategory.WRITE),
GET_ROW (CassandraOperationCategory.READ),
GET_ROWS_RANGE (CassandraOperationCategory.READ),
GET_ROWS_SLICE (CassandraOperationCategory.READ),
GET_ROWS_BY_INDEX (CassandraOperationCategory.READ),
GET_COLUMN (CassandraOperationCategory.READ),
CQL (CassandraOperationCategory.CQL),
DESCRIBE_RING (CassandraOperationCategory.OTHER),
COUNTER_MUTATE (CassandraOperationCategory.WRITE),
COLUMN_MUTATE (CassandraOperationCategory.WRITE),
COLUMN_DELETE (CassandraOperationCategory.WRITE),
COLUMN_INSERT (CassandraOperationCategory.WRITE),
GET_COLUMN_COUNT (CassandraOperationCategory.READ),
COPY_TO (CassandraOperationCategory.WRITE),
DESCRIBE_KEYSPACE (CassandraOperationCategory.OTHER),
TRUNCATE (CassandraOperationCategory.OTHER),
DESCRIBE_CLUSTER (CassandraOperationCategory.OTHER),
DESCRIBE_VERSION (CassandraOperationCategory.OTHER),
DESCRIBE_SNITCH (CassandraOperationCategory.OTHER),
DESCRIBE_PARTITIONER(CassandraOperationCategory.OTHER),
DESCRIBE_SCHEMA_VERSION(CassandraOperationCategory.OTHER),
GET_VERSION (CassandraOperationCategory.OTHER),
DROP_COLUMN_FAMILY (CassandraOperationCategory.OTHER),
DESCRIBE_KEYSPACES (CassandraOperationCategory.OTHER),
DROP_KEYSPACE (CassandraOperationCategory.OTHER),
ADD_COLUMN_FAMILY (CassandraOperationCategory.OTHER),
UPDATE_COLUMN_FAMILY(CassandraOperationCategory.OTHER),
ADD_KEYSPACE (CassandraOperationCategory.OTHER),
UPDATE_KEYSPACE (CassandraOperationCategory.OTHER),
SET_KEYSPACE (CassandraOperationCategory.OTHER),
TEST (CassandraOperationCategory.OTHER),
;
CassandraOperationCategory category;
CassandraOperationType(CassandraOperationCategory category) {
this.category = category;
}
public CassandraOperationCategory getCategory() {
return this.category;
}
}
| 7,771 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/Serializer.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* DataSerializer.java
* dsmirnov Apr 4, 2011
*/
package com.netflix.astyanax;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.netflix.astyanax.serializers.ComparatorType;
/**
* Serializes a type T from the given bytes, or vice a versa.
*
* In cassandra column names and column values (and starting with 0.7.0 row
* keys) are all byte[]. To allow type safe conversion in java and keep all
* conversion code in one place we define the Extractor interface. Implementors
* of the interface define type conversion according to their domains. A
* predefined set of common extractors can be found in the extractors package,
* for example {@link StringSerializer}.
*
* @author Ran Tavory
*
* @param <T>
* The type to which data extraction should work.
*/
public interface Serializer<T> {
/**
* Extract bytes from the obj of type T
*
* @param obj
* @return
*/
ByteBuffer toByteBuffer(T obj);
byte[] toBytes(T obj);
T fromBytes(byte[] bytes);
/**
* Extract an object of type T from the bytes.
*
* @param bytes
* @return
*/
T fromByteBuffer(ByteBuffer byteBuffer);
Set<ByteBuffer> toBytesSet(List<T> list);
List<T> fromBytesSet(Set<ByteBuffer> list);
<V> Map<ByteBuffer, V> toBytesMap(Map<T, V> map);
<V> Map<T, V> fromBytesMap(Map<ByteBuffer, V> map);
List<ByteBuffer> toBytesList(List<T> list);
List<ByteBuffer> toBytesList(Collection<T> list);
List<ByteBuffer> toBytesList(Iterable<T> list);
List<T> fromBytesList(List<ByteBuffer> list);
ComparatorType getComparatorType();
/**
* Return the byte buffer for the next value in sorted order for the
* matching comparator type. This is used for paginating columns.
*
* @param byteBuffer
* @return
*/
ByteBuffer getNext(ByteBuffer byteBuffer);
/**
* Create a ByteBuffer by first parsing the type out of a string
*
* @param string
* @return
*/
ByteBuffer fromString(String string);
String getString(ByteBuffer byteBuffer);
}
| 7,772 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/Keyspace.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.netflix.astyanax.connectionpool.ConnectionPool;
import com.netflix.astyanax.connectionpool.Operation;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.TokenRange;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.OperationException;
import com.netflix.astyanax.cql.CqlStatement;
import com.netflix.astyanax.ddl.KeyspaceDefinition;
import com.netflix.astyanax.ddl.SchemaChangeResult;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.query.ColumnFamilyQuery;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.serializers.UnknownComparatorException;
/**
* Interface providing access to mutate and query columns from a cassandra
* keyspace.
*
* @author elandau
*
*/
public interface Keyspace {
/**
* Return the configuration object used to set up this keyspace
*/
AstyanaxConfiguration getConfig();
/**
* Returns keyspace name
*/
String getKeyspaceName();
/**
* Return the partitioner for this keyspace. The partitioner is mainly used for reading
* all rows.
*
* @return
* @throws ConnectionException
*/
Partitioner getPartitioner() throws ConnectionException;
/**
* Describe the partitioner used by the cluster
* @throws ConnectionException
*/
String describePartitioner() throws ConnectionException;
/**
* Get a list of all tokens and their endpoints. This call will return this list of ALL nodes
* in the cluster, including other regions. If you are only interested in the subset of
* nodes for a specific region then use describeRing(dc);
* @throws ConnectionException
*/
List<TokenRange> describeRing() throws ConnectionException;
/**
* Get a list of all tokens and their endpoints for a specific dc only.
*
* @param dc - null for all dcs
* @throws ConnectionException
*/
List<TokenRange> describeRing(String dc) throws ConnectionException;
/**
* Get a list of tokens and their endpoints for a specific dc/rack combination.
* @param dc
* @throws ConnectionException
*/
List<TokenRange> describeRing(String dc, String rack) throws ConnectionException;
/**
* Describe the ring but use the last locally cached version if available.
* @param cached
* @throws ConnectionException
*/
List<TokenRange> describeRing(boolean cached) throws ConnectionException;
/**
* Return a complete description of the keyspace and its column families
*
* @throws ConnectionException
*/
KeyspaceDefinition describeKeyspace() throws ConnectionException;
/**
* Get this keyspace's configuration (including column families) as flattened
* properties
* @throws ConnectionException
*/
Properties getKeyspaceProperties() throws ConnectionException;
/**
* Get the properties for a column family
*
* @param columnFamily
* @return
* @throws ConnectionException
*/
Properties getColumnFamilyProperties(String columnFamily) throws ConnectionException;
/**
* Return the serializer package for a specific column family. This requires
* a call to the Cassandra cluster and is therefore cached to reduce load on
* Cassandra and since this data rarely changes.
*
* @param columnFamily
* @param ignoreErrors
* @throws ConnectionException
*/
SerializerPackage getSerializerPackage(String cfName, boolean ignoreErrors) throws ConnectionException,
UnknownComparatorException;
/**
* Prepare a batch mutation object. It is possible to create multiple batch
* mutations and later merge them into a single mutation by calling
* mergeShallow on a batch mutation object.
* @throws ConnectionException
*/
MutationBatch prepareMutationBatch();
/**
* Starting point for constructing a query. From the column family the
* client can perform all 4 types of queries: get column, get key slice, get
* key range and and index query.
*
* @param <K>
* @param <C>
* @param cf
* Column family to be used for the query. The key and column
* serializers in the ColumnFamily are automatically used while
* constructing the query and the response.
*/
<K, C> ColumnFamilyQuery<K, C> prepareQuery(ColumnFamily<K, C> cf);
/**
* Mutation for a single column
*
* @param <K>
* @param <C>
* @param columnFamily
*/
<K, C> ColumnMutation prepareColumnMutation(ColumnFamily<K, C> columnFamily, K rowKey, C column);
/**
* Delete all rows in a column family
*
* @param <K>
* @param <C>
* @param columnFamily
* @throws ConnectionException
* @throws OperationException
*/
<K, C> OperationResult<Void> truncateColumnFamily(ColumnFamily<K, C> columnFamily) throws OperationException,
ConnectionException;
/**
* Delete all rows in a column family
*
* @param columnFamily
* @throws ConnectionException
* @throws OperationException
*/
OperationResult<Void> truncateColumnFamily(String columnFamily) throws ConnectionException;
/**
* This method is used for testing purposes only. It is used to inject
* errors in the connection pool.
*
* @param operation
* @throws ConnectionException
*/
OperationResult<Void> testOperation(Operation<?, ?> operation) throws ConnectionException;
/**
* This method is used for testing purposes only. It is used to inject
* errors in the connection pool.
*
* @param operation
* @throws ConnectionException
*/
OperationResult<Void> testOperation(Operation<?, ?> operation, RetryPolicy retry) throws ConnectionException;
/**
* Create a column family in this keyspace
*
* @param columnFamily
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
<K, C> OperationResult<SchemaChangeResult> createColumnFamily(ColumnFamily<K, C> columnFamily, Map<String, Object> options) throws ConnectionException ;
/**
* Create a column family in this keyspace using the provided properties.
* @param props
* @return
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createColumnFamily(Properties props) throws ConnectionException;
/**
* Create a column family from the provided options
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createColumnFamily(Map<String, Object> options) throws ConnectionException ;
/**
* Update the column family in cassandra
*
* @param columnFamily
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
<K, C> OperationResult<SchemaChangeResult> updateColumnFamily(ColumnFamily<K, C> columnFamily, Map<String, Object> options) throws ConnectionException ;
/**
* Update the column family definition from properties
* @param props
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> updateColumnFamily(Properties props) throws ConnectionException ;
/**
* Update the column family definition from a map of string to object
* @param props
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> updateColumnFamily(Map<String, Object> options) throws ConnectionException;
/**
* Drop a column family from this keyspace
* @param columnFamilyName
*/
OperationResult<SchemaChangeResult> dropColumnFamily(String columnFamilyName) throws ConnectionException ;
/**
* Drop a column family from this keyspace
* @param columnFamily
*/
<K, C> OperationResult<SchemaChangeResult> dropColumnFamily(ColumnFamily<K, C> columnFamily) throws ConnectionException ;
/**
* Create the keyspace in cassandra. This call will only create the keyspace and not
* any column families. Once the keyspace has been created then call createColumnFamily
* for each CF you want to create.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createKeyspace(Map<String, Object> options) throws ConnectionException ;
/**
* Create the keyspace in cassandra if it does not exist. This call will only create the keyspace and not
* any column families. Once the keyspace has been created then call createColumnFamily
* for each CF you want to create.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> createKeyspaceIfNotExists(Map<String, Object> options) throws ConnectionException ;
/**
* Create the keyspace in cassandra. This call will create the keyspace and any column families.
* @param properties
* @return
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createKeyspace(Properties properties) throws ConnectionException;
/**
* Create a keyspace if it does not exist.
* @param properties
* @return
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createKeyspaceIfNotExists(Properties properties) throws ConnectionException;
/**
* Bulk create for a keyspace and a bunch of column famlies
* @param options
* @param cfs
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createKeyspace(Map<String, Object> options, Map<ColumnFamily, Map<String, Object>> cfs) throws ConnectionException ;
/**
* Bulk create for a keyspace if it does not exist and a bunch of column famlies
* @param options
* @param cfs
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> createKeyspaceIfNotExists(Map<String, Object> options, Map<ColumnFamily, Map<String, Object>> cfs) throws ConnectionException ;
/**
* Update the keyspace in cassandra.
* @param options - For list of options see http://www.datastax.com/docs/1.0/configuration/storage_configuration
*/
OperationResult<SchemaChangeResult> updateKeyspace(Map<String, Object> options) throws ConnectionException ;
/**
* Update the keyspace definition using properties. Only keyspace options and NO column family options
* may be set here.
*
* @param props
* @return
* @throws ConnectionException
*/
OperationResult<SchemaChangeResult> updateKeyspace(Properties props) throws ConnectionException;
/**
* Drop this keyspace from cassandra
*/
OperationResult<SchemaChangeResult> dropKeyspace() throws ConnectionException ;
/**
* List all schema versions in the cluster. Under normal conditions there
* should only be one schema.
* @return
* @throws ConnectionException
*/
Map<String, List<String>> describeSchemaVersions() throws ConnectionException;
/**
* Prepare a CQL Statement on the keyspace
* @return
*/
CqlStatement prepareCqlStatement();
/**
* Exposes the internal connection pool to the client.
* @return
* @throws ConnectionException
*/
ConnectionPool<?> getConnectionPool() throws ConnectionException;
}
| 7,773 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/CassandraOperationCategory.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
public enum CassandraOperationCategory {
READ,
WRITE,
OTHER,
CQL,
}
| 7,774 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/SerializerPackage.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import java.nio.ByteBuffer;
import java.util.Set;
/**
* Grouping of serializers for a single column family. Use this only for
* implementing advanced data models.
*
* @author elandau
*
*/
public interface SerializerPackage {
/**
* @return Return the serializer for keys
*/
Serializer<?> getKeySerializer();
/**
* @deprecated use getColumnNameSerializer()
*/
@Deprecated
Serializer<?> getColumnSerializer();
/**
* @return Return serializer for column names
*/
Serializer<?> getColumnNameSerializer();
/**
* @deprecated use getDefaultValueSerializer()
*/
@Deprecated
Serializer<?> getValueSerializer();
/**
* @return Return the default value serializer
*/
Serializer<?> getDefaultValueSerializer();
/**
* @deprecated use getColumnSerializer()
*/
@Deprecated
Serializer<?> getValueSerializer(ByteBuffer columnName);
/**
* @return Return the value serializer for the specified column name
*
* @param columnName
*/
Serializer<?> getColumnSerializer(ByteBuffer columnName);
/**
* @deprecated use getColumnSerializer
*/
@Deprecated
Serializer<?> getValueSerializer(String columnName);
/**
* @return Return the value serializer for the specified column name
*
* @param columnName
*/
Serializer<?> getColumnSerializer(String columnName);
/**
* @return Return the set of supported column names
*/
Set<ByteBuffer> getColumnNames();
/**
* @return Convert a key to a string using the package's key serializer
*
* @param key
*/
String keyAsString(ByteBuffer key);
/**
* Convert a column name to a string using the package's column serializer
*
* @param key
*/
String columnAsString(ByteBuffer column);
/**
* Convert a value to a string using the package's value serializer. Will
* use either a column specific serializer, if one was specified, or the
* default value serializer.
*
* @param key
*/
String valueAsString(ByteBuffer column, ByteBuffer value);
/**
* Convert a string key to a ByteBuffer using the package's key serializer
*
* @param key
*/
ByteBuffer keyAsByteBuffer(String key);
/**
* Convert a string column name to a ByteBuffer using the package's column
* serializer
*
* @param key
*/
ByteBuffer columnAsByteBuffer(String column);
/**
* Convert a string value to a string using the package's value serializer
*
* @param key
*/
ByteBuffer valueAsByteBuffer(ByteBuffer column, String value);
/**
* Convert a string value to a string using the package's value serializer
*
* @param column
* @param value
*/
ByteBuffer valueAsByteBuffer(String column, String value);
}
| 7,775 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/CassandraOperationTracer.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
/**
* Notification interface of success or failures executing keyspace operations.
*
* @author elandau
*
*/
public interface CassandraOperationTracer {
CassandraOperationTracer start();
void success();
void failure(ConnectionException e);
}
| 7,776 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/AstyanaxCheckpointManager.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.SortedMap;
import com.google.common.collect.Maps;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.query.CheckpointManager;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.LongSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
/**
* Track checkpoints in cassandra
*
* @author elandau
*
*/
public class AstyanaxCheckpointManager implements CheckpointManager {
private final ByteBuffer bbKey;
private final Keyspace keyspace;
private final ColumnFamily<ByteBuffer, String> columnFamily;
@SuppressWarnings("rawtypes")
private final static Comparator tokenComparator = new Comparator() {
@Override
public int compare(Object arg0, Object arg1) {
return new BigInteger((String)arg0).compareTo(new BigInteger((String)arg1));
}
};
public AstyanaxCheckpointManager(Keyspace keyspace, String columnFamily, String id) {
this(keyspace, columnFamily, StringSerializer.get().toByteBuffer(id));
}
public AstyanaxCheckpointManager(Keyspace keyspace, String columnFamily, Long id) {
this(keyspace, columnFamily, LongSerializer.get().toByteBuffer(id));
}
public AstyanaxCheckpointManager(Keyspace keyspace, String columnFamily, ByteBuffer bbKey) {
this.keyspace = keyspace;
this.bbKey = bbKey;
this.columnFamily = ColumnFamily.newColumnFamily(columnFamily, ByteBufferSerializer.get(), StringSerializer.get());
}
@Override
public void trackCheckpoint(String startToken, String checkpointToken) throws ConnectionException {
keyspace.prepareColumnMutation(columnFamily, bbKey, startToken).putValue(checkpointToken, null).execute();
}
@Override
public String getCheckpoint(String startToken) throws ConnectionException {
try {
return keyspace.prepareQuery(columnFamily).getKey(bbKey).getColumn(startToken).execute().getResult().getStringValue();
}
catch (NotFoundException e) {
return startToken;
}
}
@Override
public SortedMap<String, String> getCheckpoints() throws ConnectionException {
SortedMap<String, String> checkpoints = Maps.newTreeMap(tokenComparator);
for (Column<String> column : keyspace.prepareQuery(columnFamily).getKey(bbKey).execute().getResult()) {
checkpoints.put(column.getName(), column.getStringValue());
}
return checkpoints;
}
}
| 7,777 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/NoOpWriteAheadLog.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.WriteAheadEntry;
import com.netflix.astyanax.WriteAheadLog;
import com.netflix.astyanax.connectionpool.exceptions.WalException;
public class NoOpWriteAheadLog implements WriteAheadLog {
@Override
public WriteAheadEntry createEntry() throws WalException {
return new WriteAheadEntry() {
@Override
public void readMutation(MutationBatch mutation) throws WalException {
}
@Override
public void writeMutation(MutationBatch mutation) throws WalException {
}
};
}
@Override
public void removeEntry(WriteAheadEntry entry) {
}
@Override
public WriteAheadEntry readNextEntry() {
return null;
}
@Override
public void retryEntry(WriteAheadEntry entry) {
}
}
| 7,778 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/AckingQueue.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import java.util.concurrent.TimeUnit;
import com.netflix.astyanax.MutationBatch;
/**
* Abstraction for a durable queue requiring an ack to do the final remove
*
* @author elandau
*
*/
public interface AckingQueue {
/**
* Get the next item from the queue
*
* @param timeout
* @param units
* @return
*/
MutationBatch getNextMutation(long timeout, TimeUnit units) throws InterruptedException;
/**
* Insert an item into the queue
*
* @param m
* @throws Exception
*/
void pushMutation(MutationBatch m) throws Exception;
/**
* Ack a mutation so that it may be removed from the queue
*
* @param m
*/
void ackMutation(MutationBatch m) throws Exception;
/**
* Return a mutation that couldn't be retried for it be requeued and retryed
* later
*
* @param m
* @throws Exception
*/
void repushMutation(MutationBatch m) throws Exception;
/**
* Return the number of mutations in the queue
*
* @return
*/
int size();
}
| 7,779 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/PreparedIndexExpressionImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.UUID;
import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.query.IndexOperator;
import com.netflix.astyanax.query.PreparedIndexExpression;
import com.netflix.astyanax.query.PreparedIndexValueExpression;
import com.netflix.astyanax.query.PreparedIndexOperationExpression;
import com.netflix.astyanax.serializers.BooleanSerializer;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.BytesArraySerializer;
import com.netflix.astyanax.serializers.DateSerializer;
import com.netflix.astyanax.serializers.DoubleSerializer;
import com.netflix.astyanax.serializers.IntegerSerializer;
import com.netflix.astyanax.serializers.LongSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.serializers.UUIDSerializer;
public class PreparedIndexExpressionImpl<K, C> implements PreparedIndexExpression<K, C>,
PreparedIndexOperationExpression<K, C>, PreparedIndexValueExpression<K, C> {
private ByteBuffer value;
private ByteBuffer column;
private IndexOperator operator;
private final Serializer<C> columnSerializer;
public PreparedIndexExpressionImpl(Serializer<C> columnSerializer) {
this.columnSerializer = columnSerializer;
}
@Override
public PreparedIndexOperationExpression<K, C> whereColumn(C columnName) {
column = columnSerializer.toByteBuffer(columnName);
return this;
}
@Override
public ByteBuffer getColumn() {
return column;
}
@Override
public ByteBuffer getValue() {
return value;
}
@Override
public IndexOperator getOperator() {
return operator;
}
@Override
public PreparedIndexValueExpression<K, C> equals() {
operator = IndexOperator.EQ;
return this;
}
@Override
public PreparedIndexValueExpression<K, C> greaterThan() {
operator = IndexOperator.GT;
return this;
}
@Override
public PreparedIndexValueExpression<K, C> lessThan() {
operator = IndexOperator.LT;
return this;
}
@Override
public PreparedIndexValueExpression<K, C> greaterThanEquals() {
operator = IndexOperator.GTE;
return this;
}
@Override
public PreparedIndexValueExpression<K, C> lessThanEquals() {
operator = IndexOperator.LTE;
return this;
}
@Override
public PreparedIndexExpression<K, C> value(String value) {
this.value = StringSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(long value) {
this.value = LongSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(int value) {
this.value = IntegerSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(boolean value) {
this.value = BooleanSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(Date value) {
this.value = DateSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(byte[] value) {
this.value = BytesArraySerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(ByteBuffer value) {
this.value = ByteBufferSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(double value) {
this.value = DoubleSerializer.get().toByteBuffer(value);
return this;
}
@Override
public PreparedIndexExpression<K, C> value(UUID value) {
this.value = UUIDSerializer.get().toByteBuffer(value);
return this;
}
@Override
public <V> PreparedIndexExpression<K, C> value(V value, Serializer<V> valueSerializer) {
this.value = valueSerializer.toByteBuffer(value);
return this;
}
}
| 7,780 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/RingDescribeHostSupplier.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.connectionpool.Host;
import com.netflix.astyanax.connectionpool.TokenRange;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
/**
* HostSupplier that uses existing hosts in the connection pool to execute a ring
* describe and get the entire list of hosts and their tokens from Cassandra.
*
* @author elandau
*
*/
public class RingDescribeHostSupplier implements Supplier<List<Host>> {
private final static Logger LOG = LoggerFactory.getLogger(RingDescribeHostSupplier.class);
private final Keyspace keyspace;
private final int defaultPort;
private final String dc;
private final String rack;
private volatile List<Host> previousHosts;
public RingDescribeHostSupplier(Keyspace keyspace, int defaultPort, String dc, String rack) {
this.keyspace = keyspace;
this.defaultPort = defaultPort;
this.dc = dc;
this.rack = rack;
}
public RingDescribeHostSupplier(Keyspace keyspace, int defaultPort, String dc) {
this(keyspace, defaultPort, dc, null);
}
public RingDescribeHostSupplier(Keyspace keyspace, int defaultPort) {
this(keyspace, defaultPort, null, null);
}
@Override
public synchronized List<Host> get() {
try {
Map<String, Host> ipToHost = Maps.newHashMap();
for (TokenRange range : keyspace.describeRing(dc, rack)) {
for (String endpoint : range.getEndpoints()) {
Host host = ipToHost.get(endpoint);
if (host == null) {
host = new Host(endpoint, defaultPort);
ipToHost.put(endpoint, host);
}
host.getTokenRanges().add(range);
}
}
previousHosts = Lists.newArrayList(ipToHost.values());
return previousHosts;
}
catch (ConnectionException e) {
if (previousHosts == null) {
throw new RuntimeException(e);
}
LOG.warn("Failed to get hosts from " + keyspace.getKeyspaceName() + " via ring describe. Will use previously known ring instead");
return previousHosts;
}
}
}
| 7,781 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/impl/AstyanaxConfigurationImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.impl;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.astyanax.AstyanaxConfiguration;
import com.netflix.astyanax.Clock;
import com.netflix.astyanax.clock.MicrosecondsSyncClock;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.partitioner.BigInteger127Partitioner;
import com.netflix.astyanax.partitioner.Murmur3Partitioner;
import com.netflix.astyanax.partitioner.Partitioner;
import com.netflix.astyanax.retry.RetryPolicy;
import com.netflix.astyanax.retry.RunOnce;
public class AstyanaxConfigurationImpl implements AstyanaxConfiguration {
private ConsistencyLevel defaultReadConsistencyLevel = ConsistencyLevel.CL_ONE;
private ConsistencyLevel defaultWriteConsistencyLevel = ConsistencyLevel.CL_ONE;
private Clock clock = new MicrosecondsSyncClock();
private RetryPolicy retryPolicy = RunOnce.get();
private ExecutorService asyncExecutor = Executors.newFixedThreadPool(5,
new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("AstyanaxAsync-%d")
.build());
private NodeDiscoveryType discoveryType = NodeDiscoveryType.NONE;
private int discoveryIntervalInSeconds = 30;
private ConnectionPoolType connectionPoolType = ConnectionPoolType.ROUND_ROBIN;
private String cqlVersion = null;
private String targetCassandraVersion = "1.1";
private Map<String, Partitioner> partitioners = Maps.newHashMap();
private int maxThriftSize = 16384000;
public AstyanaxConfigurationImpl() {
partitioners.put("org.apache.cassandra.dht.RandomPartitioner",
BigInteger127Partitioner.get());
try {
partitioners.put("org.apache.cassandra.dht.Murmur3Partitioner",
Murmur3Partitioner.get());
}
catch (NoClassDefFoundError exception) {
// We ignore this for backwards compatiblity with pre 1.2 cassandra.
}
}
public AstyanaxConfigurationImpl setConnectionPoolType(ConnectionPoolType connectionPoolType) {
this.connectionPoolType = connectionPoolType;
return this;
}
@Override
public ConnectionPoolType getConnectionPoolType() {
return this.connectionPoolType;
}
@Override
public ConsistencyLevel getDefaultReadConsistencyLevel() {
return this.defaultReadConsistencyLevel;
}
public AstyanaxConfigurationImpl setDefaultReadConsistencyLevel(ConsistencyLevel cl) {
this.defaultReadConsistencyLevel = cl;
return this;
}
@Override
public ConsistencyLevel getDefaultWriteConsistencyLevel() {
return this.defaultWriteConsistencyLevel;
}
public AstyanaxConfigurationImpl setDefaultWriteConsistencyLevel(ConsistencyLevel cl) {
this.defaultWriteConsistencyLevel = cl;
return this;
}
@Override
public Clock getClock() {
return this.clock;
}
public AstyanaxConfigurationImpl setClock(Clock clock) {
this.clock = clock;
return this;
}
@Override
public ExecutorService getAsyncExecutor() {
return asyncExecutor;
}
public AstyanaxConfigurationImpl setAsyncExecutor(ExecutorService executor) {
this.asyncExecutor.shutdown();
this.asyncExecutor = executor;
return this;
}
@Override
public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
public AstyanaxConfigurationImpl setRetryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public int getDiscoveryDelayInSeconds() {
return discoveryIntervalInSeconds;
}
public AstyanaxConfigurationImpl setDiscoveryDelayInSeconds(int delay) {
this.discoveryIntervalInSeconds = delay;
return this;
}
@Override
public NodeDiscoveryType getDiscoveryType() {
return discoveryType;
}
public AstyanaxConfigurationImpl setDiscoveryType(NodeDiscoveryType discoveryType) {
this.discoveryType = discoveryType;
return this;
}
@Override
public String getCqlVersion() {
return cqlVersion;
}
public AstyanaxConfigurationImpl setCqlVersion(String cqlVersion) {
this.cqlVersion = cqlVersion;
return this;
}
@Override
public String getTargetCassandraVersion() {
return this.targetCassandraVersion;
}
public AstyanaxConfigurationImpl setTargetCassandraVersion(String version) {
this.targetCassandraVersion = version;
return this;
}
public AstyanaxConfigurationImpl registerPartitioner(String name, Partitioner partitioner) {
this.partitioners.put(name, partitioner);
return this;
}
public AstyanaxConfigurationImpl setPartitioners(Map<String, Partitioner> partitioners) {
this.partitioners.putAll(partitioners);
return this;
}
@Override
public Partitioner getPartitioner(String partitionerName) throws Exception {
Partitioner partitioner = partitioners.get(partitionerName);
if (partitioner == null)
throw new Exception("Unsupported partitioner " + partitionerName);
return partitioner;
}
public AstyanaxConfigurationImpl setMaxThriftSize(int maxthriftsize) {
this.maxThriftSize = maxthriftsize;
return this;
}
@Override
public int getMaxThriftSize() {
return maxThriftSize;
}
}
| 7,782 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Coercions.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import com.netflix.astyanax.ColumnListMutation;
import com.netflix.astyanax.model.Column;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.UUID;
class Coercions {
@SuppressWarnings("unchecked")
static <T> void setFieldFromColumn(T instance, Field field,
Column<String> column) {
Object objValue = null;
if ((field.getType() == Byte.class) || (field.getType() == Byte.TYPE)) {
objValue = (byte) (column.getIntegerValue() & 0xff);
} else if ((field.getType() == Boolean.class)
|| (field.getType() == Boolean.TYPE)) {
objValue = column.getBooleanValue();
} else if ((field.getType() == Short.class)
|| (field.getType() == Short.TYPE)) {
objValue = (short) (column.getIntegerValue() & 0xff);
} else if ((field.getType() == Integer.class)
|| (field.getType() == Integer.TYPE)) {
objValue = column.getIntegerValue();
} else if ((field.getType() == Long.class)
|| (field.getType() == Long.TYPE)) {
objValue = column.getLongValue();
} else if ((field.getType() == Float.class)
|| (field.getType() == Float.TYPE)) {
objValue = (float) column.getDoubleValue();
} else if ((field.getType() == Double.class)
|| (field.getType() == Double.TYPE)) {
objValue = column.getDoubleValue();
} else if (field.getType() == Date.class) {
objValue = column.getDateValue();
} else if (field.getType() == String.class) {
objValue = column.getStringValue();
} else if (field.getType() == byte[].class) {
objValue = column.getByteArrayValue();
} else if (field.getType() == UUID.class) {
objValue = column.getUUIDValue();
} else if (field.getType().isEnum()) {
objValue = Enum.valueOf((Class<? extends Enum>)field.getType(), column.getStringValue());
}
if (objValue == null) {
throw new UnsupportedOperationException(
"Field datatype not supported: " + field.getType().getCanonicalName());
}
try {
field.set(instance, objValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e); // should never get here
}
}
@SuppressWarnings("unchecked")
static <T> void setColumnMutationFromField(T instance, Field field,
String columnName, ColumnListMutation<String> mutation) {
try {
Object objValue = field.get(instance);
if (objValue != null) {
if ((objValue.getClass() == Byte.class)
|| (objValue.getClass() == Byte.TYPE)) {
mutation.putColumn(columnName, (Byte) objValue & 0xff, null);
} else if ((objValue.getClass() == Boolean.class)
|| (objValue.getClass() == Boolean.TYPE)) {
mutation.putColumn(columnName, (Boolean) objValue, null);
} else if ((objValue.getClass() == Short.class)
|| (objValue.getClass() == Short.TYPE)) {
mutation.putColumn(columnName, (Short) objValue, null);
} else if ((objValue.getClass() == Integer.class)
|| (objValue.getClass() == Integer.TYPE)) {
mutation.putColumn(columnName, (Integer) objValue, null);
} else if ((objValue.getClass() == Long.class)
|| (objValue.getClass() == Long.TYPE)) {
mutation.putColumn(columnName, (Long) objValue, null);
} else if ((objValue.getClass() == Float.class)
|| (objValue.getClass() == Float.TYPE)) {
mutation.putColumn(columnName, (Float) objValue, null);
} else if ((objValue.getClass() == Double.class)
|| (objValue.getClass() == Double.TYPE)) {
mutation.putColumn(columnName, (Double) objValue, null);
} else if (objValue.getClass() == Date.class) {
mutation.putColumn(columnName, (Date) objValue, null);
} else if (objValue.getClass() == String.class) {
mutation.putColumn(columnName, (String) objValue, null);
} else if(objValue.getClass() == byte[].class) {
mutation.putColumn(columnName, (byte[]) objValue, null);
} else if (objValue.getClass() == UUID.class) {
mutation.putColumn(columnName, (UUID) objValue, null);
} else if (objValue.getClass().isEnum()) {
mutation.putColumn(columnName, objValue.toString(), null);
} else {
throw new UnsupportedOperationException(
"Column datatype not supported: " + objValue.getClass().getCanonicalName());
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e); // should never get here
}
}
private Coercions() {
}
}
| 7,783 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Id.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Deprecated
/**
* This is a marker annotation for the field that should act as the ID column
* @deprecated please use javax.persistence.Id instead
*/
public @interface Id {
/**
* The name by which this particular field should be persisted as. By
* default, the name of the field is used
*
* @return column name
*/
String value() default "";
}
| 7,784 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingUtil.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import com.netflix.astyanax.ColumnListMutation;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Rows;
import java.util.List;
/**
* Higher level mapping functions. Methods that behave similar to a Map.
*
* @deprecated please use DefaultEntityManager
*/
@Deprecated
public class MappingUtil {
private final Keyspace keyspace;
private final MappingCache cache;
private final AnnotationSet<?, ?> annotationSet;
/**
* @param keyspace
* keyspace to use
*/
public MappingUtil(Keyspace keyspace) {
this(keyspace, null, null);
}
/**
* @param keyspace
* keyspace to use
* @param annotationSet
* annotation set to use
*/
public MappingUtil(Keyspace keyspace, AnnotationSet<?, ?> annotationSet) {
this(keyspace, null, annotationSet);
}
/**
* @param keyspace
* keyspace to use
* @param cache
* cache to use
*/
public MappingUtil(Keyspace keyspace, MappingCache cache) {
this(keyspace, cache, null);
}
/**
* @param keyspace
* keyspace to use
* @param cache
* cache to use
* @param annotationSet
* annotation set to use
*/
public MappingUtil(Keyspace keyspace, MappingCache cache,
AnnotationSet<?, ?> annotationSet) {
this.keyspace = keyspace;
this.cache = cache;
this.annotationSet = (annotationSet != null) ? annotationSet
: new DefaultAnnotationSet();
}
/**
* Remove the given item
*
* @param columnFamily
* column family of the item
* @param item
* the item to remove
* @throws Exception
* errors
*/
public <T, K> void remove(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
mutationBatch.withRow(columnFamily,
mapping.getIdValue(item, idFieldClass)).delete();
mutationBatch.execute();
}
/**
* Add/update the given item
*
* @param columnFamily
* column family of the item
* @param item
* the item to add/update
* @throws Exception
* errors
*/
public <T, K> void put(ColumnFamily<K, String> columnFamily, T item)
throws Exception {
@SuppressWarnings({ "unchecked" })
Class<T> clazz = (Class<T>) item.getClass();
Mapping<T> mapping = getMapping(clazz);
@SuppressWarnings({ "unchecked" })
Class<K> idFieldClass = (Class<K>) mapping.getIdFieldClass(); // safe -
// after
// erasure,
// this is
// all
// just
// Class
// anyway
MutationBatch mutationBatch = keyspace.prepareMutationBatch();
ColumnListMutation<String> columnListMutation = mutationBatch.withRow(
columnFamily, mapping.getIdValue(item, idFieldClass));
mapping.fillMutation(item, columnListMutation);
mutationBatch.execute();
}
/**
* Get the specified item by its key/id
*
* @param columnFamily
* column family of the item
* @param id
* id/key of the item
* @param itemClass
* item's class
* @return new instance with the item's columns propagated
* @throws Exception
* errors
*/
public <T, K> T get(ColumnFamily<K, String> columnFamily, K id,
Class<T> itemClass) throws Exception {
Mapping<T> mapping = getMapping(itemClass);
ColumnList<String> result = keyspace.prepareQuery(columnFamily)
.getKey(id).execute().getResult();
return mapping.newInstance(result);
}
/**
* Get all rows of the specified item
*
* @param columnFamily
* column family of the item
* @param itemClass
* item's class
* @return new instances with the item's columns propagated
* @throws Exception
* errors
*/
public <T, K> List<T> getAll(ColumnFamily<K, String> columnFamily,
Class<T> itemClass) throws Exception {
Mapping<T> mapping = getMapping(itemClass);
Rows<K, String> result = keyspace.prepareQuery(columnFamily)
.getAllRows().execute().getResult();
return mapping.getAll(result);
}
/**
* Return the mapping instance for the given class
*
* @param clazz
* the class
* @return mapping instance (new or from cache)
*/
public <T> Mapping<T> getMapping(Class<T> clazz) {
return (cache != null) ? cache.getMapping(clazz, annotationSet)
: new Mapping<T>(clazz, annotationSet);
}
}
| 7,785 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/AnnotationSet.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.mapping;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* Allows for any annotations to be used to mark columns in a bean
*/
@Deprecated
public interface AnnotationSet<ID extends Annotation, COLUMN extends Annotation> {
/**
* @return the Annotation class that marks a bean field as being the ID/Key
*/
public Class<ID> getIdAnnotation();
/**
* @return the Annotation class that marks a bean field as being
* persist-able.
*/
public Class<COLUMN> getColumnAnnotation();
/**
* Return the ID/Key name to use
*
* @param field
* the field from the bean
* @param annotation
* the id annotation
* @return name to use for the field (cannot be null)
*/
public String getIdName(Field field, ID annotation);
/**
* Return the column name to use for the given field. NOTE: if the field
* should not be persisted, return <code>null</code>.
*
* @param field
* the field from the bean
* @param annotation
* the column annotation
* @return name to use for the field or null
*/
public String getColumnName(Field field, COLUMN annotation);
}
| 7,786 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Mapping.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.netflix.astyanax.ColumnListMutation;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* <p>
* Utility for doing object/relational mapping between bean-like instances and
* Cassandra
* </p>
* <p/>
* <p>
* The mapper stores values in Cassandra and maps in/out to native types. Column
* names must be strings. Annotate your bean with {@link Id} and {@link Column}.
* Or, provide an {@link AnnotationSet} that defines IDs and Columns in your
* bean.
*
* @deprecated please use DefaultEntityManager instead
*/
@Deprecated
@SuppressWarnings({ "SuspiciousMethodCalls" })
public class Mapping<T> {
private final ImmutableMap<String, Field> fields;
private final String idFieldName;
private final Class<T> clazz;
/**
* If the ID column does not have a Column annotation, this column name is
* used
*/
public static final String DEFAULT_ID_COLUMN_NAME = "ID";
/**
* Convenience for allocation a mapping object
*
* @param clazz
* clazz type to map
* @return mapper
*/
public static <T> Mapping<T> make(Class<T> clazz, boolean includeParentFields) {
return new Mapping<T>(clazz, new DefaultAnnotationSet(), includeParentFields);
}
public static <T> Mapping<T> make(Class<T> clazz) {
return new Mapping<T>(clazz, new DefaultAnnotationSet(), false);
}
/**
* Convenience for allocation a mapping object
*
* @param clazz
* clazz type to map
* @param annotationSet
* annotations to use when analyzing a bean
* @return mapper
*/
public static <T> Mapping<T> make(Class<T> clazz, AnnotationSet<?, ?> annotationSet, boolean includeParentFields) {
return new Mapping<T>(clazz, annotationSet, includeParentFields);
}
public static <T> Mapping<T> make(Class<T> clazz, AnnotationSet<?, ?> annotationSet) {
return new Mapping(clazz, annotationSet, false);
}
/**
* @param clazz
* clazz type to map
*/
public Mapping(Class<T> clazz, boolean includeParentFields) {
this(clazz, new DefaultAnnotationSet(), includeParentFields);
}
public Mapping(Class<T> clazz) {
this(clazz, new DefaultAnnotationSet(), false);
}
/**
* @param clazz
* clazz type to map
* @param annotationSet
* annotations to use when analyzing a bean
*/
public Mapping(Class<T> clazz, AnnotationSet<?, ?> annotationSet, boolean includeParentFields) {
this.clazz = clazz;
String localKeyFieldName = null;
ImmutableMap.Builder<String, Field> builder = ImmutableMap.builder();
AtomicBoolean isKey = new AtomicBoolean();
Set<String> usedNames = Sets.newHashSet();
List<Field> allFields = getFields(clazz, includeParentFields);
for (Field field : allFields) {
String name = mapField(field, annotationSet, builder, usedNames, isKey);
if (isKey.get()) {
Preconditions.checkArgument(localKeyFieldName == null);
localKeyFieldName = name;
}
}
Preconditions.checkNotNull(localKeyFieldName);
fields = builder.build();
idFieldName = localKeyFieldName;
}
public Mapping(Class<T> clazz, AnnotationSet<?, ?> annotationSet) {
this(clazz, annotationSet, false);
}
private List<Field> getFields(Class clazz, boolean recursuvely) {
List<Field> allFields = new ArrayList<Field>();
if (clazz.getDeclaredFields() != null && clazz.getDeclaredFields().length > 0) {
for (Field field : clazz.getDeclaredFields()) {
allFields.add(field);
}
if (recursuvely && clazz.getSuperclass() != null) {
allFields.addAll(getFields(clazz.getSuperclass(), true));
}
}
return allFields;
}
/**
* Return the value for the ID/Key column from the given instance
*
* @param instance
* the instance
* @param valueClass
* type of the value (must match the actual native type in the
* instance's class)
* @return value
*/
public <V> V getIdValue(T instance, Class<V> valueClass) {
return getColumnValue(instance, idFieldName, valueClass);
}
/**
* Return the value for the given column from the given instance
*
* @param instance
* the instance
* @param columnName
* name of the column (must match a corresponding annotated field
* in the instance's class)
* @param valueClass
* type of the value (must match the actual native type in the
* instance's class)
* @return value
*/
public <V> V getColumnValue(T instance, String columnName,
Class<V> valueClass) {
Field field = fields.get(columnName);
if (field == null) {
throw new IllegalArgumentException("Column not found: "
+ columnName);
}
try {
return valueClass.cast(field.get(instance));
} catch (IllegalAccessException e) {
throw new RuntimeException(e); // should never get here
}
}
/**
* Set the value for the ID/Key column for the given instance
*
* @param instance
* the instance
* @param value
* The value (must match the actual native type in the instance's
* class)
*/
public <V> void setIdValue(T instance, V value) {
setColumnValue(instance, idFieldName, value);
}
/**
* Set the value for the given column for the given instance
*
* @param instance
* the instance
* @param columnName
* name of the column (must match a corresponding annotated field
* in the instance's class)
* @param value
* The value (must match the actual native type in the instance's
* class)
*/
public <V> void setColumnValue(T instance, String columnName, V value) {
Field field = fields.get(columnName);
if (field == null) {
throw new IllegalArgumentException("Column not found: "
+ columnName);
}
try {
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e); // should never get here
}
}
/**
* Map a bean to a column mutation. i.e. set the columns in the mutation to
* the corresponding values from the instance
*
* @param instance
* instance
* @param mutation
* mutation
*/
public void fillMutation(T instance, ColumnListMutation<String> mutation) {
for (String fieldName : getNames()) {
Coercions.setColumnMutationFromField(instance, fields.get(fieldName), fieldName, mutation);
}
}
/**
* Allocate a new instance and populate it with the values from the given
* column list
*
* @param columns
* column list
* @return the allocated instance
* @throws IllegalAccessException
* if a new instance could not be instantiated
* @throws InstantiationException
* if a new instance could not be instantiated
*/
public T newInstance(ColumnList<String> columns)
throws IllegalAccessException, InstantiationException {
return initInstance(clazz.newInstance(), columns);
}
/**
* Populate the given instance with the values from the given column list
*
* @param instance
* instance
* @param columns
* column this
* @return instance (as a convenience for chaining)
*/
public T initInstance(T instance, ColumnList<String> columns) {
for (com.netflix.astyanax.model.Column<String> column : columns) {
Field field = fields.get(column.getName());
if (field != null) { // otherwise it may be a column that was
// removed, etc.
Coercions.setFieldFromColumn(instance, field, column);
}
}
return instance;
}
/**
* Load a set of rows into new instances populated with values from the
* column lists
*
* @param rows
* the rows
* @return list of new instances
* @throws IllegalAccessException
* if a new instance could not be instantiated
* @throws InstantiationException
* if a new instance could not be instantiated
*/
public List<T> getAll(Rows<?, String> rows) throws InstantiationException,
IllegalAccessException {
List<T> list = Lists.newArrayList();
for (Row<?, String> row : rows) {
if (!row.getColumns().isEmpty()) {
list.add(newInstance(row.getColumns()));
}
}
return list;
}
/**
* Return the set of column names discovered from the bean class
*
* @return column names
*/
public Collection<String> getNames() {
return fields.keySet();
}
Class<?> getIdFieldClass() {
return fields.get(idFieldName).getType();
}
private <ID extends Annotation, COLUMN extends Annotation> String mapField(
Field field, AnnotationSet<ID, COLUMN> annotationSet,
ImmutableMap.Builder<String, Field> builder, Set<String> usedNames,
AtomicBoolean isKey) {
String mappingName = null;
ID idAnnotation = field.getAnnotation(annotationSet.getIdAnnotation());
COLUMN columnAnnotation = field.getAnnotation(annotationSet
.getColumnAnnotation());
if ((idAnnotation != null) && (columnAnnotation != null)) {
throw new IllegalStateException(
"A field cannot be marked as both an ID and a Column: "
+ field.getName());
}
if (idAnnotation != null) {
mappingName = annotationSet.getIdName(field, idAnnotation);
isKey.set(true);
} else {
isKey.set(false);
}
if ((columnAnnotation != null)) {
mappingName = annotationSet.getColumnName(field, columnAnnotation);
}
if (mappingName != null) {
Preconditions.checkArgument(
!usedNames.contains(mappingName.toLowerCase()), mappingName
+ " has already been used for this column family");
usedNames.add(mappingName.toLowerCase());
field.setAccessible(true);
builder.put(mappingName, field);
}
return mappingName;
}
}
| 7,787 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/MappingCache.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* Utility to cache mappers. There's a small performance hit to reflect on a
* bean. This cache, re-uses mappers for a given bean
*/
public class MappingCache {
private final Map<Class<?>, Mapping<?>> cache = Maps.newConcurrentMap();
/**
* Return a new or cached mapper
*
* @param clazz
* class for the mapper
* @return mapper
*/
public <T> Mapping<T> getMapping(Class<T> clazz, boolean includeParentFields) {
return getMapping(clazz, new DefaultAnnotationSet(), includeParentFields);
}
public <T> Mapping<T> getMapping(Class<T> clazz) {
return getMapping(clazz, false);
}
/**
* Return a new or cached mapper
*
* @param clazz
* class for the mapper
* @param annotationSet
* annotation set for the mapper
* @return mapper
*/
@SuppressWarnings({ "unchecked" })
public <T> Mapping<T> getMapping(Class<T> clazz,
AnnotationSet<?, ?> annotationSet, boolean includeParentFields) {
Mapping<T> mapping = (Mapping<T>) cache.get(clazz); // cast is safe as
// this instance is
// the one adding to
// the map
if (mapping == null) {
// multiple threads can get here but that's OK
mapping = new Mapping<T>(clazz, annotationSet, includeParentFields);
cache.put(clazz, mapping);
}
return mapping;
}
public <T> Mapping<T> getMapping(Class<T> clazz, AnnotationSet<?, ?> annotationSet) {
return getMapping(clazz, annotationSet, false);
}
}
| 7,788 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/Column.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import java.lang.annotation.*;
@Documented
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Deprecated
/**
* @deprecated please use javax.persistence.Column instead
*/
public @interface Column {
/**
* The name by which this particular field should be persisted as. By
* default, the name of the field is used
*
* @return column name
*/
String value() default "";
}
| 7,789 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/mapping/DefaultAnnotationSet.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.mapping;
import java.lang.reflect.Field;
/**
* The default annotation set. Supports {@link Id} and {@link Column}
*/
@Deprecated
public class DefaultAnnotationSet implements AnnotationSet<Id, Column> {
@Override
public Class<Id> getIdAnnotation() {
return Id.class;
}
@Override
public Class<Column> getColumnAnnotation() {
return Column.class;
}
@Override
public String getIdName(Field field, Id annotation) {
String name = annotation.value();
return (name.length() > 0) ? name : field.getName();
}
@Override
public String getColumnName(Field field, Column annotation) {
String name = annotation.value();
return (name.length() > 0) ? name : field.getName();
}
}
| 7,790 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/CsvRecordReader.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import com.netflix.astyanax.shaded.org.apache.cassandra.utils.Pair;
import org.apache.commons.csv.CSVParser;
/**
*
* @author elandau
*
*/
public class CsvRecordReader implements RecordReader {
private CSVParser parser;
private boolean hasHeaderLine = true;
private String[] names = null;
public CsvRecordReader(Reader reader) {
this.parser = new CSVParser(reader);
}
public CsvRecordReader setHasHeaderLine(boolean flag) {
this.hasHeaderLine = flag;
return this;
}
public CsvRecordReader setNames(String... names) {
this.names = names;
return this;
}
@Override
public void start() throws IOException {
// First line contains the column names. First column expected to be the
// row key
if (hasHeaderLine) {
names = parser.getLine();
}
}
@Override
public void shutdown() {
}
@Override
public List<Pair<String, String>> next() throws IOException {
// Iterate rows
String[] row = parser.getLine();
if (null == row)
return null;
List<Pair<String, String>> columns = new ArrayList<Pair<String, String>>();
// Build row mutation for all columns
for (int i = 0; i < row.length; i++) {
if (i >= names.length) {
// Ignore past size of names
break;
}
columns.add(Pair.create(names[i], row[i]));
}
return columns;
}
}
| 7,791 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/ColumnarRecordWriter.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.List;
import com.netflix.astyanax.shaded.org.apache.cassandra.utils.Pair;
import com.netflix.astyanax.ColumnListMutation;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.SerializerPackage;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.serializers.ByteBufferSerializer;
import com.netflix.astyanax.serializers.SerializerPackageImpl;
import com.netflix.astyanax.serializers.UnknownComparatorException;
/**
* Writer rows where the first pair is the key and subsequent pairs are columns.
*
* @author elandau
*
*/
public class ColumnarRecordWriter implements RecordWriter {
private Keyspace keyspace;
private SerializerPackage serializers;
private ColumnFamily<ByteBuffer, ByteBuffer> cf;
private int batchSize = 1;
private MutationBatch mutation;
public ColumnarRecordWriter(Keyspace keyspace, String cfName) {
this.keyspace = keyspace;
this.cf = new ColumnFamily<ByteBuffer, ByteBuffer>(cfName, ByteBufferSerializer.get(),
ByteBufferSerializer.get());
try {
this.serializers = keyspace.getSerializerPackage(cfName, true);
}
catch (ConnectionException e) {
this.serializers = SerializerPackageImpl.DEFAULT_SERIALIZER_PACKAGE;
}
catch (UnknownComparatorException e) {
// We should never get this
}
}
public ColumnarRecordWriter(Keyspace keyspace, String cfName, SerializerPackage serializers) {
this.keyspace = keyspace;
this.serializers = serializers;
this.cf = new ColumnFamily<ByteBuffer, ByteBuffer>(cfName, ByteBufferSerializer.get(),
ByteBufferSerializer.get());
}
public ColumnarRecordWriter setBatchSize(int size) {
this.batchSize = size;
return this;
}
@Override
public void start() throws ConnectionException {
this.mutation = keyspace.prepareMutationBatch();
}
@Override
public void write(List<Pair<String, String>> record) {
if (record.size() <= 1)
return;
// Key is first field
Iterator<Pair<String, String>> iter = record.iterator();
ByteBuffer rowKey = this.serializers.keyAsByteBuffer(iter.next().right);
// Build row mutation for all columns
ColumnListMutation<ByteBuffer> rowMutation = mutation.withRow(cf, rowKey);
while (iter.hasNext()) {
Pair<String, String> pair = iter.next();
try {
rowMutation.putColumn(
this.serializers.columnAsByteBuffer(pair.left),
this.serializers.valueAsByteBuffer(pair.left, pair.right), null);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
// Execute a mutation
if (batchSize == mutation.getRowCount()) {
try {
mutation.execute();
}
catch (ConnectionException e) {
mutation.discardMutations();
throw new RuntimeException(e);
}
}
}
@Override
public void shutdown() {
if (mutation.getRowCount() > 0) {
try {
mutation.execute();
}
catch (ConnectionException e) {
mutation.discardMutations();
}
}
}
}
| 7,792 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/RowsWriter.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import com.netflix.astyanax.model.Rows;
public interface RowsWriter {
public void write(Rows<?, ?> rows) throws Exception;
}
| 7,793 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/ByteBufferRangeImpl.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.nio.ByteBuffer;
import com.netflix.astyanax.model.ByteBufferRange;
public class ByteBufferRangeImpl implements ByteBufferRange {
private final ByteBuffer start;
private final ByteBuffer end;
private final int limit;
private final boolean reversed;
public ByteBufferRangeImpl(ByteBuffer start, ByteBuffer end, int limit, boolean reversed) {
this.start = start;
this.end = end;
this.limit = limit;
this.reversed = reversed;
}
@Override
public ByteBuffer getStart() {
return start;
}
@Override
public ByteBuffer getEnd() {
return end;
}
@Override
public boolean isReversed() {
return reversed;
}
@Override
public int getLimit() {
return limit;
}
}
| 7,794 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/MutationBatchExecutorWithQueue.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException;
import com.netflix.astyanax.impl.AckingQueue;
public class MutationBatchExecutorWithQueue {
private static final Logger LOG = LoggerFactory.getLogger(MutationBatchExecutorWithQueue.class);
private ExecutorService executor;
private Predicate<Exception> retryablePredicate = Predicates.alwaysFalse();
private long waitOnNoHosts = 1000;
private int nThreads;
private long timeout;
private AckingQueue queue;
private AtomicLong successCount = new AtomicLong(0);
private AtomicLong failureCount = new AtomicLong(0);
public MutationBatchExecutorWithQueue(AckingQueue queue, int nThreads) {
this.executor = Executors.newFixedThreadPool(nThreads, new ThreadFactoryBuilder().setDaemon(true).build());
this.queue = queue;
this.nThreads = nThreads;
}
public MutationBatchExecutorWithQueue usingRetryablePredicate(Predicate<Exception> predicate) {
this.retryablePredicate = predicate;
return this;
}
public MutationBatchExecutorWithQueue startConsumers() {
for (int i = 0; i < nThreads; i++) {
executor.submit(new Runnable() {
public void run() {
MutationBatch m = null;
while (true) {
do {
try {
m = queue.getNextMutation(timeout, TimeUnit.MILLISECONDS);
if (m != null) {
m.execute();
successCount.incrementAndGet();
queue.ackMutation(m);
m = null;
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
catch (Exception e) {
LOG.error(e.getMessage(), e);
failureCount.incrementAndGet();
if (e instanceof NoAvailableHostsException) {
try {
Thread.sleep(waitOnNoHosts);
}
catch (InterruptedException e1) {
Thread.currentThread().interrupt();
return;
}
continue;
}
else {
if (!retryablePredicate.apply(e)) {
try {
queue.ackMutation(m);
}
catch (Exception e1) {
// TOOD:
}
}
else {
try {
queue.repushMutation(m);
}
catch (Exception e1) {
// TODO:
}
}
m = null;
}
}
} while (m != null);
}
}
});
}
return this;
}
/**
*/
public void execute(MutationBatch m) throws Exception {
queue.pushMutation(m);
}
public void shutdown() {
executor.shutdown();
}
public long getFailureCount() {
return failureCount.get();
}
public long getSuccessCount() {
return successCount.get();
}
}
| 7,795 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/BlockingAckingQueue.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.impl.AckingQueue;
public class BlockingAckingQueue implements AckingQueue {
private LinkedBlockingQueue<MutationBatch> queue = Queues.newLinkedBlockingQueue();
private ConcurrentMap<MutationBatch, Boolean> busy = Maps.newConcurrentMap();
@Override
public MutationBatch getNextMutation(long timeout, TimeUnit unit) throws InterruptedException {
MutationBatch mutation = queue.poll(timeout, unit);
if (mutation != null) {
busy.put(mutation, true);
}
return mutation;
}
@Override
public void pushMutation(MutationBatch m) throws Exception {
queue.put(m);
}
@Override
public void ackMutation(MutationBatch m) throws Exception {
busy.remove(m);
}
@Override
public void repushMutation(MutationBatch m) throws Exception {
busy.remove(m);
pushMutation(m);
}
@Override
public int size() {
return queue.size();
}
}
| 7,796 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/JsonRowsWriter.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jettison.json.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.netflix.astyanax.ExceptionCallback;
import com.netflix.astyanax.SerializerPackage;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.model.Rows;
public class JsonRowsWriter implements RowsWriter {
public interface ErrorHandler {
boolean onException(Exception e);
}
enum Field {
ROW_KEY, COUNT, NAMES, ROWS, COLUMN, TIMESTAMP, VALUE, TTL
}
private Map<Field, String> fieldNames = Maps.newHashMap();
private static final String TIME_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private final PrintWriter out;
private final SerializerPackage serializers;
private String extra = null;
private boolean rowsAsArray = true;
private boolean ignoreExceptions = true;
private boolean ignoreUndefinedColumns = false;
private Set<String> dynamicNames;
private Set<String> fixedNames;
private List<String> fixedNamesList;
private Set<String> ignoreNames = Sets.newHashSet();
private Set<String> metadataNames;
private boolean columnsAsRows = false;
private int rowCount = 0;
private int columnCount = 0;
private int maxStringLength = 256;
private String rowColumnDelimiter = "$";
public JsonRowsWriter(PrintWriter out, SerializerPackage serializers) throws ConnectionException {
this.out = out;
this.serializers = serializers;
fieldNames.put(Field.NAMES, "names");
fieldNames.put(Field.ROWS, "rows");
fieldNames.put(Field.COUNT, "count");
fieldNames.put(Field.ROW_KEY, "_key");
fieldNames.put(Field.COLUMN, "column");
fieldNames.put(Field.TIMESTAMP, "timestamp");
fieldNames.put(Field.VALUE, "value");
fieldNames.put(Field.TTL, "ttl");
}
public JsonRowsWriter setRowsName(String fieldName) {
fieldNames.put(Field.ROWS, fieldName);
return this;
}
public JsonRowsWriter setNamesName(String fieldName) {
fieldNames.put(Field.NAMES, fieldName);
return this;
}
public JsonRowsWriter setCountName(String fieldName) {
fieldNames.put(Field.COUNT, fieldName);
return this;
}
public JsonRowsWriter setRowKeyName(String fieldName) {
fieldNames.put(Field.ROW_KEY, fieldName);
return this;
}
public JsonRowsWriter setExtra(String extra) {
this.extra = extra;
return this;
}
public JsonRowsWriter setRowsAsArray(boolean flag) {
this.rowsAsArray = flag;
return this;
}
public JsonRowsWriter setIgnoreUndefinedColumns(boolean flag) {
this.ignoreUndefinedColumns = flag;
return this;
}
@Deprecated
public JsonRowsWriter setErrorValueText(String text) {
return this;
}
public JsonRowsWriter setDynamicColumnNames(boolean flag) {
if (flag) {
dynamicNames = Sets.newLinkedHashSet();
}
else {
dynamicNames = null;
}
return this;
}
public JsonRowsWriter setFixedColumnNames(String... columns) {
this.fixedNames = Sets.newLinkedHashSet(Arrays.asList(columns));
this.fixedNamesList = Arrays.asList(columns);
return this;
}
public JsonRowsWriter setIgnoreColumnNames(String... columns) {
this.ignoreNames = Sets.newHashSet(Arrays.asList(columns));
return this;
}
@Deprecated
public JsonRowsWriter setExceptionCallback(ExceptionCallback exceptionCallback) {
return this;
}
public JsonRowsWriter setColumnsAsRows(boolean columnsAsRows) {
this.columnsAsRows = columnsAsRows;
setFixedColumnNames("column", "value", "timestamp", "ttl");
return this;
}
public JsonRowsWriter addExtra(String name, String value) {
if (extra == null) {
extra = new String();
}
if (!extra.isEmpty()) {
extra += ",";
}
extra += jsonifyString(name) + ":" + jsonifyString(value);
return this;
}
public JsonRowsWriter setMaxLength(int maxStringLength) {
this.maxStringLength = maxStringLength;
return this;
}
int getColumnCount() {
return this.columnCount;
}
int getRowCount() {
return this.rowCount;
}
@Override
public void write(Rows<?, ?> rows) throws Exception {
this.rowCount = 0;
this.columnCount = 0;
out.println("{");
if (this.fixedNamesList != null) {
writeColumnNames(this.fixedNamesList);
}
else if (this.dynamicNames == null) {
metadataNames = this.getColumnNamesFromMetadata();
List<String> names = Lists.newArrayList(metadataNames);
Collections.sort(names);
writeColumnNames(names);
}
out.append(jsonifyString(this.fieldNames.get(Field.ROWS))).append(":");
int count = 0;
if (columnsAsRows) {
addExtra("columnsAsRows", "true");
if (rowsAsArray) {
out.append("[");
}
boolean firstRow = true;
for (Row<?, ?> row : rows) {
if (row.getColumns().isEmpty())
continue;
rowCount++;
String idString = serializers.keyAsString(row.getRawKey());
count += writeColumnsAsRows(idString, row.getColumns(), firstRow);
firstRow = false;
}
if (rowsAsArray) {
out.append("]");
}
out.println();
}
else {
if (rowsAsArray) {
out.append("[").println();
boolean firstRow = true;
for (Row<?, ?> row : rows) {
if (row.getColumns().isEmpty())
continue;
rowCount++;
if (!firstRow) {
out.println(",");
}
else {
firstRow = false;
}
out.append("{");
try {
String idString = serializers.keyAsString(row.getRawKey());
out.append(jsonifyString(this.fieldNames.get(Field.ROW_KEY))).append(":")
.append(jsonifyString(idString));
writeColumns(row.getColumns(), false);
count++;
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
out.print("}");
}
out.println();
out.append("]");
}
else {
out.append("{").println();
boolean firstRow = true;
for (Row<?, ?> row : rows) {
if (row.getColumns().isEmpty())
continue;
rowCount++;
if (!firstRow) {
out.println(",");
}
else {
firstRow = false;
}
try {
String idString = serializers.keyAsString(row.getRawKey());
out.append(jsonifyString(idString)).append(":{");
// out.append(jsonifyString(this.fieldNames.get(Field.ROW_KEY))).append(":").append(jsonifyString(idString));
writeColumns(row.getColumns(), true);
out.print("}");
count++;
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
}
out.println();
out.append("}");
}
}
out.println(",");
if (this.dynamicNames != null) {
List<String> names = Lists.newArrayList(this.dynamicNames);
Collections.sort(names);
writeColumnNames(names);
}
if (extra != null) {
out.append(extra).println(",");
}
out.append(jsonifyString(this.fieldNames.get(Field.COUNT))).append(":").append(Integer.toString(count))
.println();
out.println("}");
}
private int writeColumnsAsRows(String rowKey, ColumnList<?> columns, boolean first) throws Exception {
for (Column<?> column : columns) {
try {
String columnString;
try {
columnString = serializers.columnAsString(column.getRawName());
}
catch (Exception e) {
e.printStackTrace();
if (!ignoreExceptions) {
throw e;
}
columnString = e.getMessage(); // this.errorValueText;
}
String valueString = null;
try {
valueString = serializers.valueAsString(column.getRawName(), column.getByteBufferValue());
}
catch (Exception e) {
e.printStackTrace();
if (!ignoreExceptions) {
throw e;
}
valueString = e.getMessage(); // this.errorValueText;
}
if (!first) {
out.println(",");
}
else {
first = false;
}
out.append("{");
if (rowsAsArray) {
out.append(jsonifyString(this.fieldNames.get(Field.ROW_KEY))).append(":")
.append(jsonifyString(rowKey));
}
else {
out.append(jsonifyString(rowKey + rowColumnDelimiter + columnString)).append(":{");
}
out.print(",");
String timestampString;
try {
timestampString = new SimpleDateFormat(TIME_FORMAT_STRING).format(new Date(
column.getTimestamp() / 1000));
}
catch (Exception e) {
timestampString = "none";
}
int ttl;
try {
ttl = column.getTtl();
}
catch (Exception e) {
ttl = 0;
}
columnCount++;
out.append(jsonifyString(this.fieldNames.get(Field.COLUMN))).append(":")
.append(jsonifyString(columnString)).append(",")
.append(jsonifyString(this.fieldNames.get(Field.VALUE))).append(":")
.append(jsonifyString(valueString)).append(",")
.append(jsonifyString(this.fieldNames.get(Field.TIMESTAMP))).append(":")
.append(jsonifyString(timestampString)).append(",")
.append(jsonifyString(this.fieldNames.get(Field.TTL))).append(":")
.append(jsonifyString(Integer.toString(ttl))).append("}")
;
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
}
return columns.size();
}
private void writeColumns(ColumnList<?> columns, boolean first) throws Exception {
for (Column<?> column : columns) {
try {
String columnString;
try {
columnString = serializers.columnAsString(column.getRawName());
}
catch (Exception e) {
e.printStackTrace();
if (!ignoreExceptions) {
throw e;
}
columnString = e.getMessage(); // this.errorValueText;
}
if (this.ignoreNames.contains(columnString)) {
continue;
}
if (this.ignoreUndefinedColumns) {
if (this.fixedNames != null && !this.fixedNames.contains(columnString))
continue;
if (this.metadataNames != null && !this.metadataNames.contains(columnString))
continue;
}
if (this.dynamicNames != null)
this.dynamicNames.add(columnString);
String valueString = null;
try {
valueString = serializers.valueAsString(column.getRawName(), column.getByteBufferValue());
}
catch (Exception e) {
e.printStackTrace();
if (!ignoreExceptions) {
throw e;
}
valueString = e.getMessage(); // this.errorValueText;
}
if (!first)
out.append(",");
else
first = false;
out.append(jsonifyString(columnString)).append(":").append(jsonifyString(valueString));
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
}
}
private Set<String> getColumnNamesFromMetadata() throws Exception {
Set<String> set = Sets.newLinkedHashSet();
try {
for (ByteBuffer name : this.serializers.getColumnNames()) {
try {
String columnName = this.serializers.columnAsString(name);
set.add(columnName);
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
}
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
return set;
}
private void writeColumnNames(List<String> names) throws Exception {
try {
out.append(jsonifyString(this.fieldNames.get(Field.NAMES))).append(":[");
boolean first = true;
if (this.rowsAsArray) {
out.append(jsonifyString(this.fieldNames.get(Field.ROW_KEY)));
first = false;
}
for (String name : names) {
if (this.ignoreNames.contains(name)) {
continue;
}
try {
if (!first)
out.append(",");
else
first = false;
out.append(jsonifyString(name));
}
catch (Exception e) {
}
}
out.println("],");
}
catch (Exception e) {
if (!ignoreExceptions) {
throw e;
}
}
}
private String jsonifyString(String str) {
if (str == null) {
str = "null";
}
if (str.length() > maxStringLength) {
return JSONObject.quote(str.substring(0, maxStringLength) + "...");
}
else {
return JSONObject.quote(str);
}
}
}
| 7,797 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/RecordReader.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.io.IOException;
import java.util.List;
import com.netflix.astyanax.shaded.org.apache.cassandra.utils.Pair;
/**
*
* @author elandau
*
*/
public interface RecordReader {
List<Pair<String, String>> next() throws IOException;
void shutdown();
void start() throws IOException;
}
| 7,798 |
0 | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax | Create_ds/astyanax/astyanax-cassandra/src/main/java/com/netflix/astyanax/util/RecordWriter.java | /*******************************************************************************
* Copyright 2011 Netflix
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.netflix.astyanax.util;
import java.util.List;
import com.netflix.astyanax.shaded.org.apache.cassandra.utils.Pair;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
/**
*
* @author elandau
*
*/
public interface RecordWriter {
void start() throws ConnectionException;
void write(List<Pair<String, String>> record);
void shutdown();
}
| 7,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.