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/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/meta/PaasUtils.java
/* * Copyright (C) 2012 DataStax 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.paas.dao.meta; import java.math.*; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.*; /** * A number of static fields/methods handy for tests. */ public abstract class PaasUtils { private static final Logger logger = LoggerFactory.getLogger(PaasUtils.class); public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }"; public static final String CREATE_KEYSPACE_GENERIC_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : '%s', %s }"; public static final String SIMPLE_KEYSPACE = "ks"; public static final String SIMPLE_TABLE = "test"; public static final String CREATE_TABLE_SIMPLE_FORMAT = "CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)"; public static final String INSERT_FORMAT = "INSERT INTO %s (key, column1, value) VALUES ('%s', '%s', '%s')"; public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s"; public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) { switch (type.getName()) { case ASCII: bs.setString(name, (String)value); break; case BIGINT: bs.setLong(name, (Long)value); break; case BLOB: bs.setBytes(name, (ByteBuffer)value); break; case BOOLEAN: bs.setBool(name, (Boolean)value); break; case COUNTER: // Just a no-op, we shouldn't handle counters the same way than other types break; case DECIMAL: bs.setDecimal(name, (BigDecimal)value); break; case DOUBLE: bs.setDouble(name, (Double)value); break; case FLOAT: bs.setFloat(name, (Float)value); break; case INET: bs.setInet(name, (InetAddress)value); break; case INT: bs.setInt(name, (Integer)value); break; case TEXT: bs.setString(name, (String)value); break; case TIMESTAMP: bs.setDate(name, (Date)value); break; case UUID: bs.setUUID(name, (UUID)value); break; case VARCHAR: bs.setString(name, (String)value); break; case VARINT: bs.setVarint(name, (BigInteger)value); break; case TIMEUUID: bs.setUUID(name, (UUID)value); break; case LIST: bs.setList(name, (List)value); break; case SET: bs.setSet(name, (Set)value); break; case MAP: bs.setMap(name, (Map)value); break; default: throw new RuntimeException("Missing handling of " + type); } return bs; } public static Object getValue(Row row, String name, DataType type) { switch (type.getName()) { case ASCII: return row.getString(name); case BIGINT: return row.getLong(name); case BLOB: return row.getBytes(name); case BOOLEAN: return row.getBool(name); case COUNTER: return row.getLong(name); case DECIMAL: return row.getDecimal(name); case DOUBLE: return row.getDouble(name); case FLOAT: return row.getFloat(name); case INET: return row.getInet(name); case INT: return row.getInt(name); case TEXT: return row.getString(name); case TIMESTAMP: return row.getDate(name); case UUID: return row.getUUID(name); case VARCHAR: return row.getString(name); case VARINT: return row.getVarint(name); case TIMEUUID: return row.getUUID(name); case LIST: return row.getList(name, classOf(type.getTypeArguments().get(0))); case SET: return row.getSet(name, classOf(type.getTypeArguments().get(0))); case MAP: return row.getMap(name, classOf(type.getTypeArguments().get(0)), classOf(type.getTypeArguments().get(1))); } throw new RuntimeException("Missing handling of " + type); } private static Class classOf(DataType type) { assert !type.isCollection(); switch (type.getName()) { case ASCII: case TEXT: case VARCHAR: return String.class; case BIGINT: case COUNTER: return Long.class; case BLOB: return ByteBuffer.class; case BOOLEAN: return Boolean.class; case DECIMAL: return BigDecimal.class; case DOUBLE: return Double.class; case FLOAT: return Float.class; case INET: return InetAddress.class; case INT: return Integer.class; case TIMESTAMP: return Date.class; case UUID: case TIMEUUID: return UUID.class; case VARINT: return BigInteger.class; } throw new RuntimeException("Missing handling of " + type); } // Always return the "same" value for each type public static Object getFixedValue(final DataType type) { try { switch (type.getName()) { case ASCII: return "An ascii string"; case BIGINT: return 42L; case BLOB: return ByteBuffer.wrap(new byte[]{ (byte)4, (byte)12, (byte)1 }); case BOOLEAN: return true; case COUNTER: throw new UnsupportedOperationException("Cannot 'getSomeValue' for counters"); case DECIMAL: return new BigDecimal("3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"); case DOUBLE: return 3.142519; case FLOAT: return 3.142519f; case INET: return InetAddress.getByAddress(new byte[]{(byte)127, (byte)0, (byte)0, (byte)1}); case INT: return 24; case TEXT: return "A text string"; case TIMESTAMP: return new Date(1352288289L); case UUID: return UUID.fromString("087E9967-CCDC-4A9B-9036-05930140A41B"); case VARCHAR: return "A varchar string"; case VARINT: return new BigInteger("123456789012345678901234567890"); case TIMEUUID: return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"); case LIST: return new ArrayList(){{ add(getFixedValue(type.getTypeArguments().get(0))); }}; case SET: return new HashSet(){{ add(getFixedValue(type.getTypeArguments().get(0))); }}; case MAP: return new HashMap(){{ put(getFixedValue(type.getTypeArguments().get(0)), getFixedValue(type.getTypeArguments().get(1))); }}; } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Missing handling of " + type); } // Always return the "same" value for each type public static Object getFixedValue2(final DataType type) { try { switch (type.getName()) { case ASCII: return "A different ascii string"; case BIGINT: return Long.MAX_VALUE; case BLOB: ByteBuffer bb = ByteBuffer.allocate(64); bb.putInt(0xCAFE); bb.putShort((short) 3); bb.putShort((short) 45); return bb; case BOOLEAN: return false; case COUNTER: throw new UnsupportedOperationException("Cannot 'getSomeValue' for counters"); case DECIMAL: return new BigDecimal("12.3E+7"); case DOUBLE: return Double.POSITIVE_INFINITY; case FLOAT: return Float.POSITIVE_INFINITY; case INET: return InetAddress.getByName("123.123.123.123"); case INT: return Integer.MAX_VALUE; case TEXT: return "r??sum??"; case TIMESTAMP: return new Date(872835240000L); case UUID: return UUID.fromString("067e6162-3b6f-4ae2-a171-2470b63dff00"); case VARCHAR: return "A different varchar r??sum??"; case VARINT: return new BigInteger(Integer.toString(Integer.MAX_VALUE) + "000"); case TIMEUUID: return UUID.fromString("FE2B4360-28C6-11E2-81C1-0800200C9A66"); case LIST: return new ArrayList(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }}; case SET: return new HashSet(){{ add(getFixedValue2(type.getTypeArguments().get(0))); }}; case MAP: return new HashMap(){{ put(getFixedValue2(type.getTypeArguments().get(0)), getFixedValue2(type.getTypeArguments().get(1))); }}; } } catch (Exception e) { throw new RuntimeException(e); } throw new RuntimeException("Missing handling of " + type); } // Wait for a node to be up and running // This is used because there is some delay between when a node has been // added through ccm and when it's actually available for querying public static void waitFor(String node, Cluster cluster) { waitFor(node, cluster, 20, false, false); } public static void waitFor(String node, Cluster cluster, int maxTry) { waitFor(node, cluster, maxTry, false, false); } public static void waitForDown(String node, Cluster cluster) { waitFor(node, cluster, 20, true, false); } public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) { waitFor(node, cluster, 20, true, false); // FIXME: Once stop() works, remove this line try { Thread.sleep(waitTime * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void waitForDown(String node, Cluster cluster, int maxTry) { waitFor(node, cluster, maxTry, true, false); } public static void waitForDecommission(String node, Cluster cluster) { waitFor(node, cluster, 20, true, true); } public static void waitForDecommission(String node, Cluster cluster, int maxTry) { waitFor(node, cluster, maxTry, true, true); } private static void waitFor(String node, Cluster cluster, int maxTry, boolean waitForDead, boolean waitForOut) { if (waitForDead || waitForOut) if (waitForDead) logger.info("Waiting for stopped node: " + node); else if (waitForOut) logger.info("Waiting for decommissioned node: " + node); else logger.info("Waiting for upcoming node: " + node); // In the case where the we've killed the last node in the cluster, if we haven't // tried doing an actual query, the driver won't realize that last node is dead until // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force // the detection by forcing a request. // if (waitForDead || waitForOut) // cluster.manager.submitSchemaRefresh(null, null); InetAddress address; try { address = InetAddress.getByName(node); } catch (Exception e) { // That's a problem but that's not *our* problem return; } Metadata metadata = cluster.getMetadata(); for (int i = 0; i < maxTry; ++i) { for (Host host : metadata.getAllHosts()) { if (host.getAddress().equals(address) && testHost(host, waitForDead)) return; } try { Thread.sleep(1000); } catch (Exception e) {} } for (Host host : metadata.getAllHosts()) { if (host.getAddress().equals(address)) { if (testHost(host, waitForDead)) { return; } else { // logging it because this give use the timestamp of when this happens logger.info(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + "s"); throw new IllegalStateException(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + "s"); } } } if (waitForOut){ return; } else { logger.info(node + " is not part of the cluster after " + maxTry + "s"); throw new IllegalStateException(node + " is not part of the cluster after " + maxTry + "s"); } } private static boolean testHost(Host host, boolean testForDown) { return testForDown ? !host.getMonitor().isUp() : host.getMonitor().isUp(); } }
500
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/AstyanaxDaoSchemaProvider.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.paas.dao.astyanax; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Map; import java.util.Properties; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.connectionpool.exceptions.BadRequestException; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.paas.cassandra.provider.KeyspaceClientProvider; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoSchemaProvider; import com.netflix.paas.dao.DaoSchema; import com.netflix.paas.exceptions.NotFoundException; /** * Astyanax based Dao factory for persisting PAAS state * * @author elandau * */ public class AstyanaxDaoSchemaProvider implements DaoSchemaProvider { private final Logger LOG = LoggerFactory.getLogger(AstyanaxDaoSchemaProvider.class); private final static String CONFIG_PREFIX_FORMAT = "com.netflix.paas.schema.%s"; private final KeyspaceClientProvider keyspaceProvider; private final Map<String, DaoSchema> schemas = Maps.newHashMap(); private final AbstractConfiguration configuration; public class AstyanaxDaoSchema implements DaoSchema { private final IdentityHashMap<Class<?>, Dao<?>> daos = Maps.newIdentityHashMap(); private final Keyspace keyspace; private final String schemaName; public AstyanaxDaoSchema(String schemaName, Keyspace keyspace) { this.keyspace = keyspace; this.schemaName = schemaName; Configuration config = configuration.subset(String.format(CONFIG_PREFIX_FORMAT, schemaName.toLowerCase())); if (config.getBoolean("autocreate", false)) { try { createSchema(); } catch (Exception e) { LOG.error("Error creating column keyspace", e); } } } @Override public synchronized void createSchema() { final Properties props = ConfigurationConverter.getProperties(configuration.subset(String.format(CONFIG_PREFIX_FORMAT, schemaName.toLowerCase()))); try { props.setProperty("name", props.getProperty("keyspace")); LOG.info("Creating schema: " + schemaName + " " + props); this.keyspace.createKeyspace(props); } catch (ConnectionException e) { LOG.error("Failed to create schema '{}' with properties '{}'", new Object[]{schemaName, props.toString(), e}); throw new RuntimeException("Failed to create keyspace " + keyspace.getKeyspaceName(), e); } } @Override public synchronized void dropSchema() { try { this.keyspace.dropKeyspace(); } catch (ConnectionException e) { throw new RuntimeException("Failed to drop keyspace " + keyspace.getKeyspaceName(), e); } } @Override public synchronized Collection<Dao<?>> listDaos() { return Lists.newArrayList(daos.values()); } @Override public boolean isExists() { try { this.keyspace.describeKeyspace(); return true; } catch (BadRequestException e) { return false; } catch (Exception e) { throw new RuntimeException("Failed to determine if keyspace " + keyspace.getKeyspaceName() + " exists", e); } } @Override public synchronized <T> Dao<T> getDao(Class<T> type) { Dao<?> dao = daos.get(type); if (dao == null) { dao = new AstyanaxDao<T>(keyspace, type); daos.put(type, dao); } return (Dao<T>) dao; } } @Inject public AstyanaxDaoSchemaProvider(KeyspaceClientProvider keyspaceProvider, AbstractConfiguration configuration) { this.keyspaceProvider = keyspaceProvider; this.configuration = configuration; } @PostConstruct public void start() { } @PreDestroy public void stop() { } @Override public synchronized Collection<DaoSchema> listSchemas() { return Lists.newArrayList(schemas.values()); } @Override public synchronized DaoSchema getSchema(String schemaName) throws NotFoundException { AstyanaxDaoSchema schema = (AstyanaxDaoSchema)schemas.get(schemaName); if (schema == null) { LOG.info("Creating schema '{}'", new Object[]{schemaName}); Keyspace keyspace = keyspaceProvider.acquireKeyspace(schemaName); schema = new AstyanaxDaoSchema(schemaName, keyspace); schemas.put(schemaName, schema); } return schema; } }
501
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/Indexer.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.paas.dao.astyanax; import java.util.Collection; import java.util.Map; /** * Very very very simple indexing API. * * @author elandau * */ public interface Indexer { /** * Add the id to the tags * @param id * @param tags */ public void tagId(String id, Map<String, String> tags) throws IndexerException ; /** * Remove id from all it's tags * @param id */ public void removeId(String id) throws IndexerException ; /** * Get all tags for a document * @param id * @return */ public Map<String, String> getTags(String id) throws IndexerException; /** * Find all ids that have one or more of these tags * @param tags * @return */ public Collection<String> findUnion(Map<String, String> tags) throws IndexerException ; /** * Find all ids that have all of the tags * @param tags * @return */ public Collection<String> findIntersection(Map<String, String> tags) throws IndexerException ; /** * Find all ids that match the tag * @param tag * @return */ public Collection<String> find(String name, String value) throws IndexerException ; /** * Create the underlying storage */ public void createStorage() throws IndexerException ; }
502
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/AstyanaxDao.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.paas.dao.astyanax; import java.util.Collection; import java.util.List; import javax.persistence.PersistenceException; import org.apache.commons.lang.StringUtils; import com.google.common.base.CaseFormat; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.entitystore.DefaultEntityManager; import com.netflix.astyanax.entitystore.EntityManager; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.recipes.reader.AllRowsReader; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.paas.dao.Dao; /** * Simple implementation of a Dao on top of the astyanax EntityManager API * @author elandau * * @param <T> */ public class AstyanaxDao<T> implements Dao<T> { private final static String DAO_NAME = "astyanax"; private final EntityManager<T, String> manager; private final Keyspace keyspace; private final ColumnFamily<String, String> columnFamily; private final String entityName; private final String prefix; private static String entityNameFromClass(Class<?> entityType) { return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, StringUtils.removeEnd(StringUtils.substringAfterLast(entityType.getName(), "."), "Entity")); } public AstyanaxDao(Keyspace keyspace, Class<T> entityType) { this.keyspace = keyspace; this.entityName = entityNameFromClass(entityType); this.columnFamily = new ColumnFamily<String, String>(this.entityName, StringSerializer.get(), StringSerializer.get()); this.prefix = ""; manager = new DefaultEntityManager.Builder<T, String>() .withKeyspace(keyspace) .withColumnFamily(columnFamily) .withEntityType(entityType) .build(); } public AstyanaxDao(Keyspace keyspace, Class<T> entityType, String columnFamilyName) { this.keyspace = keyspace; this.entityName = entityNameFromClass(entityType); this.columnFamily = new ColumnFamily<String, String>(columnFamilyName, StringSerializer.get(), StringSerializer.get()); this.prefix = this.entityName + ":"; manager = new DefaultEntityManager.Builder<T, String>() .withKeyspace(keyspace) .withColumnFamily(columnFamily) .withEntityType(entityType) .build(); } @Override public T read(String id) throws PersistenceException { return this.manager.get(id); } @Override public void write(T entity) throws PersistenceException { this.manager.put(entity); } @Override public Collection<T> list() throws PersistenceException{ return this.manager.getAll(); } @Override public void delete(String id) throws PersistenceException{ this.manager.delete(id); } @Override public void createTable() throws PersistenceException { try { keyspace.createColumnFamily(columnFamily, null); } catch (ConnectionException e) { throw new PersistenceException("Failed to create column family : " + columnFamily.getName(), e); } } @Override public void deleteTable() throws PersistenceException{ try { keyspace.dropColumnFamily(columnFamily); } catch (ConnectionException e) { throw new PersistenceException("Failed to drop column family : " + columnFamily.getName(), e); } } @Override public String getEntityType() { return this.entityName; } @Override public String getDaoType() { return DAO_NAME; } @Override public Boolean healthcheck() { return isExists(); } @Override public Boolean isExists() { try { return keyspace.describeKeyspace().getColumnFamily(columnFamily.getName()) != null; } catch (Throwable t) { return false; } } @Override public void shutdown() { } @Override public Collection<String> listIds() throws PersistenceException { final List<String> ids = Lists.newArrayList(); try { new AllRowsReader.Builder<String, String>(keyspace, columnFamily) .withIncludeEmptyRows(false) .forEachRow(new Function<Row<String,String>, Boolean>() { @Override public Boolean apply(Row<String, String> row) { ids.add(row.getKey()); return true; } }) .build() .call(); } catch (Exception e) { throw new PersistenceException("Error trying to fetch row ids", e); } return ids; } @Override public Collection<T> read(Collection<String> keys) throws PersistenceException { return this.manager.get(keys); } }
503
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/IndexerException.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.paas.dao.astyanax; public class IndexerException extends Exception { public IndexerException(String message, Exception e) { super(message, e); } public IndexerException(String message) { super(message); } }
504
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/DaoKeys.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.paas.dao.astyanax; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.cassandra.entity.ColumnFamilyEntity; import com.netflix.paas.cassandra.entity.KeyspaceEntity; import com.netflix.paas.dao.DaoKey; import com.netflix.paas.entity.ClusterEntity; public class DaoKeys { public final static DaoKey<KeyspaceEntity> DAO_KEYSPACE_ENTITY = new DaoKey<KeyspaceEntity> (SchemaNames.CONFIGURATION.name(), KeyspaceEntity.class); public final static DaoKey<CassandraClusterEntity> DAO_CASSANDRA_CLUSTER_ENTITY = new DaoKey<CassandraClusterEntity>(SchemaNames.CONFIGURATION.name(), CassandraClusterEntity.class); public final static DaoKey<ColumnFamilyEntity> DAO_COLUMN_FAMILY_ENTITY = new DaoKey<ColumnFamilyEntity> (SchemaNames.CONFIGURATION.name(), ColumnFamilyEntity.class); }
505
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/MetaDaoImpl.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.paas.dao.astyanax; import com.google.inject.Inject; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.paas.json.JsonObject; import com.netflix.paas.meta.dao.MetaDao; import com.netflix.paas.meta.entity.Entity; import com.netflix.paas.meta.entity.PaasTableEntity; import com.netflix.paas.cassandra.provider.KeyspaceClientProvider; public class MetaDaoImpl implements MetaDao{ KeyspaceClientProvider kscp; public static ColumnFamily<String, String> dbcf = ColumnFamily .newColumnFamily( "db", StringSerializer.get(), StringSerializer.get()); @Inject public MetaDaoImpl(KeyspaceClientProvider kscp) { this.kscp = kscp; } @Override public void writeMetaEntity(Entity entity) { // TODO Auto-generated method stub Keyspace ks = kscp.acquireKeyspace("meta"); ks.prepareMutationBatch(); MutationBatch m; OperationResult<Void> result; m = ks.prepareMutationBatch(); m.withRow(dbcf, entity.getRowKey()).putColumn(entity.getName(), entity.getPayLoad(), null); try { result = m.execute(); if (entity instanceof PaasTableEntity) { String schemaName = ((PaasTableEntity)entity).getSchemaName(); Keyspace schemaks = kscp.acquireKeyspace(schemaName); ColumnFamily<String, String> cf = ColumnFamily.newColumnFamily(entity.getName(), StringSerializer.get(), StringSerializer.get()); schemaks.createColumnFamily(cf, null); } int i = 0; } catch (ConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public Entity readMetaEntity(String rowKey) { // TODO Auto-generated method stub return null; } @Override public void writeRow(String db, String table, JsonObject rowObj) { // TODO Auto-generated method stub } @Override public String listRow(String db, String table, String keycol, String key) { // TODO Auto-generated method stub return null; } }
506
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/SimpleReverseIndexer.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.paas.dao.astyanax; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.annotations.Component; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.serializers.AnnotatedCompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.astyanax.util.TimeUUIDUtils; /** * Very very very simple and inefficient tagger that stores a single row per tag. * Use this when storing and tagging a relatively small number of 'documents'. * The tagger works on equality and does not provide prefix or wildcard searches * * RowKey: <TagName> * Column: <ForeignKey><VersionUUID> * * @author elandau * */ public class SimpleReverseIndexer implements Indexer { private final static String ID_PREFIX = "$"; /** * Composite entry within the index CF * @author elandau * */ public static class IndexEntry { public IndexEntry() { } public IndexEntry(String id, UUID uuid) { this.id = id; this.version = uuid; } @Component(ordinal = 0) public String id; @Component(ordinal = 1) public UUID version; } private static final AnnotatedCompositeSerializer<IndexEntry> EntrySerializer = new AnnotatedCompositeSerializer<IndexEntry>(IndexEntry.class); /** * Builder pattern * @author elandau */ public static class Builder { private Keyspace keyspace; private String columnFamily; public Builder withKeyspace(Keyspace keyspace) { this.keyspace = keyspace; return this; } public Builder withColumnFamily(String columnFamily) { this.columnFamily = columnFamily; return this; } public SimpleReverseIndexer build() { return new SimpleReverseIndexer(this); } } public static Builder builder() { return new Builder(); } private Keyspace keyspace; private ColumnFamily<String, IndexEntry> indexCf; private ColumnFamily<String, String> dataCf; private SimpleReverseIndexer(Builder builder) { indexCf = new ColumnFamily<String, IndexEntry>(builder.columnFamily + "_idx", StringSerializer.get(), EntrySerializer); dataCf = new ColumnFamily<String, String> (builder.columnFamily + "_data", StringSerializer.get(), StringSerializer.get()); keyspace = builder.keyspace; } @Override public Collection<String> findUnion(Map<String, String> tags) throws IndexerException { Set<String> ids = Sets.newHashSet(); MutationBatch mb = keyspace.prepareMutationBatch(); try { for (Row<String, IndexEntry> row : keyspace.prepareQuery(indexCf).getKeySlice(fieldsToSet(tags)).execute().getResult()) { ColumnListMutation<IndexEntry> mrow = null; IndexEntry previousEntry = null; for (Column<IndexEntry> column : row.getColumns()) { IndexEntry entry = column.getName(); if (previousEntry != null && entry.id == previousEntry.id) { if (mrow == null) mrow = mb.withRow(indexCf, row.getKey()); mrow.deleteColumn(previousEntry); } ids.add(entry.id); } } } catch (ConnectionException e) { throw new IndexerException("Failed to get tags : " + tags, e); } finally { try { mb.execute(); } catch (Exception e) { // OK to ignore } } return ids; } private Collection<String> fieldsToSet(Map<String, String> tags) { return Collections2.transform(tags.entrySet(), new Function<Entry<String, String>, String>() { public String apply(Entry<String, String> entry) { return entry.getKey() + "=" + entry.getValue(); } }); } @Override public Collection<String> findIntersection(Map<String, String> tags) throws IndexerException { Set<String> ids = Sets.newHashSet(); MutationBatch mb = keyspace.prepareMutationBatch(); try { boolean first = true; Set<Entry<String, String>> elements = tags.entrySet(); for (Row<String, IndexEntry> row : keyspace.prepareQuery(indexCf).getKeySlice(fieldsToSet(tags)).execute().getResult()) { Set<String> rowIds = Sets.newHashSet(); ColumnListMutation<IndexEntry> mrow = null; IndexEntry previousEntry = null; for (Column<IndexEntry> column : row.getColumns()) { IndexEntry entry = column.getName(); if (previousEntry != null && entry.id == previousEntry.id) { if (mrow == null) mrow = mb.withRow(indexCf, row.getKey()); mrow.deleteColumn(previousEntry); } rowIds.add(entry.id); } if (first) { first = false; ids = rowIds; } else { ids = Sets.intersection(ids, rowIds); if (ids.isEmpty()) return ids; } } } catch (ConnectionException e) { throw new IndexerException("Failed to get tags : " + tags, e); } finally { try { mb.execute(); } catch (ConnectionException e) { // OK to ignore } } return ids; } @Override public Collection<String> find(String field, String value) throws IndexerException { Set<String> ids = Sets.newHashSet(); String indexRowKey = field + "=" + value; MutationBatch mb = keyspace.prepareMutationBatch(); try { boolean first = true; ColumnList<IndexEntry> row = keyspace.prepareQuery(indexCf).getRow(indexRowKey).execute().getResult(); IndexEntry previousEntry = null; for (Column<IndexEntry> column : row) { IndexEntry entry = column.getName(); ColumnListMutation<IndexEntry> mrow = null; if (previousEntry != null && entry.id == previousEntry.id) { if (mrow == null) mrow = mb.withRow(indexCf, indexRowKey); mrow.deleteColumn(previousEntry); } else { ids.add(entry.id); } } } catch (ConnectionException e) { throw new IndexerException("Failed to get tag : " + indexRowKey, e); } finally { try { mb.execute(); } catch (ConnectionException e) { // OK to ignore } } return ids; } @Override public void tagId(String id, Map<String, String> tags) throws IndexerException { MutationBatch mb = keyspace.prepareMutationBatch(); ColumnListMutation<String> idRow = mb.withRow(dataCf, id); UUID uuid = TimeUUIDUtils.getUniqueTimeUUIDinMicros(); for (Map.Entry<String, String> tag : tags.entrySet()) { String rowkey = tag.getKey() + "=" + tag.getValue(); System.out.println("Rowkey: " + rowkey); mb.withRow(indexCf, tag.getKey() + "=" + tag.getValue()) .putEmptyColumn(new IndexEntry(id, uuid)); // idRow.putColumn(tag.getKey(), tag.getValue()); } try { mb.execute(); } catch (ConnectionException e) { throw new IndexerException("Failed to store tags : " + tags + " for id " + id, e); } } @Override public void removeId(String id) throws IndexerException { // TODO Auto-generated method stub } @Override public void createStorage() throws IndexerException { try { keyspace.createColumnFamily(indexCf, ImmutableMap.<String, Object>builder() .put("comparator_type", "CompositeType(UTF8Type, TimeUUIDType)") .build()); } catch (ConnectionException e) { e.printStackTrace(); } try { keyspace.createColumnFamily(dataCf, ImmutableMap.<String, Object>builder() .put("default_validation_class", "LongType") .put("key_validation_class", "UTF8Type") .put("comparator_type", "UTF8Type") .build()); } catch (ConnectionException e) { e.printStackTrace(); } } @Override public Map<String, String> getTags(String id) throws IndexerException { try { ColumnList<String> fields = keyspace.prepareQuery(dataCf).getRow(id).execute().getResult(); Map<String, String> mapped = Maps.newHashMap(); for (Column<String> column : fields) { mapped.put(column.getName(), column.getStringValue()); } return mapped; } catch (ConnectionException e) { throw new IndexerException("Failed to get tags for id " + id, e); } } }
507
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/PaasCassandraBootstrap.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.paas.cassandra; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.netflix.paas.PaasBootstrap; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.dao.DaoSchema; public class PaasCassandraBootstrap { private static final Logger LOG = LoggerFactory.getLogger(PaasBootstrap.class); @Inject public PaasCassandraBootstrap(DaoProvider daoProvider) throws Exception { LOG.info("Bootstrap PaasAstyanax"); DaoSchema schemaDao = daoProvider.getSchema(SchemaNames.CONFIGURATION.name()); if (!schemaDao.isExists()) { schemaDao.createSchema(); } Dao<CassandraClusterEntity> clusterDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), CassandraClusterEntity.class); if (!clusterDao.isExists()) { clusterDao.createTable(); } } }
508
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/CassandraPaasModule.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.paas.cassandra; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.multibindings.MapBinder; import com.netflix.paas.cassandra.admin.CassandraClusterAdminResource; import com.netflix.paas.cassandra.admin.CassandraClusterAdminResourceFactory; import com.netflix.paas.cassandra.admin.CassandraSystemAdminResource; import com.netflix.paas.cassandra.discovery.ClusterDiscoveryService; import com.netflix.paas.cassandra.discovery.LocalClusterDiscoveryService; import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider; import com.netflix.paas.cassandra.provider.CassandraTableResourceFactory; import com.netflix.paas.cassandra.provider.ClusterClientProvider; import com.netflix.paas.cassandra.provider.HostSupplierProvider; import com.netflix.paas.cassandra.provider.KeyspaceClientProvider; import com.netflix.paas.cassandra.provider.impl.DefaultAstyanaxConfigurationProvider; import com.netflix.paas.cassandra.provider.impl.DefaultAstyanaxConnectionPoolConfigurationProvider; import com.netflix.paas.cassandra.provider.impl.DefaultAstyanaxConnectionPoolMonitorProvider; import com.netflix.paas.cassandra.provider.impl.DefaultAstyanaxClusterClientProvider; import com.netflix.paas.cassandra.provider.impl.DefaultKeyspaceClientProvider; import com.netflix.paas.cassandra.provider.impl.LocalHostSupplierProvider; import com.netflix.paas.cassandra.resources.admin.AstyanaxThriftClusterAdminResource; import com.netflix.paas.cassandra.tasks.ClusterDiscoveryTask; import com.netflix.paas.cassandra.tasks.ClusterRefreshTask; import com.netflix.paas.dao.DaoSchemaProvider; import com.netflix.paas.dao.astyanax.AstyanaxDaoSchemaProvider; import com.netflix.paas.provider.TableDataResourceFactory; import com.netflix.paas.resources.impl.JerseySchemaDataResourceImpl; public class CassandraPaasModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(CassandraPaasModule.class); @Override protected void configure() { LOG.info("Loading CassandraPaasModule"); // There will be a different TableResourceProvider for each persistence technology MapBinder<String, TableDataResourceFactory> tableResourceProviders = MapBinder.newMapBinder(binder(), String.class, TableDataResourceFactory.class); tableResourceProviders.addBinding("cassandra").to(CassandraTableResourceFactory.class).in(Scopes.SINGLETON); // Binding to enable DAOs using astyanax MapBinder<String, DaoSchemaProvider> daoManagers = MapBinder.newMapBinder(binder(), String.class, DaoSchemaProvider.class); daoManagers.addBinding("astyanax").to(AstyanaxDaoSchemaProvider.class).in(Scopes.SINGLETON); bind(AstyanaxConfigurationProvider.class) .to(DefaultAstyanaxConfigurationProvider.class).in(Scopes.SINGLETON); bind(AstyanaxConnectionPoolConfigurationProvider.class).to(DefaultAstyanaxConnectionPoolConfigurationProvider.class).in(Scopes.SINGLETON); bind(AstyanaxConnectionPoolMonitorProvider.class) .to(DefaultAstyanaxConnectionPoolMonitorProvider.class).in(Scopes.SINGLETON); bind(KeyspaceClientProvider.class) .to(DefaultKeyspaceClientProvider.class).in(Scopes.SINGLETON); bind(ClusterClientProvider.class) .to(DefaultAstyanaxClusterClientProvider.class).in(Scopes.SINGLETON); install(new FactoryModuleBuilder() .implement(CassandraClusterAdminResource.class, AstyanaxThriftClusterAdminResource.class) .build(CassandraClusterAdminResourceFactory.class)); // REST resources bind(ClusterDiscoveryService.class).to(LocalClusterDiscoveryService.class); bind(CassandraSystemAdminResource.class).in(Scopes.SINGLETON); bind(JerseySchemaDataResourceImpl.class).in(Scopes.SINGLETON); MapBinder<String, HostSupplierProvider> hostSuppliers = MapBinder.newMapBinder(binder(), String.class, HostSupplierProvider.class); hostSuppliers.addBinding("local").to(LocalHostSupplierProvider.class).in(Scopes.SINGLETON); // Tasks bind(ClusterDiscoveryTask.class); bind(ClusterRefreshTask.class); } }
509
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/MetaModule.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.paas.cassandra; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.Cluster; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.name.Named; import com.netflix.paas.PaasModule; import com.netflix.paas.dao.astyanax.MetaDaoImpl; import com.netflix.paas.dao.meta.CqlMetaDaoImpl; import com.netflix.paas.meta.dao.MetaDao; public class MetaModule extends AbstractModule{ private static final Logger LOG = LoggerFactory.getLogger(MetaModule.class); @Override protected void configure() { // TODO Auto-generated method stub // bind(MetaDao.class).to(MetaDaoImpl.class).asEagerSingleton(); bind(MetaDao.class).to(CqlMetaDaoImpl.class).asEagerSingleton(); } @Provides Cluster provideCluster(@Named("clustername") String clustername) { //String nodes = eureka.getNodes(clustername); //get nodes in the cluster, to pass as parameters to the underlying apis Cluster cluster = Cluster.builder().addContactPoint("localhost").build(); return cluster; } }
510
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/MetaCassandraBootstrap.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.paas.cassandra; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.netflix.paas.PaasBootstrap; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.dao.DaoSchema; public class MetaCassandraBootstrap { private static final Logger LOG = LoggerFactory.getLogger(PaasBootstrap.class); @Inject public MetaCassandraBootstrap(DaoProvider daoProvider) throws Exception { LOG.info("Bootstrap Meta Cassandra"); DaoSchema schemaDao = daoProvider.getSchema(SchemaNames.META.name()); if (!schemaDao.isExists()) { schemaDao.createSchema(); } Dao<CassandraClusterEntity> clusterDao = daoProvider.getDao(SchemaNames.META.name(), CassandraClusterEntity.class); if (!clusterDao.isExists()) { clusterDao.createTable(); } } }
511
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/tasks/ClearSchemasTask.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.paas.cassandra.tasks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.paas.tasks.Task; import com.netflix.paas.tasks.TaskContext; public class ClearSchemasTask implements Task { private static final Logger LOG = LoggerFactory.getLogger(ClearSchemasTask.class); @Override public void execte(TaskContext context) throws Exception { } }
512
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/tasks/ClusterRefreshTask.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.paas.cassandra.tasks; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.MapDifference; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.inject.Inject; import com.netflix.astyanax.Cluster; import com.netflix.astyanax.ddl.ColumnDefinition; import com.netflix.astyanax.ddl.ColumnFamilyDefinition; import com.netflix.astyanax.ddl.FieldMetadata; import com.netflix.astyanax.ddl.KeyspaceDefinition; import com.netflix.paas.JsonSerializer; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.cassandra.entity.MapStringToObject; import com.netflix.paas.cassandra.keys.ClusterKey; import com.netflix.paas.cassandra.provider.ClusterClientProvider; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.tasks.Task; import com.netflix.paas.tasks.TaskContext; /** * Refresh the information for a cluster * * @author elandau * */ public class ClusterRefreshTask implements Task { private static Logger LOG = LoggerFactory.getLogger(ClusterRefreshTask.class); private final ClusterClientProvider provider; private final Dao<CassandraClusterEntity> clusterDao; @Inject public ClusterRefreshTask(ClusterClientProvider provider, DaoProvider daoProvider) throws Exception { this.provider = provider; this.clusterDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), CassandraClusterEntity.class); } @Override public void execte(TaskContext context) throws Exception{ // Get parameters from the context String clusterName = context.getStringParameter("cluster"); Boolean ignoreSystem = context.getBooleanParameter("ignoreSystem", true); CassandraClusterEntity entity = (CassandraClusterEntity)context.getParamater("entity"); LOG.info("Refreshing cluster " + clusterName); // Read the current state from the DAO // CassandraClusterEntity entity = clusterDao.read(clusterName); Map<String, String> existingKeyspaces = entity.getKeyspaces(); if (existingKeyspaces == null) { existingKeyspaces = Maps.newHashMap(); entity.setKeyspaces(existingKeyspaces); } Map<String, String> existingColumnFamilies = entity.getColumnFamilies(); if (existingColumnFamilies == null) { existingColumnFamilies = Maps.newHashMap(); entity.setColumnFamilies(existingColumnFamilies); } Set<String> foundKeyspaces = Sets.newHashSet(); Set<String> foundColumnFamilies = Sets.newHashSet(); Cluster cluster = provider.acquireCluster(new ClusterKey(entity.getClusterName(), entity.getDiscoveryType())); boolean changed = false; // // Iterate found keyspaces try { for (KeyspaceDefinition keyspace : cluster.describeKeyspaces()) { // Extract data from the KeyspaceDefinition String ksName = keyspace.getName(); MapStringToObject keyspaceOptions = getKeyspaceOptions(keyspace); if (existingKeyspaces.containsKey(ksName)) { MapStringToObject previousOptions = JsonSerializer.fromString(existingKeyspaces.get(ksName), MapStringToObject.class); MapDifference keyspaceDiff = Maps.difference(keyspaceOptions, previousOptions); if (keyspaceDiff.areEqual()) { LOG.info("Keyspace '{}' didn't change", new Object[]{ksName}); } else { changed = true; LOG.info("CF Changed: " + keyspaceDiff.entriesDiffering()); } } else { changed = true; } String strKeyspaceOptions = JsonSerializer.toString(keyspaceOptions); // // Keep track of keyspace foundKeyspaces.add(keyspace.getName()); existingKeyspaces.put(ksName, strKeyspaceOptions); LOG.info("Found keyspace '{}|{}' : {}", new Object[]{entity.getClusterName(), ksName, keyspaceOptions}); // // Iterate found column families for (ColumnFamilyDefinition cf : keyspace.getColumnFamilyList()) { // Extract data from the ColumnFamilyDefinition String cfName = String.format("%s|%s", keyspace.getName(), cf.getName()); MapStringToObject cfOptions = getColumnFamilyOptions(cf); String strCfOptions = JsonSerializer.toString(cfOptions); // // // Check for changes if (existingColumnFamilies.containsKey(cfName)) { MapStringToObject previousOptions = JsonSerializer.fromString(existingColumnFamilies.get(cfName), MapStringToObject.class); LOG.info("Old options: " + previousOptions); MapDifference cfDiff = Maps.difference(cfOptions, previousOptions); if (cfDiff.areEqual()) { LOG.info("CF '{}' didn't change", new Object[]{cfName}); } else { changed = true; LOG.info("CF Changed: " + cfDiff.entriesDiffering()); } } else { changed = true; } // // // Keep track of the cf foundColumnFamilies.add(cfName); existingColumnFamilies.put(cfName, strCfOptions); LOG.info("Found column family '{}|{}|{}' : {}", new Object[]{entity.getClusterName(), keyspace.getName(), cf.getName(), strCfOptions}); } } } catch (Exception e) { LOG.info("Error refreshing cluster: " + entity.getClusterName(), e); entity.setEnabled(false); } SetView<String> ksRemoved = Sets.difference(existingKeyspaces.keySet(), foundKeyspaces); LOG.info("Keyspaces removed: " + ksRemoved); SetView<String> cfRemoved = Sets.difference(existingColumnFamilies.keySet(), foundColumnFamilies); LOG.info("CF removed: " + cfRemoved); clusterDao.write(entity); } private MapStringToObject getKeyspaceOptions(KeyspaceDefinition keyspace) { MapStringToObject result = new MapStringToObject(); for (FieldMetadata field : keyspace.getFieldsMetadata()) { result.put(field.getName(), keyspace.getFieldValue(field.getName())); } result.remove("CF_DEFS"); return result; } private MapStringToObject getColumnFamilyOptions(ColumnFamilyDefinition cf) { MapStringToObject result = new MapStringToObject(); for (FieldMetadata field : cf.getFieldsMetadata()) { if (field.getName().equals("COLUMN_METADATA")) { // // This will get handled below } else { Object value = cf.getFieldValue(field.getName()); if (value instanceof ByteBuffer) { result.put(field.getName(), ((ByteBuffer)value).array()); } else { result.put(field.getName(), value); } } } // // Hack to get the column metadata List<MapStringToObject> columns = Lists.newArrayList(); for (ColumnDefinition column : cf.getColumnDefinitionList()) { MapStringToObject map = new MapStringToObject(); for (FieldMetadata field : column.getFieldsMetadata()) { Object value = column.getFieldValue(field.getName()); if (value instanceof ByteBuffer) { result.put(field.getName(), ((ByteBuffer)value).array()); } else { map.put(field.getName(), value); } } columns.add(map); } result.put("COLUMN_METADATA", columns); return result; } }
513
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/tasks/ClusterToVirtualSchemaTask.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.paas.cassandra.tasks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.paas.tasks.Task; import com.netflix.paas.tasks.TaskContext; /** * Load a schema into a task * @author elandau * */ public class ClusterToVirtualSchemaTask implements Task { private static final Logger LOG = LoggerFactory.getLogger(ClusterToVirtualSchemaTask.class); @Override public void execte(TaskContext context) throws Exception { String clusterName = context.getStringParameter("cluster"); } }
514
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/tasks/ClusterDiscoveryTask.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.paas.cassandra.tasks; import java.util.Collection; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.discovery.ClusterDiscoveryService; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.tasks.Task; import com.netflix.paas.tasks.TaskContext; import com.netflix.paas.tasks.TaskManager; /** * Task to compare the list of clusters in the Dao and the list of clusters from the discovery * service and add/remove/update in response to any changes. * * @author elandau * */ public class ClusterDiscoveryTask implements Task { private static final Logger LOG = LoggerFactory.getLogger(ClusterDiscoveryTask.class); private final ClusterDiscoveryService discoveryService; private final Dao<CassandraClusterEntity> clusterDao; private final TaskManager taskManager; @Inject public ClusterDiscoveryTask( ClusterDiscoveryService discoveryService, DaoProvider daoProvider, TaskManager taskManager) throws NotFoundException{ this.discoveryService = discoveryService; this.clusterDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), CassandraClusterEntity.class); this.taskManager = taskManager; } @Override public void execte(TaskContext context) throws Exception { // Get complete set of existing clusters from the discovery service Collection<String> clusters = Sets.newHashSet(discoveryService.getClusterNames()); LOG.info(clusters.toString()); // Load entire list of previously known clusters to a map of <ClusterName> => <ClusterEntity> Map<String, CassandraClusterEntity> existingClusters = Maps.uniqueIndex( this.clusterDao.list(), new Function<CassandraClusterEntity, String>() { @Override public String apply(CassandraClusterEntity cluster) { LOG.info("Found existing cluster : " + cluster.getClusterName()); return cluster.getClusterName(); } }); // Iterate through new list of clusters and look for changes for (String clusterName : clusters) { CassandraClusterEntity entity = existingClusters.get(clusterName); // This is a new cluster if (entity == null) { LOG.info("Found new cluster : " + clusterName); entity = CassandraClusterEntity.builder() .withName(clusterName) .withIsEnabled(true) .withDiscoveryType(discoveryService.getName()) .build(); try { clusterDao.write(entity); } catch (Exception e) { LOG.warn("Failed to persist cluster info for '{}'", new Object[]{clusterName, e}); } updateCluster(entity); } // We knew about it before and it is disabled else if (!entity.isEnabled()) { LOG.info("Cluster '{}' is disabled and will not be refreshed", new Object[]{clusterName}); } // Refresh the info for an existing cluster else { LOG.info("Cluster '{}' is being refreshed", new Object[]{clusterName}); if (entity.getDiscoveryType() == null) { entity.setDiscoveryType(discoveryService.getName()); try { clusterDao.write(entity); } catch (Exception e) { LOG.warn("Failed to persist cluster info for '{}'", new Object[]{clusterName, e}); } } updateCluster(entity); } } } private void updateCluster(CassandraClusterEntity entity) { LOG.info("Need to update cluster " + entity.getClusterName()); try { taskManager.submit(ClusterRefreshTask.class, ImmutableMap.<String, Object>builder() .put("entity", entity) .build()); } catch (Exception e) { LOG.warn("Failed to create ClusterRefreshTask for " + entity.getClusterName(), e); } } }
515
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/entity/MapStringToObject.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.paas.cassandra.entity; import java.util.HashMap; public class MapStringToObject extends HashMap<String, Object> { }
516
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/entity/CassandraClusterEntity.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.paas.cassandra.entity; import java.util.Collection; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import org.apache.commons.lang.StringUtils; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; @Entity public class CassandraClusterEntity { public static class Builder { private final CassandraClusterEntity entity = new CassandraClusterEntity(); public Builder withName(String name) { entity.clusterName = name; return this; } public Builder withIsEnabled(Boolean enabled) { entity.enabled = enabled; return this; } public Builder withDiscoveryType(String discoveryType) { entity.discoveryType = discoveryType; return this; } public CassandraClusterEntity build() { Preconditions.checkNotNull(entity.clusterName); return this.entity; } } public static Builder builder() { return new Builder(); } @Id private String clusterName; @Column private Map<String, String> keyspaces; @Column private Map<String, String> columnFamilies; @Column(name="enabled") private boolean enabled = true; @Column(name="discovery") private String discoveryType; public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public Map<String, String> getKeyspaces() { return keyspaces; } public void setKeyspaces(Map<String, String> keyspaces) { this.keyspaces = keyspaces; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Collection<String> getColumnFamilyNames() { if (this.columnFamilies == null) return Lists.newArrayList(); return columnFamilies.keySet(); } public Collection<String> getKeyspaceNames() { if (this.keyspaces == null) return Lists.newArrayList(); return keyspaces.keySet(); } public Collection<String> getKeyspaceColumnFamilyNames(final String keyspaceName) { return Collections2.filter(this.columnFamilies.keySet(), new Predicate<String>() { @Override public boolean apply(String cfName) { return StringUtils.startsWith(cfName, keyspaceName + "|"); } }); } public Map<String, String> getColumnFamilies() { return columnFamilies; } public void setColumnFamilies(Map<String, String> columnFamilies) { this.columnFamilies = columnFamilies; } public String getDiscoveryType() { return discoveryType; } public void setDiscoveryType(String discoveryType) { this.discoveryType = discoveryType; } }
517
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/entity/ColumnFamilyEntity.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.paas.cassandra.entity; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import com.google.common.base.Preconditions; @Entity public class ColumnFamilyEntity { public static class Builder { private final ColumnFamilyEntity entity = new ColumnFamilyEntity(); public Builder withName(String name) { entity.name = name; return this; } public Builder withKeyspace(String name) { entity.keyspaceName = name; return this; } public Builder withCluster(String name) { entity.clusterName = name; return this; } public Builder withOptions(Map<String, String> options) { entity.setOptions(options); return this; } public ColumnFamilyEntity build() { Preconditions.checkNotNull(entity.name); return this.entity; } } public static Builder builder() { return new Builder(); } @PrePersist private void prePersist() { this.id = String.format("%s.%s.%s", clusterName, keyspaceName, name); } @PostLoad private void postLoad() { this.id = String.format("%s.%s.%s", clusterName, keyspaceName, name); } @Id private String id; @Column(name="name") private String name; @Column(name="keyspace") private String keyspaceName; @Column(name="cluster") private String clusterName; /** * Low level Cassandra column family configuration parameters */ @Column(name="options") private Map<String, String> options; public String getKeyspaceName() { return keyspaceName; } public void setKeyspaceName(String keyspaceName) { this.keyspaceName = keyspaceName; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } }
518
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/entity/KeyspaceEntity.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.paas.cassandra.entity; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.Transient; import com.google.common.base.Preconditions; import com.netflix.paas.exceptions.NotFoundException; @Entity public class KeyspaceEntity { public static class Builder { private final KeyspaceEntity entity = new KeyspaceEntity(); public Builder withName(String name) { entity.name = name; return this; } public Builder addColumnFamily(String columnFamilyName) { if (entity.getColumnFamilies() == null) { entity.setColumnFamilies(new HashSet<String>()); } entity.getColumnFamilies().add(columnFamilyName); return this; } public Builder withOptions(Map<String, String> options) { entity.setOptions(options); return this; } public KeyspaceEntity build() { return this.entity; } } public static Builder builder() { return new Builder(); } @Id private String id; @Column(name="name") private String name; @Column(name="cluster") private String clusterName; @Column(name="options") private Map<String, String> options; @Column(name="cfs") private Set<String> columnFamilies; @Transient private Map<String, ColumnFamilyEntity> columnFamilyEntities; @PrePersist private void prePersist() { this.id = String.format("%s.%s", clusterName, name); } @PostLoad private void postLoad() { this.id = String.format("%s.%s", clusterName, name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, ColumnFamilyEntity> getColumnFamilyEntities() { return columnFamilyEntities; } public void setColumnFamilyEntities(Map<String, ColumnFamilyEntity> columnFamilyEntities) { this.columnFamilyEntities = columnFamilyEntities; } public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public Set<String> getColumnFamilies() { return columnFamilies; } public void setColumnFamilies(Set<String> columnFamilies) { this.columnFamilies = columnFamilies; } public ColumnFamilyEntity getColumnFamily(String columnFamilyName) throws NotFoundException { ColumnFamilyEntity entity = columnFamilyEntities.get(columnFamilyName); if (entity == null) throw new NotFoundException("columnfamily", columnFamilyName); return entity; } }
519
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/resources/CassandraKeyspaceHolder.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.paas.cassandra.resources; import java.util.concurrent.ConcurrentMap; import com.google.common.collect.Maps; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Keyspace; import com.netflix.paas.exceptions.AlreadyExistsException; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.resources.TableDataResource; /** * Tracks a keyspace and column families that are accessible on it to this instance * * @author elandau * */ public class CassandraKeyspaceHolder { private final AstyanaxContext<Keyspace> context; private final ConcurrentMap<String, TableDataResource> columnFamilies = Maps.newConcurrentMap(); public CassandraKeyspaceHolder(AstyanaxContext<Keyspace> context) { this.context = context; } /** * Register a column family on this keyspace and create the appropriate DataTableResource * to read from it. * * @param columnFamily * @throws AlreadyExistsException */ public synchronized void registerColumnFamily(String columnFamily) throws AlreadyExistsException { if (columnFamilies.containsKey(columnFamily)) throw new AlreadyExistsException("columnfamily", columnFamily); columnFamilies.put(columnFamily, new AstyanaxThriftDataTableResource(context.getClient(), columnFamily)); } /** * Unregister a column family so that it is no longer available * @param columnFamily * @throws NotFoundException */ public synchronized void unregisterColumnFamily(String columnFamily) throws NotFoundException { columnFamilies.remove(columnFamily); } /** * Retrieve a register column family resource * * @param columnFamily * @return * @throws NotFoundException */ public TableDataResource getColumnFamilyDataResource(String columnFamily) throws NotFoundException { TableDataResource resource = columnFamilies.get(columnFamily); if (resource == null) throw new NotFoundException("columnfamily", columnFamily); return resource; } public void shutdown() { this.context.shutdown(); } public void initialize() { this.context.start(); } }
520
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/resources/AstyanaxThriftDataTableResource.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.paas.cassandra.resources; import java.nio.ByteBuffer; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; 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.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.model.Rows; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.query.RowQuery; import com.netflix.astyanax.serializers.ByteBufferSerializer; import com.netflix.astyanax.util.RangeBuilder; import com.netflix.paas.data.QueryResult; import com.netflix.paas.data.RowData; import com.netflix.paas.data.SchemalessRows; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.exceptions.PaasException; import com.netflix.paas.json.JsonObject; import com.netflix.paas.resources.TableDataResource; /** * Column family REST resource * @author elandau * */ public class AstyanaxThriftDataTableResource implements TableDataResource { private static Logger LOG = LoggerFactory.getLogger(AstyanaxThriftDataTableResource.class); private final Keyspace keyspace; private final ColumnFamily<ByteBuffer, ByteBuffer> columnFamily; private volatile SerializerPackage serializers; public AstyanaxThriftDataTableResource(Keyspace keyspace, String name) { this.keyspace = keyspace; this.columnFamily = ColumnFamily.newColumnFamily(name, ByteBufferSerializer.get(), ByteBufferSerializer.get()); } @Override public QueryResult listRows(String cursor, Integer rowLimit, Integer columnLimit) throws PaasException { try { invariant(); // Execute the query Partitioner partitioner = keyspace.getPartitioner(); Rows<ByteBuffer, ByteBuffer> result = keyspace .prepareQuery(columnFamily) .getKeyRange(null, null, cursor != null ? cursor : partitioner.getMinToken(), partitioner.getMaxToken(), rowLimit) .execute() .getResult(); // Convert raw data into a simple sparse tree SchemalessRows.Builder builder = SchemalessRows.builder(); for (Row<ByteBuffer, ByteBuffer> row : result) { Map<String, String> columns = Maps.newHashMap(); for (Column<ByteBuffer> column : row.getColumns()) { columns.put(serializers.columnAsString(column.getRawName()), serializers.valueAsString(column.getRawName(), column.getByteBufferValue())); } builder.addRow(serializers.keyAsString(row.getKey()), columns); } QueryResult dr = new QueryResult(); dr.setSrows(builder.build()); if (!result.isEmpty()) { dr.setCursor(partitioner.getTokenForKey(Iterables.getLast(result).getKey())); } return dr; } catch (ConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public void truncateRows() { } @Override public QueryResult readRow(String key, Integer columnCount, String startColumn, String endColumn, Boolean reversed) throws PaasException { invariant(); try { // Construct the query RowQuery<ByteBuffer, ByteBuffer> query = keyspace .prepareQuery(this.columnFamily) .getRow(serializers.keyAsByteBuffer(key)); RangeBuilder range = new RangeBuilder(); if (columnCount != null && columnCount > 0) { range.setLimit(columnCount); } if (startColumn != null && !startColumn.isEmpty()) { range.setStart(serializers.columnAsByteBuffer(startColumn)); } if (endColumn != null && !endColumn.isEmpty()) { range.setEnd(serializers.columnAsByteBuffer(endColumn)); } range.setReversed(reversed); query.withColumnRange(range.build()); // Execute the query ColumnList<ByteBuffer> result = query.execute().getResult(); // Convert raw data into a simple sparse tree SchemalessRows.Builder builder = SchemalessRows.builder(); Map<String, String> columns = Maps.newHashMap(); if (!result.isEmpty()) { for (Column<ByteBuffer> column : result) { columns.put(serializers.columnAsString(column.getRawName()), serializers.valueAsString(column.getRawName(), column.getByteBufferValue())); } builder.addRow(key, columns); } QueryResult dr = new QueryResult(); dr.setSrows(builder.build()); return dr; } catch (ConnectionException e) { throw new PaasException( String.format("Failed to read row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } @Override public void deleteRow(String key) throws PaasException { invariant(); MutationBatch mb = keyspace.prepareMutationBatch(); mb.withRow(this.columnFamily, serializers.keyAsByteBuffer(key)).delete(); try { mb.execute(); } catch (ConnectionException e) { throw new PaasException( String.format("Failed to update row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } public void updateRow(String key, RowData rowData) throws PaasException { LOG.info("Update row: " + rowData.toString()); invariant(); MutationBatch mb = keyspace.prepareMutationBatch(); if (rowData.hasSchemalessRows()) { ColumnListMutation<ByteBuffer> mbRow = mb.withRow(this.columnFamily, serializers.keyAsByteBuffer(key)); for (Entry<String, Map<String, String>> row : rowData.getSrows().getRows().entrySet()) { for (Entry<String, String> column : row.getValue().entrySet()) { mbRow.putColumn(serializers.columnAsByteBuffer(column.getKey()), serializers.valueAsByteBuffer(column.getKey(), column.getValue())); } } } try { mb.execute(); } catch (ConnectionException e) { throw new PaasException( String.format("Failed to update row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } @Override public QueryResult readColumn(String key, String column) throws NotFoundException, PaasException { invariant(); try { Column<ByteBuffer> result = keyspace .prepareQuery(this.columnFamily) .getRow(serializers.keyAsByteBuffer(key)) .getColumn(serializers.columnAsByteBuffer(column)) .execute() .getResult(); // Convert raw data into a simple sparse tree SchemalessRows.Builder builder = SchemalessRows.builder(); Map<String, String> columns = Maps.newHashMap(); columns.put(serializers.columnAsString(result.getRawName()), serializers.valueAsString(result.getRawName(), result.getByteBufferValue())); builder.addRow(key, columns); QueryResult dr = new QueryResult(); dr.setSrows(builder.build()); return dr; } catch (com.netflix.astyanax.connectionpool.exceptions.NotFoundException e) { throw new NotFoundException( "column", String.format("%s.%s.%s.%s", key, column, this.keyspace.getKeyspaceName(), this.columnFamily.getName())); } catch (ConnectionException e) { throw new PaasException( String.format("Failed to read row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } @Override public void updateColumn(String key, String column, String value) throws NotFoundException, PaasException { LOG.info("Update row"); invariant(); MutationBatch mb = keyspace.prepareMutationBatch(); ColumnListMutation<ByteBuffer> mbRow = mb.withRow(this.columnFamily, serializers.keyAsByteBuffer(key)); mbRow.putColumn(serializers.columnAsByteBuffer(column), serializers.valueAsByteBuffer(column, value)); try { mb.execute(); } catch (ConnectionException e) { throw new PaasException( String.format("Failed to update row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } @Override public void deleteColumn(String key, String column) throws PaasException { LOG.info("Update row"); invariant(); MutationBatch mb = keyspace.prepareMutationBatch(); ColumnListMutation<ByteBuffer> mbRow = mb.withRow(this.columnFamily, serializers.keyAsByteBuffer(key)); mbRow.deleteColumn(serializers.columnAsByteBuffer(column)); try { mb.execute(); } catch (ConnectionException e) { throw new PaasException( String.format("Failed to update row '%s' in column family '%s.%s'" , key, this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } private void invariant() throws PaasException { if (this.serializers == null) refreshSerializers(); } private void refreshSerializers() throws PaasException { try { this.serializers = this.keyspace.getSerializerPackage(this.columnFamily.getName(), true); } catch (Exception e) { LOG.error("Failed to get serializer package for column family '{}.{}'", new Object[]{keyspace.getKeyspaceName(), this.columnFamily.getName(), e}); throw new PaasException( String.format("Failed to get serializer package for column family '%s.%s' in keyspace", this.keyspace.getKeyspaceName(), this.columnFamily.getName()), e); } } @Override @POST @Path("{db}/{table}") public void updateRow(@PathParam("db") String db, @PathParam("table") String table, JsonObject rowData) throws PaasException { // TODO Auto-generated method stub } }
521
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/resources/CassandraClusterHolder.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.paas.cassandra.resources; import java.util.concurrent.ConcurrentMap; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.connectionpool.NodeDiscoveryType; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType; import com.netflix.astyanax.connectionpool.impl.Slf4jConnectionPoolMonitorImpl; import com.netflix.astyanax.impl.AstyanaxConfigurationImpl; import com.netflix.astyanax.thrift.ThriftFamilyFactory; import com.netflix.paas.exceptions.AlreadyExistsException; import com.netflix.paas.exceptions.NotFoundException; /** * Tracks accessible keyspaces for this cluster * * @author elandau */ public class CassandraClusterHolder { private final String clusterName; private final ConcurrentMap<String, CassandraKeyspaceHolder> keyspaces = Maps.newConcurrentMap(); public CassandraClusterHolder(String clusterName) { this.clusterName = clusterName; } /** * Register a keyspace such that a client is created for it and it is now accessible to * this instance * * @param keyspaceName * @throws AlreadyExistsException */ public synchronized void registerKeyspace(String keyspaceName) throws AlreadyExistsException { Preconditions.checkNotNull(keyspaceName); if (keyspaces.containsKey(keyspaceName)) { throw new AlreadyExistsException("keyspace", keyspaceName); } CassandraKeyspaceHolder keyspace = new CassandraKeyspaceHolder(new AstyanaxContext.Builder() .forCluster(clusterName) .forKeyspace(keyspaceName) .withAstyanaxConfiguration( new AstyanaxConfigurationImpl() .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE) .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN) .setDiscoveryDelayInSeconds(60000)) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl( clusterName + "_" + keyspaceName) .setSeeds("localhost:9160")) .withConnectionPoolMonitor(new Slf4jConnectionPoolMonitorImpl()) .buildKeyspace(ThriftFamilyFactory.getInstance())); try { keyspace.initialize(); } finally { keyspaces.put(keyspaceName, keyspace); } } /** * Unregister a keyspace so that it is no longer accessible to this instance * @param keyspaceName */ public void unregisterKeyspace(String keyspaceName) { Preconditions.checkNotNull(keyspaceName); CassandraKeyspaceHolder keyspace = keyspaces.remove(keyspaceName); if (keyspace != null) { keyspace.shutdown(); } } /** * Get the Keyspace holder for the specified keyspace name * * @param keyspaceName * @return * @throws NotFoundException */ public CassandraKeyspaceHolder getKeyspace(String keyspaceName) throws NotFoundException { Preconditions.checkNotNull(keyspaceName); CassandraKeyspaceHolder keyspace = keyspaces.get(keyspaceName); if (keyspace == null) throw new NotFoundException("keyspace", keyspaceName); return keyspace; } public String getClusterName() { return this.clusterName; } public void shutdown() { // TODO } public void initialize() { // TODO } }
522
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/resources
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/resources/admin/AstyanaxThriftClusterAdminResource.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.paas.cassandra.resources.admin; import java.util.Collection; import java.util.Properties; import java.util.concurrent.ScheduledExecutorService; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.persistence.PersistenceException; import javax.ws.rs.PathParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.eventbus.EventBus; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import com.google.inject.name.Named; import com.netflix.astyanax.Cluster; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.paas.cassandra.admin.CassandraClusterAdminResource; import com.netflix.paas.cassandra.discovery.ClusterDiscoveryService; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.cassandra.entity.ColumnFamilyEntity; import com.netflix.paas.cassandra.entity.KeyspaceEntity; import com.netflix.paas.cassandra.events.ColumnFamilyDeleteEvent; import com.netflix.paas.cassandra.events.ColumnFamilyUpdateEvent; import com.netflix.paas.cassandra.events.KeyspaceUpdateEvent; import com.netflix.paas.cassandra.keys.ClusterKey; import com.netflix.paas.cassandra.keys.ColumnFamilyKey; import com.netflix.paas.cassandra.keys.KeyspaceKey; import com.netflix.paas.cassandra.provider.ClusterClientProvider; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.dao.astyanax.DaoKeys; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.exceptions.PaasException; /** * Implementation of a Cassandra Cluster Admin interface using Astyanax and Thrift. * Since this is the admin interface only one connection is actually needed to the cluster * * @author elandau */ public class AstyanaxThriftClusterAdminResource implements CassandraClusterAdminResource { private static final Logger LOG = LoggerFactory.getLogger(AstyanaxThriftClusterAdminResource.class); private final ClusterKey clusterKey; private final Cluster cluster; private final DaoProvider daoProvider; private final EventBus eventBus; @Inject public AstyanaxThriftClusterAdminResource( EventBus eventBus, DaoProvider daoProvider, @Named("tasks") ScheduledExecutorService taskExecutor, ClusterDiscoveryService discoveryService, ClusterClientProvider clusterProvider, @Assisted ClusterKey clusterKey) { this.clusterKey = clusterKey; this.cluster = clusterProvider.acquireCluster(clusterKey); this.daoProvider = daoProvider; this.eventBus = eventBus; } @PostConstruct public void initialize() { } @PreDestroy public void shutdown() { } @Override public CassandraClusterEntity getClusterDetails() throws PersistenceException { return daoProvider.getDao(DaoKeys.DAO_CASSANDRA_CLUSTER_ENTITY).read(clusterKey.getCanonicalName()); } @Override public KeyspaceEntity getKeyspace(String keyspaceName) throws PersistenceException { Dao<KeyspaceEntity> dao = daoProvider.getDao(DaoKeys.DAO_KEYSPACE_ENTITY); return dao.read(keyspaceName); } @Override public void createKeyspace(KeyspaceEntity keyspace) throws PaasException { LOG.info("Creating keyspace '{}'", new Object[] {keyspace.getName()}); Preconditions.checkNotNull(keyspace, "Missing keyspace entity definition"); Properties props = new Properties(); props.putAll(getDefaultKeyspaceProperties()); if (keyspace.getOptions() != null) { props.putAll(keyspace.getOptions()); } props.setProperty("name", keyspace.getName()); keyspace.setClusterName(clusterKey.getClusterName()); try { cluster.createKeyspace(props); eventBus.post(new KeyspaceUpdateEvent(new KeyspaceKey(clusterKey, keyspace.getName()))); } catch (ConnectionException e) { throw new PaasException(String.format("Error creating keyspace '%s' from cluster '%s'", keyspace.getName(), clusterKey.getClusterName()), e); } } @Override public void updateKeyspace(@PathParam("keyspace") String keyspaceName, KeyspaceEntity keyspace) throws PaasException { try { if (keyspace.getOptions() == null) { return; // Nothing to do } // Add them as existing values to the properties object Properties props = new Properties(); props.putAll(cluster.getKeyspaceProperties(keyspaceName)); props.putAll(keyspace.getOptions()); props.setProperty("name", keyspace.getName()); keyspace.setClusterName(clusterKey.getClusterName()); cluster.updateKeyspace(props); eventBus.post(new KeyspaceUpdateEvent(new KeyspaceKey(clusterKey, keyspace.getName()))); } catch (ConnectionException e) { throw new PaasException(String.format("Error creating keyspace '%s' from cluster '%s'", keyspace.getName(), clusterKey.getClusterName()), e); } } @Override public void deleteKeyspace(String keyspaceName) throws PaasException { LOG.info("Dropping keyspace"); try { cluster.dropKeyspace(keyspaceName); } catch (ConnectionException e) { throw new PaasException(String.format("Error deleting keyspace '%s' from cluster '%s'", keyspaceName, clusterKey.getClusterName()), e); } } @Override public ColumnFamilyEntity getColumnFamily(String keyspaceName, String columnFamilyName) throws NotFoundException { Dao<ColumnFamilyEntity> dao = daoProvider.getDao(DaoKeys.DAO_COLUMN_FAMILY_ENTITY); return dao.read(new ColumnFamilyKey(clusterKey, keyspaceName, columnFamilyName).getCanonicalName()); } @Override public void deleteColumnFamily(String keyspaceName, String columnFamilyName) throws PaasException { LOG.info("Deleting column family: '{}.{}.{}'", new Object[] {clusterKey.getClusterName(), keyspaceName, columnFamilyName}); try { cluster.dropColumnFamily(keyspaceName, columnFamilyName); } catch (ConnectionException e) { throw new PaasException(String.format("Error creating column family '%s.%s' on cluster '%s'", keyspaceName, columnFamilyName, clusterKey.getClusterName()), e); } eventBus.post(new ColumnFamilyDeleteEvent(new ColumnFamilyKey(clusterKey, keyspaceName, columnFamilyName))); } @Override public void createColumnFamily(@PathParam("keyspace") String keyspaceName, ColumnFamilyEntity columnFamily) throws PaasException { LOG.info("Creating column family: '{}.{}.{}'", new Object[] {clusterKey.getClusterName(), keyspaceName, columnFamily.getName()}); columnFamily.setKeyspaceName(keyspaceName); columnFamily.setClusterName(clusterKey.getClusterName()); Properties props = new Properties(); props.putAll(getDefaultColumnFamilyProperties()); if (columnFamily.getOptions() != null) { props.putAll(columnFamily.getOptions()); } props.setProperty("name", columnFamily.getName()); props.setProperty("keyspace", columnFamily.getKeyspaceName()); try { cluster.createColumnFamily(props); eventBus.post(new ColumnFamilyUpdateEvent(new ColumnFamilyKey(new KeyspaceKey(clusterKey, keyspaceName), columnFamily.getName()))); } catch (ConnectionException e) { throw new PaasException(String.format("Error creating column family '%s.%s' on cluster '%s'", keyspaceName, columnFamily.getName(), clusterKey.getClusterName()), e); } } @Override public void updateColumnFamily(@PathParam("keyspace") String keyspaceName, String columnFamilyName, ColumnFamilyEntity columnFamily) throws PaasException { LOG.info("Updating column family: '{}.{}.{}'", new Object[] {clusterKey.getClusterName(), keyspaceName, columnFamily.getName()}); columnFamily.setKeyspaceName(keyspaceName); columnFamily.setClusterName(clusterKey.getClusterName()); try { Properties props = new Properties(); props.putAll(cluster.getColumnFamilyProperties(keyspaceName, columnFamilyName)); if (columnFamily.getOptions() != null) { props.putAll(columnFamily.getOptions()); } props.setProperty("name", columnFamily.getName()); props.setProperty("keyspace", columnFamily.getKeyspaceName()); cluster.createColumnFamily(props); eventBus.post(new ColumnFamilyUpdateEvent(new ColumnFamilyKey(new KeyspaceKey(clusterKey, keyspaceName), columnFamily.getName()))); } catch (ConnectionException e) { throw new PaasException(String.format("Error creating column family '%s.%s' on cluster '%s'", keyspaceName, columnFamily.getName(), clusterKey.getClusterName()), e); } } @Override public Collection<ColumnFamilyEntity> listColumnFamilies() { // TODO Auto-generated method stub return null; } @Override public Collection<String> listKeyspaceNames() { // TODO Auto-generated method stub return null; } @Override public Collection<String> listColumnFamilyNames() { // TODO Auto-generated method stub return null; } private Properties getDefaultKeyspaceProperties() { // TODO: Read from configuration return new Properties(); } private Properties getDefaultColumnFamilyProperties() { return new Properties(); } @Override public Collection<KeyspaceEntity> listKeyspaces() { // TODO Auto-generated method stub return null; } }
523
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/discovery/ClusterDiscoveryService.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.paas.cassandra.discovery; import java.util.Collection; /** * Abstraction for service that keeps track of clusters. These clusters are normally stored * in a some naming service. The implementation handles any custom exclusions. * * @author elandau */ public interface ClusterDiscoveryService { /** * @return Return the complete list of clusters */ public Collection<String> getClusterNames(); /** * Return the name of this cluster service * @return */ String getName(); }
524
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/discovery/LocalClusterDiscoveryService.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.paas.cassandra.discovery; import java.util.Collection; import java.util.concurrent.ConcurrentMap; import com.google.common.collect.Maps; import com.netflix.paas.entity.ClusterEntity; import com.netflix.paas.exceptions.AlreadyExistsException; public class LocalClusterDiscoveryService implements ClusterDiscoveryService { private ConcurrentMap<String, ClusterEntity> clusters = Maps.newConcurrentMap(); public void addCluster(ClusterEntity cluster) throws AlreadyExistsException { if (null != clusters.putIfAbsent(cluster.getName(), cluster)) { throw new AlreadyExistsException("cluster", cluster.getName()); } } public void removeCluster(String clusterName) { } @Override public Collection<String> getClusterNames() { return clusters.keySet(); } @Override public String getName() { return "localhost"; } }
525
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/admin/CassandraClusterAdminResource.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.paas.cassandra.admin; import java.util.Collection; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.cassandra.entity.ColumnFamilyEntity; import com.netflix.paas.cassandra.entity.KeyspaceEntity; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.exceptions.PaasException; public interface CassandraClusterAdminResource { @GET public CassandraClusterEntity getClusterDetails(); @GET @Path("ks") public Collection<KeyspaceEntity> listKeyspaces(); @POST @Path("ks") public void createKeyspace(KeyspaceEntity keyspace) throws PaasException; @GET @Path("ks/{keyspace}") public KeyspaceEntity getKeyspace(@PathParam("keyspace") String keyspaceName) throws NotFoundException; @POST @Path("ks/{keyspace}") public void updateKeyspace(@PathParam("keyspace") String keyspaceName, KeyspaceEntity keyspace) throws PaasException; @DELETE @Path("ks/{keyspace}") public void deleteKeyspace(@PathParam("keyspace") String keyspaceName) throws PaasException; @POST @Path("ks/{keyspace}/cf") public void createColumnFamily(@PathParam("keyspace") String keyspaceName, ColumnFamilyEntity columnFamily) throws PaasException; @POST @Path("ks/{keyspace}/cf/{columnfamily}") public void updateColumnFamily(@PathParam("keyspace") String keyspaceName, String columnFamilyName, ColumnFamilyEntity columnFamily) throws PaasException; @GET @Path("ks/{keyspace}/cf/{columnfamily}") public ColumnFamilyEntity getColumnFamily(@PathParam("keyspace") String keyspaceName, String columnFamilyName) throws NotFoundException; @DELETE @Path("ks/{keyspace}/cf/{columnfamily}") public void deleteColumnFamily(@PathParam("keyspace") String keyspaceName, String columnFamilyName) throws PaasException; @GET @Path("cf") public Collection<ColumnFamilyEntity> listColumnFamilies(); @GET @Path("names/ks") public Collection<String> listKeyspaceNames(); @GET @Path("names/cf") public Collection<String> listColumnFamilyNames(); }
526
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/admin/CassandraClusterAdminResourceFactory.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.paas.cassandra.admin; import com.netflix.paas.cassandra.keys.ClusterKey; public interface CassandraClusterAdminResourceFactory { public CassandraClusterAdminResource get(ClusterKey clusterKey); }
527
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/admin/CassandraSystemAdminResource.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.paas.cassandra.admin; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.netflix.paas.SchemaNames; import com.netflix.paas.cassandra.discovery.ClusterDiscoveryService; import com.netflix.paas.cassandra.entity.CassandraClusterEntity; import com.netflix.paas.cassandra.tasks.ClusterDiscoveryTask; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.tasks.TaskManager; @Path("/v1/cassandra") public class CassandraSystemAdminResource { private static final Logger LOG = LoggerFactory.getLogger(CassandraSystemAdminResource.class); private final Dao<CassandraClusterEntity> dao; private final CassandraClusterAdminResourceFactory clusterResourceFactory; private final ClusterDiscoveryService clusterDiscovery; private final TaskManager taskManager; private final ConcurrentMap<String, CassandraClusterAdminResource> clusters = Maps.newConcurrentMap(); private static class CassandraClusterEntityToName implements Function<CassandraClusterEntity, String> { @Override public String apply(CassandraClusterEntity cluster) { return cluster.getClusterName(); } } @Inject public CassandraSystemAdminResource( TaskManager taskManager, DaoProvider daoProvider, ClusterDiscoveryService clusterDiscovery, CassandraClusterAdminResourceFactory clusterResourceFactory) throws Exception { this.clusterResourceFactory = clusterResourceFactory; this.dao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), CassandraClusterEntity.class); this.clusterDiscovery = clusterDiscovery; this.taskManager = taskManager; } @PostConstruct public void initialize() { } @PreDestroy public void shutdown() { } @Path("clusters/{id}") public CassandraClusterAdminResource getCluster(@PathParam("id") String clusterName) throws NotFoundException { CassandraClusterAdminResource resource = clusters.get(clusterName); if (resource == null) { throw new NotFoundException(CassandraClusterAdminResource.class, clusterName); } return resource; } @GET @Path("clusters") public Set<String> listClusters() { return clusters.keySet(); } @GET @Path("discover") public void discoverClusters() { taskManager.submit(ClusterDiscoveryTask.class); // Set<String> foundNames = Sets.newHashSet(clusterDiscovery.getClusterNames()); // Map<String, CassandraClusterEntity> current = Maps.uniqueIndex(dao.list(), new CassandraClusterEntityToName()); // // // Look for new clusters (may contain clusters that are disabled) // for (String clusterName : Sets.difference(foundNames, current.keySet())) { //// CassandraClusterEntity entity = CassandraClusterEntity.builder(); // } // // // Look for clusters that were removed // for (String clusterName : Sets.difference(current.keySet(), foundNames)) { // } } @POST @Path("clusters") public void refreshClusterList() { // Map<String, CassandraClusterEntity> newList = Maps.uniqueIndex(dao.list(), new CassandraClusterEntityToName()); // // // Look for new clusters (may contain clusters that are disabled) // for (String clusterName : Sets.difference(newList.keySet(), clusters.keySet())) { // CassandraClusterEntity entity = newList.get(clusterName); // if (entity.isEnabled()) { // CassandraClusterAdminResource resource = clusterResourceFactory.get(clusterName); // if (null == clusters.putIfAbsent(clusterName, resource)) { // // TODO: Start it // } // } // } // // // Look for clusters that were removed // for (String clusterName : Sets.difference(clusters.keySet(), newList.keySet())) { // CassandraClusterAdminResource resource = clusters.remove(clusterName); // if (resource != null) { // // TODO: Shut it down // } // } // // // Look for clusters that may have been disabled // for (String clusterName : Sets.intersection(clusters.keySet(), newList.keySet())) { // CassandraClusterEntity entity = newList.get(clusterName); // if (!entity.isEnabled()) { // CassandraClusterAdminResource resource = clusters.remove(clusterName); // if (resource != null) { // // TODO: Shut it down // } // } // } } }
528
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/AstyanaxConnectionPoolMonitorProvider.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.paas.cassandra.provider; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; public interface AstyanaxConnectionPoolMonitorProvider { public ConnectionPoolMonitor get(String name); }
529
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/HostSupplierProvider.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.paas.cassandra.provider; import java.util.List; import com.google.common.base.Supplier; import com.netflix.astyanax.connectionpool.Host; public interface HostSupplierProvider { public Supplier<List<Host>> getSupplier(String clusterName); }
530
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/AstyanaxConnectionPoolConfigurationProvider.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.paas.cassandra.provider; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; public interface AstyanaxConnectionPoolConfigurationProvider { public ConnectionPoolConfiguration get(String name); }
531
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/ClusterClientProvider.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.paas.cassandra.provider; import com.netflix.astyanax.Cluster; import com.netflix.paas.cassandra.keys.ClusterKey; /** * Provider for cluster level client. For now the cluster level client is used * mostly for admin purposes * * @author elandau * */ public interface ClusterClientProvider { /** * Acquire a cassandra cluster by name. Must call releaseCluster once done. * The concrete provider must implement it's own reference counting and * garbage collection to shutdown Cluster clients that are not longer in use. * * @param clusterName */ public Cluster acquireCluster(ClusterKey clusterName); /** * Release a cassandra cluster that was acquired using acquireCluster * * @param clusterName */ public void releaseCluster(ClusterKey clusterName); }
532
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/KeyspaceClientProvider.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.paas.cassandra.provider; import com.netflix.astyanax.Keyspace; import com.netflix.paas.cassandra.keys.KeyspaceKey; /** * Abstraction for getting a keyspace. The implementation will handle lifecycle * management for the keyspace. * * @author elandau * */ public interface KeyspaceClientProvider { /** * Get a keyspace by name. Will create one if one does not exist. The provider * will internally keep track of references to the keyspace and will auto remove * it once releaseKeyspace is called and the reference count goes down to 0. * * @param keyspaceName Globally unique keyspace name * * @return A new or previously created keyspace. */ public Keyspace acquireKeyspace(String schemaName); /** * Get a keyspace by key. * @param key * @return */ public Keyspace acquireKeyspace(KeyspaceKey key); /** * Release a previously acquried keyspace * @param keyspace */ public void releaseKeyspace(String schemaName); }
533
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/CassandraTableResourceFactory.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.paas.cassandra.provider; //import org.mortbay.log.Log; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.netflix.astyanax.Keyspace; import com.netflix.paas.cassandra.keys.ClusterKey; import com.netflix.paas.cassandra.keys.KeyspaceKey; import com.netflix.paas.cassandra.resources.AstyanaxThriftDataTableResource; import com.netflix.paas.entity.TableEntity; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.provider.TableDataResourceFactory; import com.netflix.paas.resources.TableDataResource; public class CassandraTableResourceFactory implements TableDataResourceFactory { private final KeyspaceClientProvider clientProvider; @Inject public CassandraTableResourceFactory(KeyspaceClientProvider clientProvider) { this.clientProvider = clientProvider; } @Override public TableDataResource getTableDataResource(TableEntity table) throws NotFoundException { //Log.info(table.toString()); String clusterName = table.getOption("cassandra.cluster"); String keyspaceName = table.getOption("cassandra.keyspace"); String columnFamilyName = table.getOption("cassandra.columnfamily"); String discoveryType = table.getOption("discovery"); if (discoveryType == null) discoveryType = "eureka"; Preconditions.checkNotNull(clusterName, "Must specify cluster name for table " + table.getTableName()); Preconditions.checkNotNull(keyspaceName, "Must specify keyspace name for table " + table.getTableName()); Preconditions.checkNotNull(columnFamilyName, "Must specify column family name for table " + table.getTableName()); Preconditions.checkNotNull(discoveryType, "Must specify discovery type for table " + table.getTableName()); Keyspace keyspace = clientProvider.acquireKeyspace(new KeyspaceKey(new ClusterKey(clusterName, discoveryType), keyspaceName)); return new AstyanaxThriftDataTableResource(keyspace, columnFamilyName); } }
534
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/AstyanaxConfigurationProvider.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.paas.cassandra.provider; import com.netflix.astyanax.AstyanaxConfiguration; public interface AstyanaxConfigurationProvider { public AstyanaxConfiguration get(String name); }
535
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/AnnotatedAstyanaxConfiguration.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.paas.cassandra.provider.impl; import java.util.concurrent.ExecutorService; import com.netflix.astyanax.AstyanaxConfiguration; import com.netflix.astyanax.Clock; 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; import com.netflix.astyanax.retry.RunOnce; import com.netflix.governator.annotations.Configuration; public class AnnotatedAstyanaxConfiguration implements AstyanaxConfiguration { @Configuration("${prefix}.${name}.retryPolicy") private RetryPolicy retryPolicy = RunOnce.get(); @Configuration("${prefix}.${name}.defaultReadConsistencyLevel") private ConsistencyLevel defaultReadConsistencyLevel = ConsistencyLevel.CL_ONE; @Configuration("${prefix}.${name}.defaultWriteConsistencyLevel") private ConsistencyLevel defaultWriteConsistencyLevel = ConsistencyLevel.CL_ONE; @Configuration("${prefix}.${name}.clock") private String clockName = null; @Configuration("${prefix}.${name}.discoveryDelayInSeconds") private int discoveryDelayInSeconds; @Configuration("${prefix}.${name}.discoveryType") private NodeDiscoveryType discoveryType; @Configuration("${prefix}.${name}.connectionPoolType") private ConnectionPoolType getConnectionPoolType; @Configuration("${prefix}.${name}.cqlVersion") private String cqlVersion; private Clock clock; void initialize() { } void cleanup() { } @Override public RetryPolicy getRetryPolicy() { return retryPolicy; } @Override public ConsistencyLevel getDefaultReadConsistencyLevel() { return this.defaultReadConsistencyLevel; } @Override public ConsistencyLevel getDefaultWriteConsistencyLevel() { return this.defaultWriteConsistencyLevel; } @Override public Clock getClock() { return this.clock; } @Override public ExecutorService getAsyncExecutor() { return null; } @Override public int getDiscoveryDelayInSeconds() { // TODO Auto-generated method stub return 0; } @Override public NodeDiscoveryType getDiscoveryType() { // TODO Auto-generated method stub return null; } @Override public ConnectionPoolType getConnectionPoolType() { // TODO Auto-generated method stub return null; } @Override public String getCqlVersion() { // TODO Auto-generated method stub return null; } @Override public String getTargetCassandraVersion() { // TODO Auto-generated method stub return null; } @Override public Partitioner getPartitioner(String partitionerName) throws Exception { // TODO Auto-generated method stub return null; } }
536
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConnectionPoolConfigurationProvider.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.paas.cassandra.provider.impl; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider; public class DefaultAstyanaxConnectionPoolConfigurationProvider implements AstyanaxConnectionPoolConfigurationProvider { @Override public ConnectionPoolConfiguration get(String name) { return new ConnectionPoolConfigurationImpl(name); } }
537
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/LocalHostSupplierProvider.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.paas.cassandra.provider.impl; import java.util.List; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; import com.netflix.astyanax.connectionpool.Host; import com.netflix.paas.cassandra.provider.HostSupplierProvider; public class LocalHostSupplierProvider implements HostSupplierProvider { private final List<Host> localhost; public LocalHostSupplierProvider() { localhost = Lists.newArrayList(new Host("localhost", 9160)); } @Override public Supplier<List<Host>> getSupplier(String clusterName) { return Suppliers.ofInstance(localhost); } }
538
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConfigurationProvider.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.paas.cassandra.provider.impl; import com.netflix.astyanax.AstyanaxConfiguration; import com.netflix.astyanax.connectionpool.NodeDiscoveryType; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType; import com.netflix.astyanax.impl.AstyanaxConfigurationImpl; import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider; public class DefaultAstyanaxConfigurationProvider implements AstyanaxConfigurationProvider { @Override public AstyanaxConfiguration get(String name) { return new AstyanaxConfigurationImpl() .setDiscoveryType(NodeDiscoveryType.NONE) .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN) .setDiscoveryDelayInSeconds(60000) .setCqlVersion("3.0.0"); } }
539
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxConnectionPoolMonitorProvider.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.paas.cassandra.provider.impl; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.impl.Slf4jConnectionPoolMonitorImpl; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider; public class DefaultAstyanaxConnectionPoolMonitorProvider implements AstyanaxConnectionPoolMonitorProvider { @Override public ConnectionPoolMonitor get(String name) { return new Slf4jConnectionPoolMonitorImpl(); } }
540
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultAstyanaxClusterClientProvider.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.paas.cassandra.provider.impl; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.configuration.AbstractConfiguration; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Cluster; import com.netflix.astyanax.thrift.ThriftFamilyFactory; import com.netflix.paas.cassandra.keys.ClusterKey; import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider; import com.netflix.paas.cassandra.provider.ClusterClientProvider; import com.netflix.paas.cassandra.provider.HostSupplierProvider; public class DefaultAstyanaxClusterClientProvider implements ClusterClientProvider { /** * Track cluster references * * @author elandau * */ public static class ClusterContextHolder { private AstyanaxContext<Cluster> context; private AtomicLong refCount = new AtomicLong(0); public ClusterContextHolder(AstyanaxContext<Cluster> context) { this.context = context; } public Cluster getKeyspace() { return context.getClient(); } public void start() { context.start(); } public void shutdown() { context.shutdown(); } public long addRef() { return refCount.incrementAndGet(); } public long releaseRef() { return refCount.decrementAndGet(); } } private final Map<String, ClusterContextHolder> contextMap = Maps.newHashMap(); private final AstyanaxConfigurationProvider configurationProvider; private final AstyanaxConnectionPoolConfigurationProvider cpProvider; private final AstyanaxConnectionPoolMonitorProvider monitorProvider; private final Map<String, HostSupplierProvider> hostSupplierProviders; private final AbstractConfiguration configuration; @Inject public DefaultAstyanaxClusterClientProvider( AbstractConfiguration configuration, Map<String, HostSupplierProvider> hostSupplierProviders, AstyanaxConfigurationProvider configurationProvider, AstyanaxConnectionPoolConfigurationProvider cpProvider, AstyanaxConnectionPoolMonitorProvider monitorProvider) { this.configurationProvider = configurationProvider; this.cpProvider = cpProvider; this.monitorProvider = monitorProvider; this.hostSupplierProviders = hostSupplierProviders; this.configuration = configuration; } @Override public synchronized Cluster acquireCluster(ClusterKey clusterKey) { String clusterName = clusterKey.getClusterName().toLowerCase(); Preconditions.checkNotNull(clusterName, "Invalid cluster name 'null'"); ClusterContextHolder holder = contextMap.get(clusterName); if (holder == null) { HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(clusterKey.getDiscoveryType()); Preconditions.checkNotNull(hostSupplierProvider, String.format("Unknown host supplier provider '%s' for cluster '%s'", clusterKey.getDiscoveryType(), clusterName)); AstyanaxContext<Cluster> context = new AstyanaxContext.Builder() .forCluster(clusterName) .withAstyanaxConfiguration(configurationProvider.get(clusterName)) .withConnectionPoolConfiguration(cpProvider.get(clusterName)) .withConnectionPoolMonitor(monitorProvider.get(clusterName)) .withHostSupplier(hostSupplierProvider.getSupplier(clusterName)) .buildCluster(ThriftFamilyFactory.getInstance()); holder = new ClusterContextHolder(context); holder.start(); } holder.addRef(); return holder.getKeyspace(); } @Override public synchronized void releaseCluster(ClusterKey clusterKey) { String clusterName = clusterKey.getClusterName().toLowerCase(); ClusterContextHolder holder = contextMap.get(clusterName); if (holder.releaseRef() == 0) { contextMap.remove(clusterName); holder.shutdown(); } } }
541
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/provider/impl/DefaultKeyspaceClientProvider.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.paas.cassandra.provider.impl; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.configuration.AbstractConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.thrift.ThriftFamilyFactory; import com.netflix.paas.cassandra.keys.KeyspaceKey; import com.netflix.paas.cassandra.provider.AstyanaxConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolConfigurationProvider; import com.netflix.paas.cassandra.provider.AstyanaxConnectionPoolMonitorProvider; import com.netflix.paas.cassandra.provider.HostSupplierProvider; import com.netflix.paas.cassandra.provider.KeyspaceClientProvider; public class DefaultKeyspaceClientProvider implements KeyspaceClientProvider { private static final Logger LOG = LoggerFactory.getLogger(DefaultKeyspaceClientProvider.class); private static final String DISCOVERY_TYPE_FORMAT = "com.netflix.paas.schema.%s.discovery"; private static final String CLUSTER_NAME_FORMAT = "com.netflix.paas.schema.%s.cluster"; private static final String KEYSPACE_NAME__FORMAT = "com.netflix.paas.schema.%s.keyspace"; ImmutableMap<String, Object> defaultKsOptions = ImmutableMap.<String, Object>builder() .put("strategy_options", ImmutableMap.<String, Object>builder() .put("replication_factor", "1") .build()) .put("strategy_class", "SimpleStrategy") .build(); public static class KeyspaceContextHolder { private AstyanaxContext<Keyspace> context; private AtomicLong refCount = new AtomicLong(0); public KeyspaceContextHolder(AstyanaxContext<Keyspace> context) { this.context = context; } public Keyspace getKeyspace() { return context.getClient(); } public void start() { context.start(); } public void shutdown() { context.shutdown(); } public long addRef() { return refCount.incrementAndGet(); } public long releaseRef() { return refCount.decrementAndGet(); } } private final Map<String, KeyspaceContextHolder> contextMap = Maps.newHashMap(); private final AstyanaxConfigurationProvider configurationProvider; private final AstyanaxConnectionPoolConfigurationProvider cpProvider; private final AstyanaxConnectionPoolMonitorProvider monitorProvider; private final Map<String, HostSupplierProvider> hostSupplierProviders; private final AbstractConfiguration configuration; @Inject public DefaultKeyspaceClientProvider( AbstractConfiguration configuration, Map<String, HostSupplierProvider> hostSupplierProviders, AstyanaxConfigurationProvider configurationProvider, AstyanaxConnectionPoolConfigurationProvider cpProvider, AstyanaxConnectionPoolMonitorProvider monitorProvider) { this.configurationProvider = configurationProvider; this.cpProvider = cpProvider; this.monitorProvider = monitorProvider; this.hostSupplierProviders = hostSupplierProviders; this.configuration = configuration; } @Override public synchronized Keyspace acquireKeyspace(String schemaName) { schemaName = schemaName.toLowerCase(); Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'"); KeyspaceContextHolder holder = contextMap.get(schemaName); if (holder == null) { LOG.info("Creating schema for '{}'", new Object[]{schemaName}); String clusterName = configuration.getString(String.format(CLUSTER_NAME_FORMAT, schemaName)); String keyspaceName = configuration.getString(String.format(KEYSPACE_NAME__FORMAT, schemaName)); String discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, schemaName)); if (clusterName==null || clusterName.equals("")) clusterName = configuration.getString(String.format(CLUSTER_NAME_FORMAT, "configuration")); if (keyspaceName == null || keyspaceName.equals("")) keyspaceName = schemaName; if (discoveryType==null || discoveryType.equals("")) discoveryType = configuration.getString(String.format(DISCOVERY_TYPE_FORMAT, "configuration")); Preconditions.checkNotNull(clusterName, "Missing cluster name for schema " + schemaName + " " + String.format(CLUSTER_NAME_FORMAT,schemaName)); Preconditions.checkNotNull(keyspaceName, "Missing cluster name for schema " + schemaName + " " + String.format(KEYSPACE_NAME__FORMAT,schemaName)); Preconditions.checkNotNull(discoveryType, "Missing cluster name for schema " + schemaName + " " + String.format(DISCOVERY_TYPE_FORMAT,schemaName)); HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(discoveryType); Preconditions.checkNotNull(hostSupplierProvider, String.format("Unknown host supplier provider '%s' for schema '%s'", discoveryType, schemaName)); AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder() .forCluster(clusterName) .forKeyspace(keyspaceName) .withAstyanaxConfiguration(configurationProvider.get(schemaName)) .withConnectionPoolConfiguration(cpProvider.get(schemaName)) .withConnectionPoolMonitor(monitorProvider.get(schemaName)) .withHostSupplier(hostSupplierProvider.getSupplier(clusterName)) .buildKeyspace(ThriftFamilyFactory.getInstance()); context.start(); try { context.getClient().createKeyspace(defaultKsOptions); } catch (ConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); } holder = new KeyspaceContextHolder(context); contextMap.put(schemaName, holder); holder.start(); } holder.addRef(); return holder.getKeyspace(); } @Override public synchronized void releaseKeyspace(String schemaName) { KeyspaceContextHolder holder = contextMap.get(schemaName); if (holder.releaseRef() == 0) { contextMap.remove(schemaName); holder.shutdown(); } } @Override public Keyspace acquireKeyspace(KeyspaceKey key) { String schemaName = key.getSchemaName().toLowerCase(); Preconditions.checkNotNull(schemaName, "Invalid schema name 'null'"); KeyspaceContextHolder holder = contextMap.get(schemaName); if (holder == null) { Preconditions.checkNotNull(key.getClusterName(), "Missing cluster name for schema " + schemaName); Preconditions.checkNotNull(key.getKeyspaceName(), "Missing cluster name for schema " + schemaName); Preconditions.checkNotNull(key.getDiscoveryType(), "Missing cluster name for schema " + schemaName); HostSupplierProvider hostSupplierProvider = hostSupplierProviders.get(key.getDiscoveryType()); Preconditions.checkNotNull(hostSupplierProvider, "Unknown host supplier provider " + key.getDiscoveryType()); AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder() .forCluster(key.getClusterName()) .forKeyspace(key.getKeyspaceName()) .withAstyanaxConfiguration(configurationProvider.get(schemaName)) .withConnectionPoolConfiguration(cpProvider.get(schemaName)) .withConnectionPoolMonitor(monitorProvider.get(schemaName)) .withHostSupplier(hostSupplierProvider.getSupplier(key.getClusterName())) .buildKeyspace(ThriftFamilyFactory.getInstance()); holder = new KeyspaceContextHolder(context); contextMap.put(schemaName, holder); holder.start(); } holder.addRef(); return holder.getKeyspace(); } }
542
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/ColumnFamilyKey.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.paas.cassandra.keys; import org.apache.commons.lang.StringUtils; public class ColumnFamilyKey { private final KeyspaceKey keyspaceKey; private final String columnFamilyName; public ColumnFamilyKey(KeyspaceKey keyspaceKey, String columnFamilyName) { super(); this.keyspaceKey = keyspaceKey; this.columnFamilyName = columnFamilyName; } public ColumnFamilyKey(ClusterKey clusterKey, String keyspaceName, String columnFamilyName) { this.keyspaceKey = new KeyspaceKey(clusterKey, keyspaceName); this.columnFamilyName = columnFamilyName; } public KeyspaceKey getKeyspaceKey() { return keyspaceKey; } public String getColumnFamilyName() { return columnFamilyName; } public String getCanonicalName() { return StringUtils.join(new String[]{keyspaceKey.getCanonicalName(), columnFamilyName}, "."); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((columnFamilyName == null) ? 0 : columnFamilyName.hashCode()); result = prime * result + ((keyspaceKey == null) ? 0 : keyspaceKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ColumnFamilyKey other = (ColumnFamilyKey) obj; if (columnFamilyName == null) { if (other.columnFamilyName != null) return false; } else if (!columnFamilyName.equals(other.columnFamilyName)) return false; if (keyspaceKey == null) { if (other.keyspaceKey != null) return false; } else if (!keyspaceKey.equals(other.keyspaceKey)) return false; return true; } }
543
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/ClusterKey.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.paas.cassandra.keys; import org.apache.commons.lang.StringUtils; public class ClusterKey { private final String clusterName; private final String discoveryType; public ClusterKey(String clusterName, String discoveryType) { this.clusterName = clusterName; this.discoveryType = discoveryType; } public String getDiscoveryType() { return discoveryType; } public String getClusterName() { return this.clusterName; } public String getCanonicalName() { return StringUtils.join(new String[]{this.discoveryType, this.clusterName}, "."); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clusterName == null) ? 0 : clusterName.hashCode()); result = prime * result + ((discoveryType == null) ? 0 : discoveryType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClusterKey other = (ClusterKey) obj; if (clusterName == null) { if (other.clusterName != null) return false; } else if (!clusterName.equals(other.clusterName)) return false; if (discoveryType == null) { if (other.discoveryType != null) return false; } else if (!discoveryType.equals(other.discoveryType)) return false; return true; } }
544
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/keys/KeyspaceKey.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.paas.cassandra.keys; import org.apache.commons.lang.StringUtils; import com.google.common.base.Preconditions; /** * Global unique keyspace identifier * @author elandau * */ public class KeyspaceKey { private final ClusterKey clusterKey; private final String keyspaceName; private final String schemaName; public KeyspaceKey(String schemaName) { String parts[] = StringUtils.split(schemaName, "."); Preconditions.checkState(parts.length == 2, String.format("Schema name must have format <cluster>.<keyspace> ('%s')", schemaName)); this.clusterKey = new ClusterKey(parts[0], null); // TODO this.keyspaceName = parts[1]; this.schemaName = schemaName; } public KeyspaceKey(ClusterKey clusterKey, String keyspaceName) { this.clusterKey = clusterKey; this.keyspaceName = keyspaceName; this.schemaName = StringUtils.join(new String[]{clusterKey.getClusterName(), keyspaceName}, "."); } public ClusterKey getClusterKey() { return clusterKey; } public String getClusterName() { return clusterKey.getClusterName(); } public String getKeyspaceName() { return this.keyspaceName; } public String getDiscoveryType() { return this.clusterKey.getDiscoveryType(); } public String getSchemaName() { return this.schemaName; } public String getCanonicalName() { return StringUtils.join(new String[]{this.clusterKey.getCanonicalName(), getKeyspaceName()}, "."); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((clusterKey == null) ? 0 : clusterKey.hashCode()); result = prime * result + ((keyspaceName == null) ? 0 : keyspaceName.hashCode()); result = prime * result + ((schemaName == null) ? 0 : schemaName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; KeyspaceKey other = (KeyspaceKey) obj; if (clusterKey == null) { if (other.clusterKey != null) return false; } else if (!clusterKey.equals(other.clusterKey)) return false; if (keyspaceName == null) { if (other.keyspaceName != null) return false; } else if (!keyspaceName.equals(other.keyspaceName)) return false; if (schemaName == null) { if (other.schemaName != null) return false; } else if (!schemaName.equals(other.schemaName)) return false; return true; } }
545
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/service/ClusterMetaService.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.paas.cassandra.service; import com.google.common.eventbus.Subscribe; import com.netflix.paas.cassandra.events.ClusterUpdateEvent; import com.netflix.paas.cassandra.events.ColumnFamilyDeleteEvent; import com.netflix.paas.cassandra.events.ColumnFamilyUpdateEvent; import com.netflix.paas.cassandra.events.KeyspaceDeleteEvent; import com.netflix.paas.cassandra.events.KeyspaceUpdateEvent; public class ClusterMetaService { public ClusterMetaService() { } @Subscribe public void handleClusterUpdateEvent(ClusterUpdateEvent event) { } @Subscribe public void handleKeyspaceUpdateEvent(KeyspaceUpdateEvent event) { } @Subscribe public void handleKeyspaceDeleteEvent(KeyspaceDeleteEvent event) { } @Subscribe public void handleColumnFamilyUpdateEvent(ColumnFamilyUpdateEvent event) { } @Subscribe public void handleColumnFamilyDeleteEvent(ColumnFamilyDeleteEvent event) { } }
546
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ColumnFamilyDeleteEvent.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.paas.cassandra.events; import com.netflix.paas.cassandra.keys.ColumnFamilyKey; public class ColumnFamilyDeleteEvent { private final ColumnFamilyKey columnFamilyKey; public ColumnFamilyDeleteEvent(ColumnFamilyKey columnFamilyKey) { super(); this.columnFamilyKey = columnFamilyKey; } public ColumnFamilyKey getColumnFamilyKey() { return columnFamilyKey; } }
547
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/KeyspaceDeleteEvent.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.paas.cassandra.events; import com.netflix.paas.cassandra.keys.KeyspaceKey; public class KeyspaceDeleteEvent { private final KeyspaceKey keyspaceKey; public KeyspaceDeleteEvent(KeyspaceKey keyspaceKey) { super(); this.keyspaceKey = keyspaceKey; } public KeyspaceKey getKeyspaceKey() { return keyspaceKey; } }
548
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ColumnFamilyUpdateEvent.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.paas.cassandra.events; import com.netflix.paas.cassandra.keys.ColumnFamilyKey; public class ColumnFamilyUpdateEvent { private final ColumnFamilyKey columnFamilyKey; public ColumnFamilyUpdateEvent(ColumnFamilyKey columnFamilyKey) { super(); this.columnFamilyKey = columnFamilyKey; } public ColumnFamilyKey getColumnFamilyKey() { return columnFamilyKey; } }
549
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/ClusterUpdateEvent.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.paas.cassandra.events; import com.netflix.paas.cassandra.keys.ClusterKey; public class ClusterUpdateEvent { private final ClusterKey clusterKey; public ClusterUpdateEvent(ClusterKey clusterKey) { super(); this.clusterKey = clusterKey; } public ClusterKey getClusterKey() { return clusterKey; } }
550
0
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra
Create_ds/staash/staash-astyanax/src/main/java/com/netflix/paas/cassandra/events/KeyspaceUpdateEvent.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.paas.cassandra.events; import com.netflix.paas.cassandra.keys.KeyspaceKey; public class KeyspaceUpdateEvent { private final KeyspaceKey keyspaceKey; public KeyspaceUpdateEvent(KeyspaceKey keyspaceKey) { super(); this.keyspaceKey = keyspaceKey; } public KeyspaceKey getKeyspaceKey() { return keyspaceKey; } }
551
0
Create_ds/staash/staash-core/src/test/java/com/netflix
Create_ds/staash/staash-core/src/test/java/com/netflix/paas/TrieTest.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.paas; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.lang.StringUtils; import org.junit.Test; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class TrieTest { public static interface TrieNodeVisitor { void visit(TrieNode node); } public static interface TrieNode { public TrieNode getOrCreateChild(Character c); public TrieNode getChild(Character c); public Character getCharacter(); public void setIsWord(boolean isWord); public boolean isWord(); public void accept(TrieNodeVisitor visitor); } public static class HashMapTrieNode implements TrieNode { private final ConcurrentMap<Character, TrieNode> children = Maps.newConcurrentMap(); private final Character character; private volatile boolean isWord = false; public HashMapTrieNode(Character ch) { this.character = ch; } public TrieNode getChild(Character c) { return children.get(c); } public TrieNode getOrCreateChild(Character c) { TrieNode node = children.get(c); if (node == null) { TrieNode newNode = new HashMapTrieNode(c); System.out.println("Create child : " + c); node = children.putIfAbsent(c, newNode); if (node == null) return newNode; } return node; } public void setIsWord(boolean isWord) { this.isWord = isWord; } public boolean isWord() { return isWord; } @Override public Character getCharacter() { return this.character; } public void accept(TrieNodeVisitor visitor) { List<TrieNode> nodes = Lists.newArrayList(children.values()); Collections.sort(nodes, new Comparator<TrieNode>() { @Override public int compare(TrieNode arg0, TrieNode arg1) { return arg0.getCharacter().compareTo(arg1.getCharacter()); } }); for (TrieNode node : nodes) { visitor.visit(node); } } } public static class AtomicTrieNode implements TrieNode { private final AtomicReference<Map<Character, TrieNode>> children = new AtomicReference<Map<Character, TrieNode>>(); private final Character character; private volatile boolean isWord = false; public AtomicTrieNode(Character ch) { this.children.set(new HashMap<Character, TrieNode>()); this.character = ch; } public TrieNode getChild(Character c) { return children.get().get(c); } public TrieNode getOrCreateChild(Character c) { TrieNode node = children.get().get(c); if (node == null) { Map<Character, TrieNode> newChs; do { Map<Character, TrieNode> chs = children.get(); node = chs.get(c); if (node != null) { break; } newChs = Maps.newHashMap(chs); node = new AtomicTrieNode(c); newChs.put(c, node); if (children.compareAndSet(chs, newChs)) { break; } } while (true); } return node; } public void setIsWord(boolean isWord) { this.isWord = isWord; } public boolean isWord() { return isWord; } @Override public Character getCharacter() { return this.character; } public void accept(TrieNodeVisitor visitor) { List<TrieNode> nodes = Lists.newArrayList(children.get().values()); Collections.sort(nodes, new Comparator<TrieNode>() { @Override public int compare(TrieNode arg0, TrieNode arg1) { return arg0.getCharacter().compareTo(arg1.getCharacter()); } }); for (TrieNode node : nodes) { visitor.visit(node); } } } public static class Trie { private TrieNode root = new AtomicTrieNode(null); public boolean addWord(String word) { word = word.toUpperCase(); StringCharacterIterator iter = new StringCharacterIterator(word); TrieNode current = root; for (Character ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) { current = current.getOrCreateChild(ch); } current.setIsWord(true); return true; } public boolean containsWord(String word) { word = word.toUpperCase(); StringCharacterIterator iter = new StringCharacterIterator(word); TrieNode current = root; for (Character ch = iter.first(); ch != CharacterIterator.DONE; ch = iter.next()) { current = current.getChild(ch); if (current == null) return false; } return current.isWord(); } public void accept(TrieNodeVisitor visitor) { visitor.visit(root); } } public static class SimpleTriePrinter implements TrieNodeVisitor { private String prefix = ""; @Override public void visit(TrieNode node) { System.out.println(prefix + node.getCharacter()); prefix += " "; node.accept(this); prefix = StringUtils.substring(prefix, 1); } } @Test public void testTrie() { String[] common = {"the","of","and","a","to","in","is","you","that","it","he","was","for","on","are","as","with","his","they","I","at","be","this","have","from","or","one","had","by","word","but","not","what","all","were","we","when","your","can","said","there","use","an","each","which","she","do","how","their","if","will","up","other","about","out","many","then","them","these","so","some","her","would","make","like","him","into","time","has","look","two","more","write","go","see","number","no","way","could","people","my","than","first","water","been","call","who","oil","its","now","find","long","down","day","did","get","come","made","may","part"}; Trie trie = new Trie(); for (String word : common) { trie.addWord(word); } trie.accept(new SimpleTriePrinter()); } }
552
0
Create_ds/staash/staash-core/src/test/java/com/netflix
Create_ds/staash/staash-core/src/test/java/com/netflix/paas/ArchaeusPassConfigurationTest.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.paas; import java.lang.reflect.Method; import org.apache.commons.lang.time.StopWatch; import org.junit.Ignore; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.ProvidedBy; import com.google.inject.Provider; import com.netflix.config.ConfigurationManager; import com.netflix.paas.config.annotations.Configuration; import com.netflix.paas.config.annotations.DefaultValue; import com.netflix.paas.config.annotations.Dynamic; import com.netflix.paas.config.base.CglibArchaeusConfigurationFactory; import com.netflix.paas.config.base.DynamicProxyArchaeusConfigurationFactory; import com.netflix.paas.config.base.JavaAssistArchaeusConfigurationFactory; public class ArchaeusPassConfigurationTest { public class TestProxyProvider<T> implements Provider<T> { private Class<T> type; public TestProxyProvider(Class<T> type) { this.type = type; } @Override public T get() { System.out.println("TestProxyProvider " + type.getCanonicalName()); return null; } } public interface MyConfig { @Configuration(value="test.property.dynamic.string") @Dynamic @DefaultValue("DefaultA") String getDynamicString(); @Configuration(value="test.property.dynamic.int") @DefaultValue("123") @Dynamic Integer getDynamicInt(); @Configuration(value="test.property.dynamic.boolean") @DefaultValue("true") @Dynamic Boolean getDynamicBoolean(); @Configuration(value="test.property.dynamic.long") @DefaultValue("456") @Dynamic Long getDynamicLong(); @Configuration(value="test.property.dynamic.double") @DefaultValue("1.2") @Dynamic Double getDynamicDouble(); // @Configuration(value="test.property.supplier.string", defaultValue="suppliedstring", dynamic=true) // Supplier<String> getDynamicStringSupplier(); @Configuration(value="test.property.static.string") @DefaultValue("DefaultA") String getStaticString(); @Configuration(value="test.property.static.int") @DefaultValue("123") Integer getStaticInt(); @Configuration(value="test.property.static.boolean") @DefaultValue("true") Boolean getStaticBoolean(); @Configuration(value="test.property.static.long") @DefaultValue("456") Long getStaticLong(); @Configuration(value="test.property.static.double") @DefaultValue("1.2") Double getStaticDouble(); } @Test @Ignore public void test() throws Exception { MyConfig config = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class); System.out.println("----- BEFORE -----"); printContents(config); ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.string", "NewA"); ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.int", "321"); ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.boolean", "false"); ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.long", "654"); ConfigurationManager.getConfigInstance().setProperty("test.property.dynamic.double", "2.1"); ConfigurationManager.getConfigInstance().setProperty("test.property.static.string", "NewA"); ConfigurationManager.getConfigInstance().setProperty("test.property.static.int", "321"); ConfigurationManager.getConfigInstance().setProperty("test.property.static.boolean", "false"); ConfigurationManager.getConfigInstance().setProperty("test.property.static.long", "654"); ConfigurationManager.getConfigInstance().setProperty("test.property.static.double", "2.1"); System.out.println("----- AFTER -----"); printContents(config); // Supplier<String> supplier = config.getDynamicStringSupplier(); // System.out.println("Supplier value : " + supplier.get()); int count = 1000000; MyConfig configDynamicProxy = new DynamicProxyArchaeusConfigurationFactory().get(MyConfig.class); MyConfig configJavaAssixt = new JavaAssistArchaeusConfigurationFactory().get(MyConfig.class); MyConfig configCglib = new CglibArchaeusConfigurationFactory().get(MyConfig.class); for (int i = 0; i < 10; i++) { System.out.println("==== Run " + i + " ===="); timeConfig(configDynamicProxy, "Dynamic Proxy", count); timeConfig(configJavaAssixt, "Java Assist ", count); timeConfig(configCglib, "CGLIB ", count); } } @Test @Ignore public void testWithInjection() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(MyConfig.class).toProvider(new TestProxyProvider<MyConfig>(MyConfig.class)); } }); MyConfig config = injector.getInstance(MyConfig.class); } void timeConfig(MyConfig config, String name, int count) { StopWatch sw = new StopWatch(); sw.start(); for (int i = 0; i < count; i++) { for (Method method : MyConfig.class.getMethods()) { try { Object value = method.invoke(config); // System.out.println(name + " " + method.getName() + " " + value); } catch (Exception e) { e.printStackTrace(); } } } System.out.println(name + " took " + sw.getTime()); } void printContents(MyConfig config) { for (Method method : MyConfig.class.getMethods()) { try { System.out.println(method.getName() + " " + method.invoke(config)); } catch (Exception e) { e.printStackTrace(); } } } }
553
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/ByteBufferSerializer.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.paas; public class ByteBufferSerializer { }
554
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/PaasModule.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.paas; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.configuration.AbstractConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import com.netflix.config.ConfigurationManager; import com.netflix.paas.config.ArchaeusPaasConfiguration; import com.netflix.paas.config.PaasConfiguration; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.resources.DataResource; import com.netflix.paas.resources.SchemaAdminResource; import com.netflix.paas.resources.impl.JerseySchemaAdminResourceImpl; import com.netflix.paas.service.SchemaService; import com.netflix.paas.services.impl.DaoSchemaService; import com.netflix.paas.tasks.InlineTaskManager; import com.netflix.paas.tasks.TaskManager; /** * Core bindings for PAAS. Anything configurable will be loaded by different modules * @author elandau * */ public class PaasModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(PaasModule.class); private final EventBus eventBus = new EventBus("Default EventBus"); @Override protected void configure() { LOG.info("Loading PaasModule"); bind(EventBus.class).toInstance(eventBus); bindListener(Matchers.any(), new TypeListener() { public <I> void hear(TypeLiteral<I> typeLiteral, TypeEncounter<I> typeEncounter) { typeEncounter.register(new InjectionListener<I>() { public void afterInjection(I i) { eventBus.register(i); } }); } }); bind(TaskManager.class).to(InlineTaskManager.class); // Constants bind(String.class).annotatedWith(Names.named("namespace")).toInstance("com.netflix.pass."); bind(String.class).annotatedWith(Names.named("appname" )).toInstance("paas"); bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance()); // Configuration bind(PaasConfiguration.class).to(ArchaeusPaasConfiguration.class).in(Scopes.SINGLETON); // Stuff bind(ScheduledExecutorService.class).annotatedWith(Names.named("tasks")).toInstance(Executors.newScheduledThreadPool(10)); bind(DaoProvider.class).in(Scopes.SINGLETON); // Rest resources bind(DataResource.class).in(Scopes.SINGLETON); bind(SchemaAdminResource.class).to(JerseySchemaAdminResourceImpl.class).in(Scopes.SINGLETON); bind(SchemaService.class).to(DaoSchemaService.class).in(Scopes.SINGLETON); } }
555
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/ByteBufferDeserializer.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.paas; public class ByteBufferDeserializer { }
556
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/JsonSerializer.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.paas; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.module.SimpleModule; public class JsonSerializer { final static ObjectMapper mapper = new ObjectMapper(); { mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); mapper.enableDefaultTyping(); } public static <T> String toString(T entity) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); mapper.writeValue(baos, entity); baos.flush(); return baos.toString(); } public static <T> T fromString(String data, Class<T> clazz) throws Exception { return (T) mapper.readValue( new ByteArrayInputStream(data.getBytes()), clazz); } }
557
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/SchemaNames.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.paas; public enum SchemaNames { CONFIGURATION,META }
558
0
Create_ds/staash/staash-core/src/main/java/com/netflix
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/PaasBootstrap.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.paas; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.netflix.paas.dao.Dao; import com.netflix.paas.dao.DaoProvider; import com.netflix.paas.dao.DaoSchema; import com.netflix.paas.entity.PassGroupConfigEntity; import com.netflix.paas.entity.DbEntity; import com.netflix.paas.resources.DataResource; public class PaasBootstrap { private static final Logger LOG = LoggerFactory.getLogger(PaasBootstrap.class); @Inject public PaasBootstrap(DaoProvider daoProvider) throws Exception { LOG.info("Bootstrapping PAAS"); DaoSchema schemaDao = daoProvider.getSchema(SchemaNames.CONFIGURATION.name()); if (!schemaDao.isExists()) { schemaDao.createSchema(); } Dao<DbEntity> vschemaDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), DbEntity.class); if (!vschemaDao.isExists()) { vschemaDao.createTable(); } Dao<PassGroupConfigEntity> groupDao = daoProvider.getDao(SchemaNames.CONFIGURATION.name(), PassGroupConfigEntity.class); if (!groupDao.isExists()) { groupDao.createTable(); } } }
559
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/InlineTaskManager.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.paas.tasks; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Binding; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; public class InlineTaskManager implements TaskManager { private final static Logger LOG = LoggerFactory.getLogger(InlineTaskManager.class); private final Injector injector; public static class SyncListenableFuture implements ListenableFuture<Void> { private final Exception exception; public SyncListenableFuture(Exception exception) { this.exception = exception; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public Void get() throws InterruptedException, ExecutionException { if (exception != null) throw new ExecutionException("Very bad", exception); return null; } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (exception != null) throw new ExecutionException("Very bad", exception); return get(); } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public void addListener(Runnable listener, Executor executor) { } } @Inject public InlineTaskManager(Injector injector, EventBus eventBus) { this.injector = injector; LOG.info("SyncTaskManager " + this.injector); for (Entry<Key<?>, Binding<?>> key : this.injector.getBindings().entrySet()) { LOG.info("SyncTaskManager " + key.toString()); } } @Override public ListenableFuture<Void> submit(Class<?> clazz, Map<String, Object> args) { Task task; Exception exception = null; TaskContext context = new TaskContext(clazz, args); try { LOG.info(clazz.getCanonicalName()); task = (Task) injector.getInstance(clazz); task.execte(context); } catch (Exception e) { LOG.warn("Failed to execute task '{}'. '{}'", new Object[]{context.getKey(), e.getMessage(), e}); exception = e; } return new SyncListenableFuture(exception); } @Override public ListenableFuture<Void> submit(Class<?> clazz) { return submit(clazz, null); } }
560
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/TaskContext.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.paas.tasks; import java.util.Map; public class TaskContext { private final Map<String, Object> parameters; private final String className; public TaskContext(Class<?> className, Map<String, Object> arguments) { this.className = className.getCanonicalName(); this.parameters = arguments; } public Object getParamater(String key) { return this.parameters.get(key); } public String getStringParameter(String key) { return (String)getParamater(key); } public String getStringParameter(String key, String defaultValue) { Object value = getParamater(key); return (value == null) ? defaultValue : (String)value; } public Boolean getBooleanParameter(String key) { return (Boolean)getParamater(key); } public Boolean getBooleanParameter(String key, Boolean defaultValue) { Object value = getParamater(key); return (value == null) ? defaultValue : (Boolean)value; } public Integer getIntegerParameter(String key) { return (Integer)getParamater(key); } public Integer getIntegerParameter(String key, Integer defaultValue) { Object value = getParamater(key); return (value == null) ? defaultValue : (Integer)value; } public Long getLongParameter(String key) { return (Long)getParamater(key); } public Long getLongParameter(String key, Long defaultValue) { Object value = getParamater(key); return (value == null) ? defaultValue : (Long)value; } public String getClassName(String className) { return this.className; } public String getKey() { if (parameters == null || !parameters.containsKey("key")) return className; return className + "$" + parameters.get("key"); } }
561
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/TaskManager.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.paas.tasks; import java.util.Map; import com.google.common.util.concurrent.ListenableFuture; public interface TaskManager { ListenableFuture<Void> submit(Class<?> className); ListenableFuture<Void> submit(Class<?> className, Map<String, Object> args); }
562
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/tasks/Task.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.paas.tasks; public interface Task { public void execte(TaskContext context) throws Exception; }
563
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/TableTrigger.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.paas.trigger; public interface TableTrigger { void onDeleteRow(String schema, String table, String rowkey); void onUpsertRow(String schema, String table, String rowkey); }
564
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/impl/HttpTableTrigger.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.paas.trigger.impl; import com.netflix.paas.trigger.TableTrigger; public class HttpTableTrigger implements TableTrigger { @Override public void onDeleteRow(String schema, String table, String rowkey) { // TODO Auto-generated method stub } @Override public void onUpsertRow(String schema, String table, String rowkey) { // TODO Auto-generated method stub } }
565
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/trigger/impl/LoggingTableTrigger.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.paas.trigger.impl; import com.netflix.paas.trigger.TableTrigger; public class LoggingTableTrigger implements TableTrigger { @Override public void onDeleteRow(String schema, String table, String rowkey) { // TODO Auto-generated method stub } @Override public void onUpsertRow(String schema, String table, String rowkey) { // TODO Auto-generated method stub } }
566
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/NaturalNotationContextResolver.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.paas.jersey; import com.sun.jersey.api.json.JSONJAXBContext; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @Provider class NaturalNotationContextResolver implements ContextResolver<JAXBContext> { private JAXBContext context; NaturalNotationContextResolver() { try { this.context = new JSONJAXBContext(); } catch ( JAXBException e ) { throw new RuntimeException(e); } } public JAXBContext getContext(Class<?> objectType) { return context; } }
567
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/JsonMessageBodyReader.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.paas.jersey; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; @Consumes({"application/json"}) @Provider public class JsonMessageBodyReader implements MessageBodyReader<Object> { private final ObjectMapper mapper; public JsonMessageBodyReader() { mapper = new ObjectMapper(); // mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return mapper.canSerialize(type); } @Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> arg4, InputStream is) throws IOException, WebApplicationException { return mapper.readValue(is, type); } }
568
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/jersey/JsonMessageBodyWriter.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.paas.jersey; import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; /** * A MessageBodyWriter implementation that uses Jackson ObjectMapper to serialize objects to JSON. */ @Produces({"application/json"}) @Provider public class JsonMessageBodyWriter implements MessageBodyWriter<Object> { private final ObjectMapper mapper; public JsonMessageBodyWriter() { mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return mapper.canSerialize(type); } public long getSize(Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public void writeTo(Object data, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException, WebApplicationException { mapper.writeValue(out, data); out.flush(); } }
569
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/util/Pair.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.paas.util; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class Pair<L, R> { private final L left; private final R right; /** * @param left * @param right */ public Pair(L left, R right) { Validate.notNull(left); this.left = left; Validate.notNull(right); this.right = right; } /** * @return L */ public L getLeft() { return left; } /** * @return R */ public R getRight() { return right; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (other == this) return true; if (!(other instanceof Pair)) return false; Pair<?,?> that = (Pair<?,?>) other; return new EqualsBuilder(). append(this.left, that.left). append(this.right, that.left). isEquals(); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return new HashCodeBuilder(). append(this.left). append(this.right). toHashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("). append(this.left). append(","). append(this.right). append(")"); return sb.toString(); } }
570
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ConfigurationFactory.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.paas.config; import org.apache.commons.configuration.AbstractConfiguration; import com.netflix.config.DynamicPropertyFactory; /** * Interface for creating a proxied Configuration of an interface which * uses the Configuration annotation * * @author elandau */ public interface ConfigurationFactory { /** * Create an instance of the configuration interface using the default DynamicPropertyFactory and AbstractConfiguration * * @param configClass * @return * @throws Exception */ public <T> T get(Class<T> configClass) throws Exception; /** * Create an instance of the configuration interface * * @param configClass * @param propertyFactory * @param configuration * @return * @throws Exception */ public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception; }
571
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/PaasProperty.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.paas.config; public enum PaasProperty implements GenericProperty { TEST("test", "0") ; PaasProperty(String name, String defaultValue) { this.name = name; this.defaultValue = defaultValue; } private final String name; private final String defaultValue; @Override public String getName() { return this.name; } @Override public String getDefault() { return defaultValue; } }
572
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ArchaeusPaasConfiguration.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.paas.config; import java.io.IOException; import java.util.concurrent.ConcurrentMap; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.name.Named; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.DynamicStringProperty; import com.netflix.config.PropertyWrapper; public class ArchaeusPaasConfiguration implements PaasConfiguration { private static final Logger LOG = LoggerFactory.getLogger(ArchaeusPaasConfiguration.class); private static final DynamicStringProperty PAAS_PROPS_FILE = DynamicPropertyFactory.getInstance().getStringProperty("paas.client.props", "paas"); private final String namespace; private static ConcurrentMap<String, PropertyWrapper<?>> parameters; @Inject public ArchaeusPaasConfiguration(@Named("namespace") String namespace) { LOG.info("Created"); this.namespace = namespace; } @PostConstruct public void initialize() { LOG.info("Initializing"); String filename = PAAS_PROPS_FILE.get(); try { ConfigurationManager.loadCascadedPropertiesFromResources(filename); } catch (IOException e) { LOG.warn( "Cannot find the properties specified : {}. This may be okay if there are other environment specific properties or the configuration is installed with a different mechanism.", filename); } } @Override public Integer getInteger(GenericProperty name) { PropertyWrapper<Integer> prop = (PropertyWrapper<Integer>)parameters.get(name.getName()); if (prop == null) { PropertyWrapper<Integer> newProp = DynamicPropertyFactory.getInstance().getIntProperty(namespace + name, Integer.parseInt(name.getDefault())); prop = (PropertyWrapper<Integer>) parameters.putIfAbsent(name.getName(), newProp); if (prop == null) prop = newProp; } return prop.getValue(); } @Override public String getString(GenericProperty name) { PropertyWrapper<String> prop = (PropertyWrapper<String>)parameters.get(name.getName()); if (prop == null) { PropertyWrapper<String> newProp = DynamicPropertyFactory.getInstance().getStringProperty(namespace + name, name.getDefault()); prop = (PropertyWrapper<String>) parameters.putIfAbsent(name.getName(), newProp); if (prop == null) prop = newProp; } return prop.getValue(); } @Override public Boolean getBoolean(GenericProperty name) { PropertyWrapper<Boolean> prop = (PropertyWrapper<Boolean>)parameters.get(name.getName()); if (prop == null) { PropertyWrapper<Boolean> newProp = DynamicPropertyFactory.getInstance().getBooleanProperty(namespace + name, Boolean.parseBoolean(name.getDefault())); prop = (PropertyWrapper<Boolean>) parameters.putIfAbsent(name.getName(), newProp); if (prop == null) prop = newProp; } return prop.getValue(); } @Override public Long getLong(GenericProperty name) { PropertyWrapper<Long> prop = (PropertyWrapper<Long>)parameters.get(name.getName()); if (prop == null) { PropertyWrapper<Long> newProp = DynamicPropertyFactory.getInstance().getLongProperty(namespace + name, Long.parseLong(name.getDefault())); prop = (PropertyWrapper<Long>) parameters.putIfAbsent(name.getName(), newProp); if (prop == null) prop = newProp; } return prop.getValue(); } @Override public Double getDouble(GenericProperty name) { PropertyWrapper<Double> prop = (PropertyWrapper<Double>)parameters.get(name.getName()); if (prop == null) { PropertyWrapper<Double> newProp = DynamicPropertyFactory.getInstance().getDoubleProperty(namespace + name, Double.parseDouble(name.getDefault())); prop = (PropertyWrapper<Double>) parameters.putIfAbsent(name.getName(), newProp); if (prop == null) prop = newProp; } return prop.getValue(); } }
573
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/GenericProperty.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.paas.config; public interface GenericProperty { String getName(); String getDefault(); }
574
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/PaasConfiguration.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.paas.config; public interface PaasConfiguration { public Integer getInteger(GenericProperty name); public String getString(GenericProperty name); public Boolean getBoolean(GenericProperty name); public Double getDouble(GenericProperty name); public Long getLong(GenericProperty name); }
575
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/ConfigurationProxyFactory.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.paas.config; public interface ConfigurationProxyFactory { }
576
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/ProxyConfig.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.paas.config.annotations; 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.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ProxyConfig { }
577
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/Configuration.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.paas.config.annotations; 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.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Configuration { String value() default ""; String documentation() default ""; }
578
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/Dynamic.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.paas.config.annotations; 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.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Dynamic { }
579
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/annotations/DefaultValue.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.paas.config.annotations; 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.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface DefaultValue { String value(); }
580
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/DynamicProxyArchaeusConfigurationFactory.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.paas.config.base; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import net.sf.cglib.proxy.Enhancer; import org.apache.commons.configuration.AbstractConfiguration; import com.google.common.base.Supplier; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.paas.config.ConfigurationFactory; public class DynamicProxyArchaeusConfigurationFactory implements ConfigurationFactory { @Override public <T> T get(Class<T> configClass) throws Exception { return get(configClass, DynamicPropertyFactory.getInstance(), ConfigurationManager.getConfigInstance()); } @SuppressWarnings({ "unchecked", "static-access" }) public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration); if (configClass.isInterface()) { Class<?> proxyClass = Proxy.getProxyClass( configClass.getClassLoader(), new Class[] { configClass }); return (T) proxyClass .getConstructor(new Class[] { InvocationHandler.class }) .newInstance(new Object[] { new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); return supplier.get(); } }}); } else { final Enhancer enhancer = new Enhancer(); final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } }); ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration); return (T)obj; } } }
581
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/ProxyConfigProvider.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.paas.config.base; import com.google.inject.Provider; public class ProxyConfigProvider implements Provider<Object> { @Override public Object get() { System.out.println("ProxyConfigProvider"); return null; } }
582
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/CglibArchaeusConfigurationFactory.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.paas.config.base; import java.lang.reflect.Method; import java.util.Map; import org.apache.commons.configuration.AbstractConfiguration; import com.google.common.base.Supplier; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.paas.config.ConfigurationFactory; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.InvocationHandler; public class CglibArchaeusConfigurationFactory implements ConfigurationFactory { @Override public <T> T get(Class<T> configClass) throws Exception { return get(configClass, DynamicPropertyFactory.getInstance(), ConfigurationManager.getConfigInstance()); } @SuppressWarnings({ "unchecked", "static-access" }) public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration); if (configClass.isInterface()) { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(configClass); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); return supplier.get(); } }); return (T) enhancer.create(); } else { final Enhancer enhancer = new Enhancer(); final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } }); ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration); return (T)obj; } } }
583
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/ConfigurationProxyUtils.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.paas.config.base; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Maps; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.PropertyWrapper; import com.netflix.governator.annotations.Configuration; import com.netflix.paas.config.annotations.DefaultValue; import com.netflix.paas.config.annotations.Dynamic; import java.lang.reflect.Field; import org.apache.commons.configuration.AbstractConfiguration; /** * Utility class used by ConfigurationProxyFactory implementations to proxy methods of a * configuration interface using information from the Configuration annotation * * @author elandau */ public class ConfigurationProxyUtils { public static class PropertyWrapperSupplier<T> implements Supplier<T> { private final PropertyWrapper<T> wrapper; public PropertyWrapperSupplier(PropertyWrapper<T> wrapper) { this.wrapper = wrapper; } @Override public T get() { return this.wrapper.getValue(); } } static Supplier<?> getDynamicSupplier(Class<?> type, String key, String defaultValue, DynamicPropertyFactory propertyFactory) { if (type.isAssignableFrom(String.class)) { return new PropertyWrapperSupplier<String>( propertyFactory.getStringProperty( key, defaultValue)); } else if (type.isAssignableFrom(Integer.class)) { return new PropertyWrapperSupplier<Integer>( propertyFactory.getIntProperty( key, defaultValue == null ? 0 : Integer.parseInt(defaultValue))); } else if (type.isAssignableFrom(Double.class)) { return new PropertyWrapperSupplier<Double>( propertyFactory.getDoubleProperty( key, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue))); } else if (type.isAssignableFrom(Long.class)) { return new PropertyWrapperSupplier<Long>( propertyFactory.getLongProperty( key, defaultValue == null ? 0L : Long.parseLong(defaultValue))); } else if (type.isAssignableFrom(Boolean.class)) { return new PropertyWrapperSupplier<Boolean>( propertyFactory.getBooleanProperty( key, defaultValue == null ? false : Boolean.parseBoolean(defaultValue))); } throw new RuntimeException("Unsupported value type " + type.getCanonicalName()); } static Supplier<?> getStaticSupplier(Class<?> type, String key, String defaultValue, AbstractConfiguration configuration) { if (type.isAssignableFrom(String.class)) { return Suppliers.ofInstance( configuration.getString( key, defaultValue)); } else if (type.isAssignableFrom(Integer.class)) { return Suppliers.ofInstance( configuration.getInteger( key, defaultValue == null ? 0 : Integer.parseInt(defaultValue))); } else if (type.isAssignableFrom(Double.class)) { return Suppliers.ofInstance( configuration.getDouble( key, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue))); } else if (type.isAssignableFrom(Long.class)) { return Suppliers.ofInstance( configuration.getLong( key, defaultValue == null ? 0L : Long.parseLong(defaultValue))); } else if (type.isAssignableFrom(Boolean.class)) { return Suppliers.ofInstance( configuration.getBoolean( key, defaultValue == null ? false : Boolean.parseBoolean(defaultValue))); } throw new RuntimeException("Unsupported value type " + type.getCanonicalName()); } static String getPropertyName(Method method, Configuration c) { String name = c.value(); if (name.isEmpty()) { name = method.getName(); name = StringUtils.removeStart(name, "is"); name = StringUtils.removeStart(name, "get"); name = name.toLowerCase(); } return name; } static String getPropertyName(Field field, Configuration c) { String name = c.value(); if (name.isEmpty()) { return field.getName(); } return name; } static <T> Map<String, Supplier<?>> getMethodSuppliers(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) { final Map<String, Supplier<?>> properties = Maps.newHashMap(); for (Method method : configClass.getMethods()) { Configuration c = method.getAnnotation(Configuration.class); if (c == null) continue; String defaultValue = null; DefaultValue dv = method.getAnnotation(DefaultValue.class); if (dv != null) defaultValue = dv.value(); String name = getPropertyName(method, c); if (method.getReturnType().isAssignableFrom(Supplier.class)) { Type returnType = method.getGenericReturnType(); if(returnType instanceof ParameterizedType){ ParameterizedType type = (ParameterizedType) returnType; Class<?> actualType = (Class<?>)type.getActualTypeArguments()[0]; properties.put(method.getName(), method.getAnnotation(Dynamic.class) != null ? Suppliers.ofInstance(getDynamicSupplier(actualType, name, defaultValue, propertyFactory)) : Suppliers.ofInstance(getStaticSupplier(actualType, name, defaultValue, configuration))); } else { throw new RuntimeException("We'll get to this later"); } } else { properties.put(method.getName(), method.getAnnotation(Dynamic.class) != null ? getDynamicSupplier(method.getReturnType(), name, defaultValue, propertyFactory) : getStaticSupplier (method.getReturnType(), name, defaultValue, configuration)); } } return properties; } static void assignFieldValues(final Object obj, Class<?> type, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { // Iterate through all fields and set initial value as well as set up dynamic properties // where necessary for (final Field field : type.getFields()) { Configuration c = field.getAnnotation(Configuration.class); if (c == null) continue; String defaultValue = field.get(obj).toString(); String name = ConfigurationProxyUtils.getPropertyName(field, c); Supplier<?> supplier = ConfigurationProxyUtils.getStaticSupplier(field.getType(), name, defaultValue, configuration); field.set(obj, supplier.get()); if (field.getAnnotation(Dynamic.class) != null) { final PropertyWrapper<?> property; if (field.getType().isAssignableFrom(String.class)) { property = propertyFactory.getStringProperty( name, defaultValue); } else if (field.getType().isAssignableFrom(Integer.class)) { property = propertyFactory.getIntProperty( name, defaultValue == null ? 0 : Integer.parseInt(defaultValue)); } else if (field.getType().isAssignableFrom(Double.class)) { property = propertyFactory.getDoubleProperty( name, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue)); } else if (field.getType().isAssignableFrom(Long.class)) { property = propertyFactory.getLongProperty( name, defaultValue == null ? 0L : Long.parseLong(defaultValue)); } else if (field.getType().isAssignableFrom(Boolean.class)) { property = propertyFactory.getBooleanProperty( name, defaultValue == null ? false : Boolean.parseBoolean(defaultValue)); } else { throw new RuntimeException("Unsupported type " + field.getType()); } property.addCallback(new Runnable() { @Override public void run() { try { field.set(obj, property.getValue()); } catch (Exception e) { e.printStackTrace(); } } }); } } } }
584
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/config/base/JavaAssistArchaeusConfigurationFactory.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.paas.config.base; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import net.sf.cglib.proxy.Enhancer; import org.apache.commons.configuration.AbstractConfiguration; import com.google.common.base.Supplier; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.paas.config.ConfigurationFactory; public class JavaAssistArchaeusConfigurationFactory implements ConfigurationFactory { @Override public <T> T get(Class<T> configClass) throws Exception { return get(configClass, DynamicPropertyFactory.getInstance(), ConfigurationManager.getConfigInstance()); } @SuppressWarnings({ "unchecked", "static-access" }) public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory, AbstractConfiguration configuration) throws Exception { final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass, propertyFactory, configuration); if (configClass.isInterface()) { Class<?> proxyClass = Proxy.getProxyClass( configClass.getClassLoader(), new Class[] { configClass }); return (T) proxyClass .getConstructor(new Class[] { InvocationHandler.class }) .newInstance(new Object[] { new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } }}); } else { final Enhancer enhancer = new Enhancer(); final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Supplier<?> supplier = (Supplier<?>)methods.get(method.getName()); if (supplier == null) { return method.invoke(proxy, args); } return supplier.get(); } }); ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration); return (T)obj; } } }
585
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TableEntity.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.paas.entity; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import com.google.common.collect.Maps; /** * Definition for a table in the system. This definition provides this system will * all the information for connecting to the target persistence implementation * * @author elandau * */ @Entity public class TableEntity { public static class Builder { private TableEntity entity = new TableEntity(); public Builder withStorageType(String type) { entity.storageType = type; return this; } public Builder withTableName(String tableName) { entity.tableName = tableName; return this; } public Builder withSchemaName(String schema) { entity.schema = schema; return this; } public Builder withOptions(Map<String, String> options) { entity.options = options; return this; } public Builder withOption(String key, String value) { if (entity.options == null) { entity.options = Maps.newHashMap(); } entity.options.put(key, value); return this; } public TableEntity build() { return entity; } } public static Builder builder() { return new Builder(); } /** * Unique table name within the schema */ @Id private String tableName; /** * Type of storage for this table. (ex. cassandra) */ @Column(name="type") private String storageType; /** * Parent schema */ @Column(name="schema") private String schema; /** * Additional configuration options for the table. These parameters are normally * specific to the underlying persistence technology */ @Column(name="options") private Map<String, String> options; public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getStorageType() { return storageType; } public void setStorageType(String storageType) { this.storageType = storageType; } public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } public String getOption(String option) { return getOption(option, null); } public String getOption(String key, String defaultValue) { if (this.options == null) return defaultValue; String value = options.get(key); if (value == null) return defaultValue; return value; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } @Override public String toString() { return "VirtualTableEntity [tableName=" + tableName + ", storageType=" + storageType + ", schema=" + schema + ", options=" + options + "]"; } }
586
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/RackEntity.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.paas.entity; public class RackEntity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
587
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/DbEntity.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.paas.entity; import java.util.Map; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Transient; import com.google.common.collect.Maps; /** * Definition of a global schema in the system. A schema may contain * tables that are implemented using different technologies. * * @author elandau */ @Entity(name="db") public class DbEntity { public static class Builder { private DbEntity entity = new DbEntity(); public Builder withName(String name) { entity.name = name; return this; } public Builder addTable(TableEntity table) throws Exception { if (null == entity.getTables()) { entity.tables = Maps.newHashMap(); } entity.tables.put(table.getTableName(), table); return this; } public Builder withOptions(Map<String, String> options) { entity.options = options; return this; } public Builder addOption(String name, String value) { if (null == entity.getOptions()) { entity.options = Maps.newHashMap(); } entity.options.put(name, value); return this; } public DbEntity build() { return entity; } } public static Builder builder() { return new Builder(); } @Id private String name; @Column private Set<String> tableNames; @Column private Map<String, String> options; @Transient private Map<String, TableEntity> tables; public Map<String, String> getOptions() { return options; } public void setOptions(Map<String, String> options) { this.options = options; } @PrePersist private void prePersist() { } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setTables(Map<String, TableEntity> tables) { this.tables = tables; } public Map<String, TableEntity> getTables() { return tables; } public void setTableNames(Set<String> tableNames) { this.tableNames = tableNames; } public Set<String> getTableNames() { return tableNames; } public boolean hasTables() { return this.tables != null && !this.tables.isEmpty(); } @Override public String toString() { return "SchemaEntity [name=" + name + ", tables=" + tables + "]"; } }
588
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/PassGroupConfigEntity.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.paas.entity; import java.util.Collection; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import com.google.common.collect.Sets; @Entity public class PassGroupConfigEntity { public static class Builder { private PassGroupConfigEntity entity = new PassGroupConfigEntity(); public Builder withName(String name) { entity.deploymentName = name; return this; } public Builder withSchemas(Collection<String> names) { if (entity.schemas == null) { entity.schemas = Sets.newHashSet(); } entity.schemas.addAll(names); return this; } public Builder addSchema(String vschemaName) { if (entity.schemas == null) { entity.schemas = Sets.newHashSet(); } entity.schemas.add(vschemaName); return this; } public PassGroupConfigEntity build() { return entity; } } public static Builder builder() { return new Builder(); } @Id private String deploymentName; @Column private Set<String> schemas; public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } public Set<String> getSchemas() { return schemas; } public void setSchemas(Set<String> schemas) { this.schemas = schemas; } @Override public String toString() { return "PassGroupConfigEntity [deploymentName=" + deploymentName + ", schemas=" + schemas + "]"; } }
589
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TableTriggerEntity.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.paas.entity; public class TableTriggerEntity { }
590
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnMetadataEntity.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.paas.entity; import java.util.List; public class ColumnMetadataEntity { private String type; private String name; private List<ColumnValidatorEntity> validator; private List<ColumnIndexEntity> indexes; }
591
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnValidatorEntity.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.paas.entity; public class ColumnValidatorEntity { }
592
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/EntityIterable.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.paas.entity; public interface EntityIterable<T> extends Iterable<T> { }
593
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/SchemaTrigger.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.paas.entity; public class SchemaTrigger { }
594
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/DatacenterEntity.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.paas.entity; public class DatacenterEntity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
595
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ClusterEntity.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.paas.entity; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import com.google.common.collect.Sets; @Entity(name="cluster") public class ClusterEntity { public static class Builder { private ClusterEntity entity = new ClusterEntity(); public Builder withName(String name) { entity.name = name; return this; } public Builder withNodes(Set<String> nodes) { entity.nodes = nodes; return this; } public Builder addNode(String node) { if (entity.nodes == null) entity.nodes = Sets.newHashSet(); entity.nodes.add(node); return this; } public ClusterEntity build() { return entity; } } public static Builder builder() { return new Builder(); } @Id @Column private String name; @Column private Set<String> nodes; public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<String> getNodes() { return nodes; } public void setNodes(Set<String> nodes) { this.nodes = nodes; } }
596
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/ColumnIndexEntity.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.paas.entity; public class ColumnIndexEntity { }
597
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/entity/TriggerEntity.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.paas.entity; public class TriggerEntity { }
598
0
Create_ds/staash/staash-core/src/main/java/com/netflix/paas
Create_ds/staash/staash-core/src/main/java/com/netflix/paas/resources/TableDataResource.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.paas.resources; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.netflix.paas.data.QueryResult; import com.netflix.paas.data.RowData; import com.netflix.paas.exceptions.NotFoundException; import com.netflix.paas.exceptions.PaasException; import com.netflix.paas.json.JsonObject; /** * Interface for access to a table. Concrete implementation may implement a table * on top of any persistence technology. * * @author elandau * */ //@Path("/v1/data") public interface TableDataResource { // Table level API @GET public QueryResult listRows( String cursor, Integer rowLimit, Integer columnLimit ) throws PaasException; @DELETE public void truncateRows( ) throws PaasException; // Row level API @GET @Path("{key}") public QueryResult readRow( @PathParam("key") String key, @QueryParam("count") @DefaultValue("0") Integer columnCount, @QueryParam("start") @DefaultValue("") String startColumn, @QueryParam("end") @DefaultValue("") String endColumn, @QueryParam("reversed") @DefaultValue("false") Boolean reversed ) throws PaasException; @DELETE @Path("{key}") public void deleteRow( @PathParam("key") String key ) throws PaasException; @POST @Path("{db}/{table}") @Consumes(MediaType.TEXT_PLAIN) public void updateRow( @PathParam("db") String db, @PathParam("table") String table, JsonObject rowData ) throws PaasException ; // Row level API @GET @Path("{key}/{column}") public QueryResult readColumn( @PathParam("key") String key, @PathParam("column") String column ) throws PaasException, NotFoundException; @POST @Path("{key}/{column}") public void updateColumn( @PathParam("key") String key, @PathParam("column") String column, String value ) throws PaasException, NotFoundException; @DELETE @Path("{key}/{column}") public void deleteColumn( @PathParam("key") String key, @PathParam("column") String column ) throws PaasException; // TODO: Batch operations // TODO: Pagination // TODO: Index search }
599