index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/MockCompositeTypeTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.annotations.Component; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.serializers.AnnotatedCompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class MockCompositeTypeTests extends KeyspaceTests { private static final Logger LOG = Logger.getLogger(MockCompositeTypeTests.class); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_COMPOSITE, ImmutableMap.<String, Object>builder() .put("comparator_type", "CompositeType(AsciiType, IntegerType, IntegerType, BytesType, UTF8Type)") .build()); CF_COMPOSITE.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_COMPOSITE); } private static AnnotatedCompositeSerializer<MockCompositeType> M_SERIALIZER = new AnnotatedCompositeSerializer<MockCompositeType>(MockCompositeType.class); private static ColumnFamily<String, MockCompositeType> CF_COMPOSITE = ColumnFamily.newColumnFamily("mockcompositetype", StringSerializer.get(), M_SERIALIZER); @Test public void testComposite() throws Exception { String rowKey = "Composite1"; boolean bool = false; MutationBatch m = keyspace.prepareMutationBatch(); ColumnListMutation<MockCompositeType> mRow = m.withRow(CF_COMPOSITE, rowKey); int columnCount = 0; for (char part1 = 'a'; part1 <= 'b'; part1++) { for (int part2 = 0; part2 < 10; part2++) { for (int part3 = 10; part3 < 11; part3++) { bool = !bool; columnCount++; mRow.putEmptyColumn( new MockCompositeType(Character.toString(part1), part2, part3, bool, "UTF"), null); } } } m.execute(); LOG.info("Created " + columnCount + " columns"); OperationResult<ColumnList<MockCompositeType>> result; result = keyspace.prepareQuery(CF_COMPOSITE).getKey(rowKey).execute(); Assert.assertEquals(columnCount, result.getResult().size()); for (Column<MockCompositeType> col : result.getResult()) { LOG.info("COLUMN: " + col.getName().toString()); } Column<MockCompositeType> column = keyspace.prepareQuery(CF_COMPOSITE).getKey(rowKey) .getColumn(new MockCompositeType("a", 0, 10, true, "UTF")) .execute().getResult(); LOG.info("Got single column: " + column.getName().toString()); Assert.assertNotNull(column); Assert.assertEquals("MockCompositeType[a,0,10,true,UTF]", column.getName().toString()); LOG.info("Range builder"); result = keyspace .prepareQuery(CF_COMPOSITE) .getKey(rowKey) .withColumnRange( M_SERIALIZER .buildRange() .withPrefix("a") .greaterThanEquals(1) .lessThanEquals(1) .build()).execute(); Assert.assertTrue(1 == result.getResult().size()); for (Column<MockCompositeType> col : result.getResult()) { LOG.info("COLUMN: " + col.getName().toString()); Assert.assertEquals("MockCompositeType[a,1,10,false,UTF]", col.getName().toString()); } } public static class MockCompositeType { @Component private String stringPart; @Component private Integer intPart; @Component private Integer intPart2; @Component private boolean boolPart; @Component private String utf8StringPart; public MockCompositeType() { } public MockCompositeType(String part1, Integer part2, Integer part3, boolean boolPart, String utf8StringPart) { this.stringPart = part1; this.intPart = part2; this.intPart2 = part3; this.boolPart = boolPart; this.utf8StringPart = utf8StringPart; } public MockCompositeType setStringPart(String part) { this.stringPart = part; return this; } public String getStringPart() { return this.stringPart; } public MockCompositeType setIntPart1(int value) { this.intPart = value; return this; } public int getIntPart1() { return this.intPart; } public MockCompositeType setIntPart2(int value) { this.intPart2 = value; return this; } public int getIntPart2() { return this.intPart2; } public MockCompositeType setBoolPart(boolean boolPart) { this.boolPart = boolPart; return this; } public boolean getBoolPart() { return this.boolPart; } public MockCompositeType setUtf8StringPart(String str) { this.utf8StringPart = str; return this; } public String getUtf8StringPart() { return this.utf8StringPart; } public String toString() { return new StringBuilder().append("MockCompositeType[") .append(stringPart).append(',').append(intPart).append(',') .append(intPart2).append(',').append(boolPart).append(',') .append(utf8StringPart).append(']').toString(); } } }
7,600
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/AllRowsQueryTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import java.util.concurrent.atomic.AtomicLong; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.ExceptionCallback; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.RowCallback; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.model.Rows; import com.netflix.astyanax.serializers.StringSerializer; public class AllRowsQueryTest extends KeyspaceTests { private static final Logger LOG = LoggerFactory.getLogger(AllRowsQueryTest.class); public static ColumnFamily<String, String> CF_ALL_ROWS = ColumnFamily .newColumnFamily( "allrows", StringSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_ALL_ROWS, null); CF_ALL_ROWS.describe(keyspace); /** POPULATE ROWS FOR TESTS */ MutationBatch m = keyspace.prepareMutationBatch(); for (char keyName = 'A'; keyName <= 'Z'; keyName++) { String rowKey = Character.toString(keyName); ColumnListMutation<String> cfmStandard = m.withRow(CF_ALL_ROWS, rowKey); for (char cName = 'a'; cName <= 'z'; cName++) { cfmStandard.putColumn(Character.toString(cName), (int) (cName - 'a') + 1, null); } m.withCaching(true); m.execute(); m.discardMutations(); } } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_ALL_ROWS); } @Test public void getAllWithCallback() throws Exception { final AtomicLong counter = new AtomicLong(); keyspace.prepareQuery(CF_ALL_ROWS).getAllRows() .setRowLimit(30) .setRepeatLastToken(false) .setConcurrencyLevel(2) //.withColumnRange(new RangeBuilder().setLimit(2).build()) .executeWithCallback(new RowCallback<String, String>() { @Override public void success(Rows<String, String> rows) { for (Row<String, String> row : rows) { LOG.info("ROW: " + row.getKey() + " " + row.getColumns().size()); counter.incrementAndGet(); } } @Override public boolean failure(ConnectionException e) { LOG.error(e.getMessage(), e); return false; } }); LOG.info("Read " + counter.get() + " keys"); Assert.assertEquals(26, counter.get()); } @Test public void getAll() throws Exception { AtomicLong counter = new AtomicLong(0); OperationResult<Rows<String, String>> rows = keyspace .prepareQuery(CF_ALL_ROWS).getAllRows().setConcurrencyLevel(2).setRowLimit(30) //.withColumnRange(new RangeBuilder().setLimit(0).build()) .setExceptionCallback(new ExceptionCallback() { @Override public boolean onException(ConnectionException e) { Assert.fail(e.getMessage()); return true; } }).execute(); for (Row<String, String> row : rows.getResult()) { counter.incrementAndGet(); LOG.info("ROW: " + row.getKey() + " " + row.getColumns().size()); } LOG.info("Read " + counter.get() + " keys"); Assert.assertEquals(26, counter.get()); } }
7,601
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/SingleRowQueryTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.UUID; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.cql.test.utils.ReadTests; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.serializers.BytesArraySerializer; public class SingleRowQueryTests extends ReadTests { private int TestRowCount = 10; @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_USER_INFO, null); CF_USER_INFO.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_USER_INFO); } @Test public void runAllTests() throws Exception { /** POPULATE ROWS FOR READ TESTS */ populateRows(TestRowCount); // NOTE THAT WE ARE UING USER_INFO CF Thread.sleep(1000); boolean rowDeleted = false; /** NOW READ BACK THE COLUMNS FOR EACH ROW */ testSingleRowAllColumnsQuery(rowDeleted); testSingleRowSingleColumnQuery(rowDeleted); testSingleRowColumnSliceQueryWithCollection(rowDeleted); testSingleRowColumnSliceQueryVarArgs(rowDeleted); testSingleRowAllColumnsColumnCountQuery(rowDeleted); testSingleRowColumnSliceCollectionColumnCountQuery(rowDeleted); testSingleRowColumnSliceVarArgsColumnCountQuery(rowDeleted); /** NOW DELETE THE ROWS */ deleteRows(TestRowCount); Thread.sleep(1000); rowDeleted = true; /** NOW ISSUE THE SAME QUERY BUT VERIFY THAT THE RESULTS ARE EMPTY */ testSingleRowAllColumnsQuery(rowDeleted); testSingleRowSingleColumnQuery(rowDeleted); testSingleRowColumnSliceQueryWithCollection(rowDeleted); testSingleRowColumnSliceQueryVarArgs(rowDeleted); testSingleRowAllColumnsColumnCountQuery(rowDeleted); testSingleRowColumnSliceCollectionColumnCountQuery(rowDeleted); testSingleRowColumnSliceVarArgsColumnCountQuery(rowDeleted); } private void testSingleRowAllColumnsQuery(boolean rowDeleted) throws Exception { String[] arr = {"firstname", "lastname", "address","age","ageShort", "ageLong","percentile", "married","single", "birthdate", "bytes", "uuid", "empty"}; List<String> columnNames = new ArrayList<String>(Arrays.asList(arr)); Collections.sort(columnNames); /** NOW READ 1000 ROWS BACK */ /** * READ BY COLUMN NAME */ for (int i=0; i<TestRowCount; i++) { ColumnList<String> response = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i).execute().getResult(); if (rowDeleted) { Assert.assertTrue(response.isEmpty()); continue; } Assert.assertFalse(response.isEmpty()); List<String> columnNameList = new ArrayList<String>(response.getColumnNames()); Collections.sort(columnNameList); Assert.assertEquals(columnNames, columnNameList); Date date = OriginalDate.plusMinutes(i).toDate(); testColumnValue(response, "firstname", columnNames, "john_" + i); testColumnValue(response, "lastname", columnNames, "smith_" + i); testColumnValue(response, "address", columnNames, "john smith address " + i); testColumnValue(response, "age", columnNames, 30 + i); testColumnValue(response, "ageShort", columnNames, new Integer(30+i).shortValue()); testColumnValue(response, "ageLong", columnNames, new Integer(30+i).longValue()); testColumnValue(response, "percentile", columnNames, 30.1); testColumnValue(response, "married", columnNames, true); testColumnValue(response, "single", columnNames, false); testColumnValue(response, "birthdate", columnNames, date); testColumnValue(response, "bytes", columnNames, TestBytes); testColumnValue(response, "uuid", columnNames, TestUUID); testColumnValue(response, "empty", columnNames, null); /** TEST THE ITERATOR INTERFACE */ Iterator<Column<String>> iter = response.iterator(); Iterator<String> columnNameIter = columnNames.iterator(); while (iter.hasNext()) { Column<String> col = iter.next(); String columnName = columnNameIter.next(); Assert.assertEquals(columnName, col.getName()); } } } private void testSingleRowSingleColumnQuery(boolean rowDeleted) throws Exception { /** NOW READ 1000 ROWS BACK */ /** * READ BY COLUMN NAME */ for (int i=0; i<TestRowCount; i++) { Date date = OriginalDate.plusMinutes(i).toDate(); Column<String> column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("firstname").execute().getResult(); if (rowDeleted) { Assert.assertNull(column); continue; } else { Assert.assertTrue(column.hasValue()); } testColumnValue(column, "john_" + i); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("lastname").execute().getResult(); testColumnValue(column, "smith_" + i); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("address").execute().getResult(); testColumnValue(column, "john smith address " + i); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("age").execute().getResult(); testColumnValue(column, 30 + i); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("ageShort").execute().getResult(); testColumnValue(column, new Integer(30+i).shortValue()); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("ageLong").execute().getResult(); testColumnValue(column, new Integer(30+i).longValue()); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("percentile").execute().getResult(); testColumnValue(column, 30.1); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("married").execute().getResult(); testColumnValue(column, true); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("single").execute().getResult(); testColumnValue(column, false); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("birthdate").execute().getResult(); testColumnValue(column, date); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("bytes").execute().getResult(); testColumnValue(column, TestBytes); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("uuid").execute().getResult(); testColumnValue(column, TestUUID); column = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .getColumn("empty").execute().getResult(); testColumnValue(column, null); } } private void testSingleRowColumnSliceQueryWithCollection(boolean rowDeleted) throws Exception { /** * READ BY COLUMN SLICE COLLECTION */ for (int i=0; i<TestRowCount; i++) { Date date = OriginalDate.plusMinutes(i).toDate(); ColumnList<String> response = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i).withColumnSlice(columnNames).execute().getResult(); if (rowDeleted) { Assert.assertTrue(response.isEmpty()); continue; } else { Assert.assertFalse(response.isEmpty()); } testColumnValue(response, "firstname", columnNames, "john_" + i); testColumnValue(response, "lastname", columnNames, "smith_" + i); testColumnValue(response, "address", columnNames, "john smith address " + i); testColumnValue(response, "age", columnNames, 30 + i); testColumnValue(response, "ageShort", columnNames, new Integer(30+i).shortValue()); testColumnValue(response, "ageLong", columnNames, new Integer(30+i).longValue()); testColumnValue(response, "percentile", columnNames, 30.1); testColumnValue(response, "married", columnNames, true); testColumnValue(response, "single", columnNames, false); testColumnValue(response, "birthdate", columnNames, date); testColumnValue(response, "bytes", columnNames, TestBytes); testColumnValue(response, "uuid", columnNames, TestUUID); testColumnValue(response, "empty", columnNames, null); } } private void testSingleRowColumnSliceQueryVarArgs(boolean rowDeleted) throws Exception { /** * READ BY COLUMN SLICE COLLECTION */ for (int i=0; i<TestRowCount; i++) { Date date = OriginalDate.plusMinutes(i).toDate(); ColumnList<String> response = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .withColumnSlice("firstname", "lastname", "address","age","ageShort", "ageLong","percentile", "married","single", "birthdate", "bytes", "uuid", "empty").execute().getResult(); if (rowDeleted) { Assert.assertTrue(response.isEmpty()); continue; } else { Assert.assertFalse(response.isEmpty()); } testColumnValue(response, "firstname", columnNames, "john_" + i); testColumnValue(response, "lastname", columnNames, "smith_" + i); testColumnValue(response, "address", columnNames, "john smith address " + i); testColumnValue(response, "age", columnNames, 30 + i); testColumnValue(response, "ageShort", columnNames, new Integer(30+i).shortValue()); testColumnValue(response, "ageLong", columnNames, new Integer(30+i).longValue()); testColumnValue(response, "percentile", columnNames, 30.1); testColumnValue(response, "married", columnNames, true); testColumnValue(response, "single", columnNames, false); testColumnValue(response, "birthdate", columnNames, date); testColumnValue(response, "bytes", columnNames, TestBytes); testColumnValue(response, "uuid", columnNames, TestUUID); testColumnValue(response, "empty", columnNames, null); } } private void testSingleRowAllColumnsColumnCountQuery(boolean rowDeleted) throws Exception { int expected = rowDeleted ? 0 : columnNames.size(); for (int i=0; i<TestRowCount; i++) { int count = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i).getCount().execute().getResult().intValue(); Assert.assertEquals(expected, count); } } private void testSingleRowColumnSliceCollectionColumnCountQuery(boolean rowDeleted) throws Exception { int expected = rowDeleted ? 0 : columnNames.size(); for (int i=0; i<TestRowCount; i++) { int count = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i).withColumnSlice(columnNames).getCount().execute().getResult(); Assert.assertEquals(expected, count); } } private void testSingleRowColumnSliceVarArgsColumnCountQuery(boolean rowDeleted) throws Exception { int expected = rowDeleted ? 0 : columnNames.size(); for (int i=0; i<TestRowCount; i++) { int count = keyspace.prepareQuery(CF_USER_INFO).getRow("acct_" + i) .withColumnSlice("firstname", "lastname", "address","age","ageShort", "ageLong","percentile", "married","single", "birthdate", "bytes", "uuid", "empty") .getCount().execute().getResult(); Assert.assertEquals(expected, count); } } private <T> void testColumnValue(ColumnList<String> response, String columnName, List<String> columnNames, T value) { // by column name Column<String> column = response.getColumnByName(columnName); Assert.assertEquals(columnName, column.getName()); testColumnValue(column, value); } private <T> void testColumnValue(Column<String> column, T value) { // Check the column name // check if value exists if (value != null) { Assert.assertTrue(column.hasValue()); if (value instanceof String) { Assert.assertEquals(value, column.getStringValue()); } else if (value instanceof Integer) { Assert.assertEquals(value, column.getIntegerValue()); } else if (value instanceof Short) { Assert.assertEquals(value, column.getShortValue()); } else if (value instanceof Long) { Assert.assertEquals(value, column.getLongValue()); } else if (value instanceof Double) { Assert.assertEquals(value, column.getDoubleValue()); } else if (value instanceof Boolean) { Assert.assertEquals(value, column.getBooleanValue()); } else if (value instanceof Date) { Assert.assertEquals(value, column.getDateValue()); } else if (value instanceof byte[]) { ByteBuffer bbuf = column.getByteBufferValue(); String result = new String(BytesArraySerializer.get().fromByteBuffer(bbuf)); Assert.assertEquals(new String((byte[])value), result); } else if (value instanceof UUID) { Assert.assertEquals(value, column.getUUIDValue()); } else { Assert.fail("Value not recognized for column: " + column.getName()); } } else { // check that value does not exist Assert.assertFalse(column.hasValue()); } } }
7,602
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/ClickStreamTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.serializers.AnnotatedCompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.astyanax.test.SessionEvent; import com.netflix.astyanax.util.TimeUUIDUtils; public class ClickStreamTests extends KeyspaceTests { public static AnnotatedCompositeSerializer<SessionEvent> SE_SERIALIZER = new AnnotatedCompositeSerializer<SessionEvent>(SessionEvent.class); public static ColumnFamily<String, SessionEvent> CF_CLICK_STREAM = ColumnFamily.newColumnFamily("ClickStream", StringSerializer.get(), SE_SERIALIZER); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_CLICK_STREAM, null); CF_CLICK_STREAM.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_CLICK_STREAM); } @Test public void testClickStream() throws Exception { MutationBatch m = keyspace.prepareMutationBatch(); String userId = "UserId"; List<UUID> uuids = new ArrayList<UUID>(); for (int j = 0; j < 10; j++) { uuids.add(TimeUUIDUtils.getTimeUUID(j)); } long timeCounter = 0; for (int i = 0; i < 10; i++) { String sessionId = "Session" + i; for (int j = 0; j < 10; j++) { m.withRow(CF_CLICK_STREAM, userId).putColumn( new SessionEvent(sessionId, uuids.get(j)), Long.toString(timeCounter), null); timeCounter++; } } m.execute(); OperationResult<ColumnList<SessionEvent>> result; result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER.buildRange() .greaterThanEquals("Session3") .lessThanEquals("Session5").build()) .execute(); Assert.assertEquals(30, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER.buildRange() .greaterThanEquals("Session3") .lessThan("Session5").build()).execute(); Assert.assertEquals(20, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER.buildRange().greaterThan("Session3") .lessThanEquals("Session5").build()) .execute(); Assert.assertEquals(20, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER.buildRange().greaterThan("Session3") .lessThan("Session5").build()).execute(); Assert.assertEquals(10, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER .buildRange() .withPrefix("Session3") .greaterThanEquals(uuids.get(2)) .lessThanEquals(uuids.get(8)) .build()).execute(); Assert.assertEquals(7, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER .buildRange() .withPrefix("Session3") .greaterThanEquals( TimeUUIDUtils.getTimeUUID(2)) .lessThan( TimeUUIDUtils.getTimeUUID(8)) .build()).execute(); Assert.assertEquals(6, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER .buildRange() .withPrefix("Session3") .greaterThan( TimeUUIDUtils.getTimeUUID(2)) .lessThanEquals( TimeUUIDUtils.getTimeUUID(8)) .build()).execute(); Assert.assertEquals(6, result.getResult().size()); result = keyspace .prepareQuery(CF_CLICK_STREAM) .getKey(userId) .withColumnRange( SE_SERIALIZER .buildRange() .withPrefix("Session3") .greaterThan( TimeUUIDUtils.getTimeUUID(2)) .lessThan( TimeUUIDUtils.getTimeUUID(8)) .build()).execute(); Assert.assertEquals(5, result.getResult().size()); } }
7,603
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/CompositeKeyTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import junit.framework.Assert; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.cql.test.MockCompositeTypeTests.MockCompositeType; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.serializers.AnnotatedCompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class CompositeKeyTests extends KeyspaceTests { private static final Logger LOG = Logger.getLogger(CompositeKeyTests.class); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_COMPOSITE_KEY, ImmutableMap.<String, Object>builder() .put("key_validation_class", "BytesType") .build()); CF_COMPOSITE_KEY.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_COMPOSITE_KEY); } private static AnnotatedCompositeSerializer<MockCompositeType> M_SERIALIZER = new AnnotatedCompositeSerializer<MockCompositeType>(MockCompositeType.class); private static ColumnFamily<MockCompositeType, String> CF_COMPOSITE_KEY = ColumnFamily.newColumnFamily("compositekey", M_SERIALIZER, StringSerializer.get()); @Test public void testCompositeKey() { MockCompositeType key = new MockCompositeType("A", 1, 2, true, "B"); MutationBatch m = keyspace.prepareMutationBatch(); m.withRow(CF_COMPOSITE_KEY, key).putColumn("Test", "Value", null); try { m.execute(); } catch (ConnectionException e) { LOG.error(e.getMessage(), e); Assert.fail(); } try { ColumnList<String> row = keyspace.prepareQuery(CF_COMPOSITE_KEY) .getKey(key).execute().getResult(); Assert.assertFalse(row.isEmpty()); } catch (ConnectionException e) { LOG.error(e.getMessage(), e); Assert.fail(); } } }
7,604
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/PreparedStatementTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import java.util.Date; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.CqlPreparedStatement; import com.netflix.astyanax.cql.reads.model.CqlRangeBuilder; import com.netflix.astyanax.cql.test.utils.ReadTests; 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.Murmur3Partitioner; import com.netflix.astyanax.query.ColumnQuery; import com.netflix.astyanax.query.RowQuery; import com.netflix.astyanax.query.RowSliceQuery; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class PreparedStatementTests extends ReadTests { private static int TestRowCount = 10; private static ColumnFamily<String, String> CF_ROW_RANGE = new ColumnFamily<String, String>("rowrange", StringSerializer.get(), StringSerializer.get(), IntegerSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_USER_INFO, null); keyspace.createColumnFamily(CF_ROW_RANGE, null); CF_USER_INFO.describe(keyspace); CF_ROW_RANGE.describe(keyspace); populateRowsForUserInfo(TestRowCount); populateRowsForColumnRange(); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_USER_INFO); keyspace.dropColumnFamily(CF_ROW_RANGE); } @Test public void testSingleRowAllColumnsQuery() throws Exception { for (int i=0; i<TestRowCount; i++) { ColumnList<String> result = keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRow("acct_" + i) .execute() .getResult(); super.testAllColumnsForRow(result, i); } } @Test public void testSingleRowSingleColumnQuery() throws Exception { for (int i=0; i<TestRowCount; i++) { Column<String> result = keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRow("acct_" + i) .getColumn("address") .execute() .getResult(); Assert.assertNotNull(result); Assert.assertEquals("address", result.getName()); Assert.assertNotNull(result.getStringValue()); Assert.assertEquals("john smith address " + i, result.getStringValue()); } } @Test public void testSingleRowColumnSliceQueryWithCollection() throws Exception { for (int i=0; i<TestRowCount; i++) { ColumnList<String> result = keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRow("acct_" + i) .withColumnSlice("firstname", "lastname", "address", "age") .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(4 == result.size()); Assert.assertEquals("john_" + i, result.getColumnByName("firstname").getStringValue()); Assert.assertEquals("smith_" + i, result.getColumnByName("lastname").getStringValue()); Assert.assertEquals("john smith address " + i, result.getColumnByName("address").getStringValue()); Assert.assertTrue(30 + i == result.getColumnByName("age").getIntegerValue()); } } @Test public void testRowKeysAllColumnsQuery() throws Exception { keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRowSlice("acct_0", "acct_1", "acct_2", "acct_3") .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRowSlice("acct_4", "acct_5", "acct_6", "acct_7") .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(4 == result.size()); for (Row<String, String> row : result) { int rowNo = Integer.parseInt(row.getKey().substring("acct_".length())); Assert.assertTrue(rowNo >= 4); Assert.assertTrue(rowNo <= 7); Assert.assertTrue(13 == row.getColumns().size()); } } @Test public void testRowKeysColumnSetQuery() throws Exception { keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRowSlice("acct_0", "acct_1", "acct_2", "acct_3") .withColumnSlice("firstname", "lastname", "age") .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_USER_INFO) .withCaching(true) .getRowSlice("acct_4", "acct_5", "acct_6", "acct_7") .withColumnSlice("firstname", "lastname", "age") .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(4 == result.size()); for (Row<String, String> row : result) { int rowNo = Integer.parseInt(row.getKey().substring("acct_".length())); Assert.assertTrue(rowNo >= 4); Assert.assertTrue(rowNo <= 7); Assert.assertTrue(3 == row.getColumns().size()); } } @Test public void testRowKeysColumnRangeQuery() throws Exception { keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowSlice("A", "B", "C", "D") .withColumnRange(new CqlRangeBuilder<String>() .setStart("a") .setEnd("c") .build()) .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowSlice("E", "F", "G", "H") .withColumnRange(new CqlRangeBuilder<String>() .setStart("d") .setEnd("h") .build()) .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(4 == result.size()); for (Row<String, String> row : result) { int rowNo = row.getKey().charAt(0) - 'A'; Assert.assertTrue(rowNo >= 4); Assert.assertTrue(rowNo <= 7); Assert.assertTrue(5 == row.getColumns().size()); } } @Test public void testRowRangeAllColumnsQuery() throws Exception { String startToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("A")); String endToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("G")); keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(3 == result.size()); for (Row<String, String> row : result) { Assert.assertTrue(26 == row.getColumns().size()); } } @Test public void testRowRangeColumnSetQuery() throws Exception { String startToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("A")); String endToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("G")); keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .withColumnSlice("a", "s", "d", "f") .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .withColumnSlice("a", "s", "d", "f") .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(3 == result.size()); for (Row<String, String> row : result) { Assert.assertTrue(4 == row.getColumns().size()); } } @Test public void testRowRangeColumnRangeQuery() throws Exception { String startToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("A")); String endToken = Murmur3Partitioner.get().getTokenForKey(StringSerializer.get().fromString("G")); keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .withColumnRange(new CqlRangeBuilder<String>() .setStart("d") .setEnd("h") .build()) .execute(); Rows<String, String> result = keyspace.prepareQuery(CF_ROW_RANGE) .withCaching(true) .getRowRange(null, null, startToken, endToken, 10) .withColumnRange(new CqlRangeBuilder<String>() .setStart("d") .setEnd("h") .build()) .execute() .getResult(); Assert.assertNotNull(result); Assert.assertTrue(3 == result.size()); for (Row<String, String> row : result) { Assert.assertTrue(5 == row.getColumns().size()); } } private static void populateRowsForUserInfo(int numRows) throws Exception { MutationBatch mb = keyspace.prepareMutationBatch(); for (int i=0; i<numRows; i++) { Date date = OriginalDate.plusMinutes(i).toDate(); mb.withRow(CF_USER_INFO, "acct_" + i) .putColumn("firstname", "john_" + i, null) .putColumn("lastname", "smith_" + i, null) .putColumn("address", "john smith address " + i, null) .putColumn("age", 30+i, null) .putColumn("ageShort", new Integer(30+i).shortValue(), null) .putColumn("ageLong", new Integer(30+i).longValue(), null) .putColumn("percentile", 30.1) .putColumn("married", true) .putColumn("single", false) .putColumn("birthdate", date) .putColumn("bytes", TestBytes) .putColumn("uuid", TestUUID) .putEmptyColumn("empty"); mb.execute(); mb.discardMutations(); } } private static void populateRowsForColumnRange() throws Exception { MutationBatch m = keyspace.prepareMutationBatch(); for (char keyName = 'A'; keyName <= 'Z'; keyName++) { String rowKey = Character.toString(keyName); ColumnListMutation<String> colMutation = m.withRow(CF_ROW_RANGE, rowKey); for (char cName = 'a'; cName <= 'z'; cName++) { colMutation.putColumn(Character.toString(cName), (int) (cName - 'a') + 1, null); } m.withCaching(true); m.execute(); m.discardMutations(); } } }
7,605
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/DirectCqlTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.CqlResult; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.query.CqlQuery; import com.netflix.astyanax.query.PreparedCqlQuery; import com.netflix.astyanax.retry.RetryNTimes; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class DirectCqlTests extends KeyspaceTests { public static ColumnFamily<Integer, String> CF_DIRECT = ColumnFamily .newColumnFamily( "cfdirect", IntegerSerializer.get(), StringSerializer.get()); public static ColumnFamily<String, String> CF_EMPTY_TABLE = ColumnFamily .newColumnFamily( "empty_table", StringSerializer.get(), StringSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.prepareQuery(CF_DIRECT) .withCql("CREATE TABLE astyanaxunittests.cfdirect ( key int, column1 text, value bigint, PRIMARY KEY (key) )") .execute(); keyspace.prepareQuery(CF_EMPTY_TABLE) .withCql("CREATE TABLE astyanaxunittests.empty_table ( key text, column1 text, value text, PRIMARY KEY (key) )") .execute(); } @AfterClass public static void tearDown() throws Exception { keyspace.prepareQuery(CF_DIRECT) .withCql("DROP TABLE astyanaxunittests.cfdirect") .execute(); keyspace.prepareQuery(CF_EMPTY_TABLE) .withCql("DROP TABLE astyanaxunittests.empty_table") .execute(); } @Test public void testCql() throws Exception { // INSERT VALUES CqlQuery<Integer, String> cqlQuery = keyspace .prepareQuery(CF_DIRECT) .withCql("INSERT INTO astyanaxunittests.cfdirect (key, column1, value) VALUES (?,?,?)"); for (int i=0; i<10; i++) { PreparedCqlQuery<Integer, String> pStatement = cqlQuery.asPreparedStatement(); pStatement.withIntegerValue(i).withStringValue(""+i).withLongValue(Long.valueOf(""+i)).execute(); } // TEST REGULAR CQL OperationResult<CqlResult<Integer, String>> result = keyspace .prepareQuery(CF_DIRECT) .withRetryPolicy(new RetryNTimes(5)) .withCql("SELECT * FROM astyanaxunittests.cfdirect;") .execute(); Assert.assertTrue(result.getResult().hasRows()); Assert.assertEquals(10, result.getResult().getRows().size()); Assert.assertFalse(result.getResult().hasNumber()); for (int i=0; i<10; i++) { Row<Integer, String> row = result.getResult().getRows().getRow(i); Assert.assertTrue(i == row.getKey()); Assert.assertEquals(3, row.getColumns().size()); Integer key = row.getColumns().getIntegerValue("key", null); Assert.assertTrue(Integer.valueOf(""+i) == key); String column1 = row.getColumns().getStringValue("column1", null); Assert.assertEquals(""+i, column1); Long value = row.getColumns().getLongValue("value", null); Assert.assertTrue(Long.valueOf(""+i) == value); } // TEST CQL COUNT result = keyspace .prepareQuery(CF_DIRECT) .withCql("SELECT count(*) FROM astyanaxunittests.cfdirect;").execute(); Assert.assertFalse(result.getResult().hasRows()); Assert.assertTrue(result.getResult().hasNumber()); Assert.assertTrue(10 == result.getResult().getNumber()); } @Test public void testEmptyTable() throws Exception { CqlResult<String, String> result = keyspace.prepareQuery(CF_EMPTY_TABLE) .withCql("select * from astyanaxunittests.empty_table where key = 'blah'") .execute() .getResult(); Assert.assertFalse(result.hasRows()); Assert.assertFalse(result.hasNumber()); Assert.assertTrue(0 == result.getRows().size()); } }
7,606
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/LongColumnPaginationTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.reads.model.CqlRangeBuilder; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.query.RowQuery; import com.netflix.astyanax.serializers.LongSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class LongColumnPaginationTests extends KeyspaceTests { public static ColumnFamily<String, Long> CF_LONGCOLUMN = ColumnFamily .newColumnFamily( "LongColumn1", StringSerializer.get(), LongSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_LONGCOLUMN, null); CF_LONGCOLUMN.describe(keyspace); } @AfterClass public static void teardown() throws Exception { keyspace.dropColumnFamily(CF_LONGCOLUMN); } @Test public void paginateLongColumns() throws Exception { String rowKey = "A"; MutationBatch m = keyspace.prepareMutationBatch(); ColumnListMutation<Long> cfmLong = m.withRow(CF_LONGCOLUMN, rowKey); for (Long l = -10L; l < 10L; l++) { cfmLong.putEmptyColumn(l, null); } cfmLong.putEmptyColumn(Long.MAX_VALUE, null); m.execute(); // READ BACK WITH PAGINATION Long column = Long.MIN_VALUE; ColumnList<Long> columns; int pageSize = 10; RowQuery<String, Long> query = keyspace .prepareQuery(CF_LONGCOLUMN) .getKey("A") .autoPaginate(true) .withColumnRange( new CqlRangeBuilder<Long>() .setStart(column) .setFetchSize(pageSize).build()); int pageCount = 0; int colCount = 0; while (!(columns = query.execute().getResult()).isEmpty()) { for (Column<Long> c : columns) { colCount++; } pageCount++; } Assert.assertTrue("PageCount: " + pageCount, pageCount == 3); Assert.assertTrue("colCount = " + colCount,colCount == 21); query = keyspace .prepareQuery(CF_LONGCOLUMN) .getKey("A") .autoPaginate(true) .withColumnRange( new CqlRangeBuilder<Long>() .setStart(-5L) .setEnd(11L) .setFetchSize(pageSize).build()); pageCount = 0; colCount = 0; while (!(columns = query.execute().getResult()).isEmpty()) { for (Column<Long> c : columns) { colCount++; } pageCount++; } Assert.assertTrue(pageCount == 2); Assert.assertTrue("colCount = " + colCount,colCount == 15); } }
7,607
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/entitymapper/EntityMapperTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.entitymapper; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.cql.test.KeyspaceTests; import com.netflix.astyanax.cql.test.entitymapper.EntityMapperTests.SampleTestCompositeEntity.InnerEntity; import com.netflix.astyanax.entitystore.DefaultEntityManager; import com.netflix.astyanax.entitystore.EntityManager; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.serializers.StringSerializer; public class EntityMapperTests extends KeyspaceTests { private static ColumnFamily<String, String> CF_SAMPLE_TEST_ENTITY = ColumnFamily .newColumnFamily( "sampletestentity", StringSerializer.get(), StringSerializer.get()); private static EntityManager<SampleTestEntity, String> entityManager; private static EntityManager<SampleTestCompositeEntity, String> compositeEntityManager; @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_SAMPLE_TEST_ENTITY, null); CF_SAMPLE_TEST_ENTITY.describe(keyspace); entityManager = new DefaultEntityManager.Builder<SampleTestEntity, String>() .withEntityType(SampleTestEntity.class) .withKeyspace(keyspace) .withColumnFamily(CF_SAMPLE_TEST_ENTITY) .build(); compositeEntityManager = new DefaultEntityManager.Builder<SampleTestCompositeEntity, String>() .withEntityType(SampleTestCompositeEntity.class) .withKeyspace(keyspace) .withColumnFamily(CF_SAMPLE_TEST_ENTITY) .build(); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_SAMPLE_TEST_ENTITY); } @Test public void testSimpleEntityCRUD() throws Exception { final String ID = "testSimpleEntityCRUD"; final SampleTestEntity testEntity = new SampleTestEntity(); testEntity.id = ID; testEntity.testInt = 1; testEntity.testLong = 2L; testEntity.testString = "testString1"; testEntity.testDouble = 3.0; testEntity.testFloat = 4.0f; testEntity.testBoolean = true; // PUT entityManager.put(testEntity); // GET SampleTestEntity getEntity = entityManager.get(ID); Assert.assertNotNull(getEntity); Assert.assertTrue(testEntity.equals(getEntity)); // DELETE entityManager.delete(ID); getEntity = entityManager.get(ID); Assert.assertNull(getEntity); } @Test public void testSimpleEntityList() throws Exception { List<SampleTestEntity> entities = new ArrayList<SampleTestEntity>(); List<String> ids = new ArrayList<String>(); int entityCount = 11; for (int i=0; i<entityCount; i++) { SampleTestEntity testEntity = new SampleTestEntity(); testEntity.id = "id" + i; testEntity.testInt = i; testEntity.testLong = i; testEntity.testString = "testString" + i; testEntity.testDouble = i; testEntity.testFloat = i; testEntity.testBoolean = true; entities.add(testEntity); ids.add("id" + i); } // PUT COLLECTION entityManager.put(entities); // GET List<SampleTestEntity> getEntities = entityManager.get(ids); Assert.assertTrue(entityCount == getEntities.size()); int count = 0; for (SampleTestEntity e : getEntities) { Assert.assertTrue(count == e.testInt); Assert.assertTrue(count == e.testLong); Assert.assertTrue(("testString" + count).equals(e.testString)); count++; } // DELETE entityManager.delete(ids); // GET AFTER DELETE getEntities = entityManager.get(ids); Assert.assertTrue(0 == getEntities.size()); } @Test public void testGetAll() throws Exception { List<SampleTestEntity> entities = new ArrayList<SampleTestEntity>(); List<String> ids = new ArrayList<String>(); int entityCount = 11; for (int i=0; i<entityCount; i++) { SampleTestEntity testEntity = new SampleTestEntity(); testEntity.id = "id" + i; testEntity.testInt = i; testEntity.testLong = i; testEntity.testString = "testString" + i; testEntity.testDouble = i; testEntity.testFloat = i; testEntity.testBoolean = true; entities.add(testEntity); ids.add("id" + i); } // PUT COLLECTION entityManager.put(entities); List<SampleTestEntity> getEntities = entityManager.getAll(); Assert.assertTrue(entityCount == getEntities.size()); for (SampleTestEntity e : getEntities) { String id = e.id; int i = Integer.parseInt(id.substring("id".length())); Assert.assertTrue(i == e.testInt); Assert.assertTrue(i == e.testLong); Assert.assertTrue(("testString" + i).equals(e.testString)); } // DELETE entityManager.delete(ids); // GET AFTER DELETE getEntities = entityManager.getAll(); Assert.assertTrue(0 == getEntities.size()); } @Test public void testCompositeEntityCRUD() throws Exception { final String ID = "testCompositeEntityCRUD"; final SampleTestCompositeEntity testEntity = new SampleTestCompositeEntity(); testEntity.id = ID; testEntity.testInt = 1; testEntity.testLong = 2L; testEntity.testString = "testString1"; testEntity.testDouble = 3.0; testEntity.testFloat = 4.0f; testEntity.testBoolean = true; testEntity.inner = new InnerEntity(); testEntity.inner.testInnerInt = 11; testEntity.inner.testInnerLong = 22L; testEntity.inner.testInnerString = "testInnserString1"; // PUT compositeEntityManager.put(testEntity); // GET SampleTestCompositeEntity getEntity = compositeEntityManager.get(ID); System.out.println(getEntity); Assert.assertNotNull(getEntity); Assert.assertTrue(testEntity.equals(getEntity)); // DELETE entityManager.delete(ID); getEntity = compositeEntityManager.get(ID); Assert.assertNull(getEntity); } @Entity public static class SampleTestEntity { @Id private String id; @Column(name="integer") private int testInt; @Column(name="long") private long testLong; @Column(name="string") private String testString; @Column(name="float") private float testFloat; @Column(name="double") private double testDouble; @Column(name="boolean") private boolean testBoolean; public SampleTestEntity() { } @Override public String toString() { return "SampleTestEntity [\nid=" + id + "\ntestInt=" + testInt + "\ntestLong=" + testLong + "\ntestString=" + testString + "\ntestFloat=" + testFloat + "\ntestDouble=" + testDouble + "\ntestBoolean=" + testBoolean + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + (testBoolean ? 1231 : 1237); long temp; temp = Double.doubleToLongBits(testDouble); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Float.floatToIntBits(testFloat); result = prime * result + testInt; result = prime * result + (int) (testLong ^ (testLong >>> 32)); result = prime * result + ((testString == null) ? 0 : testString.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; SampleTestEntity other = (SampleTestEntity) obj; boolean equal = true; equal &= (id != null) ? id.equals(other.id) : other.id == null; equal &= testInt == other.testInt; equal &= testLong == other.testLong; equal &= testBoolean == other.testBoolean; equal &= (testString != null) ? testString.equals(other.testString) : other.testString == null; equal &= (Double.doubleToLongBits(testDouble) == Double.doubleToLongBits(other.testDouble)); equal &= (Float.floatToIntBits(testFloat) == Float.floatToIntBits(other.testFloat)); return equal; } } @Entity public static class SampleTestCompositeEntity { @Id private String id; @Column(name="integer") private int testInt; @Column(name="long") private long testLong; @Column(name="string") private String testString; @Column(name="float") private float testFloat; @Column(name="double") private double testDouble; @Column(name="boolean") private boolean testBoolean; @Entity public static class InnerEntity { @Column(name="inner_integer") private int testInnerInt; @Column(name="inner_long") private long testInnerLong; @Column(name="inner_string") private String testInnerString; @Override public String toString() { return "InnerEntity [\ninnerInt=" + testInnerInt + "\ninnerLong=" + testInnerLong + "\ninnerString=" + testInnerString + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + testInnerInt; result = prime * result + (int) (testInnerLong ^ (testInnerLong >>> 32)); result = prime * result + ((testInnerString == null) ? 0 : testInnerString.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; InnerEntity other = (InnerEntity) obj; boolean equal = true; equal &= testInnerInt == other.testInnerInt; equal &= testInnerLong == other.testInnerLong; equal &= (testInnerString != null) ? testInnerString.equals(other.testInnerString) : other.testInnerString == null; return equal; } } @Column(name="inner") private InnerEntity inner; public SampleTestCompositeEntity() { } @Override public String toString() { return "SampleTestEntity [\nid=" + id + "\ntestInt=" + testInt + "\ntestLong=" + testLong + "\ntestString=" + testString + "\ntestFloat=" + testFloat + "\ntestDouble=" + testDouble + "\ntestBoolean=" + testBoolean + "\ninner = " + inner.toString() + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + (testBoolean ? 1231 : 1237); long temp; temp = Double.doubleToLongBits(testDouble); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Float.floatToIntBits(testFloat); result = prime * result + testInt; result = prime * result + (int) (testLong ^ (testLong >>> 32)); result = prime * result + ((testString == null) ? 0 : testString.hashCode()); result = prime * result + ((inner == null) ? 0 : inner.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; SampleTestCompositeEntity other = (SampleTestCompositeEntity) obj; boolean equal = true; equal &= (id != null) ? id.equals(other.id) : other.id == null; equal &= testInt == other.testInt; equal &= testLong == other.testLong; equal &= testBoolean == other.testBoolean; equal &= (testString != null) ? testString.equals(other.testString) : other.testString == null; equal &= (Double.doubleToLongBits(testDouble) == Double.doubleToLongBits(other.testDouble)); equal &= (Float.floatToIntBits(testFloat) == Float.floatToIntBits(other.testFloat)); equal &= (inner != null) ? inner.equals(other.inner) : other.inner == null; return equal; } } }
7,608
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/utils/TestUtils.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class TestUtils { public static class TestTokenRange { public String startToken; public String endToken; public List<String> expectedRowKeys = new ArrayList<String>(); public TestTokenRange(String start, String end, String ... expectedKeys) { startToken = start; endToken = end; expectedRowKeys.addAll(Arrays.asList(expectedKeys)); } } public static List<TestTokenRange> getTestTokenRanges() { /** * HERE IS THE ACTUAL ORDER OF KEYS SORTED BY THEIR TOKENS * * -1671667184962092389 = Q, -1884162317724288694 = O, -2875471597373478633 = K, * -300136452241384611 = L, -4197513287269367591 = H, -422884050476930919 = Y, * -4837624800923759386 = B, -4942250469937744623 = W, -7139673851965614954 = J, * -7311855499978618814 = X, -7912594386904524724 = M, -8357705097978550118 = T, * -8692134701444027338 = C, 243126998722523514 = A, 3625209262381227179 = F, * 3846318681772828433 = R, 3914548583414697851 = N, 4834152074310082538 = I, * 4943864740760620945 = S, 576608558731393772 = V, 585625305377507626 = G, * 7170693507665539118 = E, 8086064298967168788 = Z, 83360928582194826 = P, * 8889191829175541774 = D, 9176724567785656400 = U * */ List<TestTokenRange> tokenRanges = new ArrayList<TestTokenRange>(); tokenRanges.add(new TestTokenRange("-8692134701444027338", "-7912594386904524724","C", "T", "M")); tokenRanges.add(new TestTokenRange("-7311855499978618814", "-4942250469937744623","X", "J", "W")); tokenRanges.add(new TestTokenRange("-4837624800923759386", "-2875471597373478633","B", "H", "K")); tokenRanges.add(new TestTokenRange("-1884162317724288694", "-422884050476930919","O", "Q", "Y")); tokenRanges.add(new TestTokenRange("-300136452241384611", "243126998722523514","L", "P", "A")); tokenRanges.add(new TestTokenRange("576608558731393772", "3625209262381227179","V", "G", "F")); tokenRanges.add(new TestTokenRange("3846318681772828433", "4834152074310082538","R", "N", "I")); tokenRanges.add(new TestTokenRange("4943864740760620945", "8086064298967168788","S", "E", "Z")); tokenRanges.add(new TestTokenRange("8889191829175541774", "9176724567785656400","D", "U")); return tokenRanges; } /** CERTAIN COLUMN FAMILIES THAT GET RE-USED A LOT FOR DIFFERENT UNIT TESTS */ public static ColumnFamily<String, String> CF_COLUMN_RANGE_TEST = ColumnFamily.newColumnFamily( "columnrange", // Column Family Name StringSerializer.get(), // Key Serializer StringSerializer.get(), // Column Serializer IntegerSerializer.get()); // Data serializer; public static void createColumnFamilyForColumnRange(Keyspace keyspace) throws Exception { keyspace.createColumnFamily(CF_COLUMN_RANGE_TEST, null); } public static void populateRowsForColumnRange(Keyspace keyspace) throws Exception { MutationBatch m = keyspace.prepareMutationBatch(); for (char keyName = 'A'; keyName <= 'Z'; keyName++) { String rowKey = Character.toString(keyName); ColumnListMutation<String> colMutation = m.withRow(CF_COLUMN_RANGE_TEST, rowKey); for (char cName = 'a'; cName <= 'z'; cName++) { colMutation.putColumn(Character.toString(cName), (int) (cName - 'a') + 1, null); } m.withCaching(true); m.execute(); m.discardMutations(); } } public static void deleteRowsForColumnRange(Keyspace keyspace) throws Exception { for (char keyName = 'A'; keyName <= 'Z'; keyName++) { MutationBatch m = keyspace.prepareMutationBatch(); String rowKey = Character.toString(keyName); m.withRow(CF_COLUMN_RANGE_TEST, rowKey).delete(); m.execute(); m.discardMutations(); } } }
7,609
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/utils/AstyanaxContextFactory.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.utils; import com.datastax.driver.core.Configuration; import com.datastax.driver.core.ProtocolOptions; import com.google.common.base.Supplier; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Cluster; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.connectionpool.Host; 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.CountingConnectionPoolMonitor; import com.netflix.astyanax.cql.CqlFamilyFactory; import com.netflix.astyanax.cql.JavaDriverConnectionPoolConfigurationImpl; import com.netflix.astyanax.cql.test.utils.ClusterConfiguration.*; import com.netflix.astyanax.impl.AstyanaxConfigurationImpl; import com.netflix.astyanax.thrift.ThriftFamilyFactory; import org.apache.log4j.PropertyConfigurator; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import static com.netflix.astyanax.cql.test.utils.ClusterConfiguration.*; public class AstyanaxContextFactory { private static final AtomicReference<Keyspace> keyspaceReference = new AtomicReference<Keyspace>(null); static { PropertyConfigurator.configure("./src/main/resources/test-log4j.properties"); AstyanaxContext<Keyspace> context = AstyanaxContextFactory.getKeyspace(); context.start(); keyspaceReference.set(context.getClient()); } public static AstyanaxContext<Cluster> getCluster() { return getCluster(TEST_CLUSTER_NAME, TheDriver); } public static AstyanaxContext<Cluster> getCluster(String clusterName, Driver driver) { if (driver == Driver.JAVA_DRIVER) { return clusterWithJavaDriver(clusterName); } else { return clusterWithThriftDriver(clusterName); } } private static AstyanaxContext<Cluster> clusterWithJavaDriver(String clusterName) { final String SEEDS = "localhost"; Supplier<List<Host>> HostSupplier = new Supplier<List<Host>>() { @Override public List<Host> get() { Host host = new Host(SEEDS, -1); return Collections.singletonList(host); } }; AstyanaxContext<Cluster> context = new AstyanaxContext.Builder() .forCluster(clusterName) .withAstyanaxConfiguration( new AstyanaxConfigurationImpl() .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE) .setDiscoveryDelayInSeconds(60000)) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl(TEST_CLUSTER_NAME + "_" + TEST_KEYSPACE_NAME) .setSocketTimeout(30000) .setMaxTimeoutWhenExhausted(2000) .setMaxConnsPerHost(20) .setInitConnsPerHost(10) .setSeeds(SEEDS) .setPort(9042) ) .withHostSupplier(HostSupplier) .withConnectionPoolMonitor(new CountingConnectionPoolMonitor()) .buildCluster(CqlFamilyFactory.getInstance()); return context; } private static AstyanaxContext<Cluster> clusterWithThriftDriver(String clusterName) { final String SEEDS = "localhost"; Supplier<List<Host>> HostSupplier = new Supplier<List<Host>>() { @Override public List<Host> get() { Host host = new Host(SEEDS, -1); return Collections.singletonList(host); } }; AstyanaxContext<Cluster> context = new AstyanaxContext.Builder() .forCluster(clusterName) .withAstyanaxConfiguration( new AstyanaxConfigurationImpl() .setDiscoveryType(NodeDiscoveryType.DISCOVERY_SERVICE) .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN) .setDiscoveryDelayInSeconds(60000)) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl(TEST_CLUSTER_NAME + "_" + TEST_KEYSPACE_NAME) .setSocketTimeout(30000) .setMaxTimeoutWhenExhausted(2000) .setMaxConnsPerHost(20) .setInitConnsPerHost(10) .setSeeds(SEEDS) .setPort(9160) ) .withHostSupplier(HostSupplier) .withConnectionPoolMonitor(new CountingConnectionPoolMonitor()) .buildCluster(ThriftFamilyFactory.getInstance()); return context; } public static AstyanaxContext<Keyspace> getKeyspace() { return getKeyspace(TEST_KEYSPACE_NAME, TheDriver); } public static AstyanaxContext<Keyspace> getKeyspace(String keyspaceName) { return getKeyspace(keyspaceName, TheDriver); } public static AstyanaxContext<Keyspace> getKeyspace(String keyspaceName, Driver driver) { if (driver == Driver.THRIFT) { return keyspaceWithThriftDriver(keyspaceName); } else { return keyspaceWithJavaDriver(keyspaceName); } } private static AstyanaxContext<Keyspace> keyspaceWithJavaDriver(String keyspaceName) { final String SEEDS = "localhost"; Supplier<List<Host>> HostSupplier = new Supplier<List<Host>>() { @Override public List<Host> get() { Host host = new Host(SEEDS, -1); return Collections.singletonList(host); } }; ProtocolOptions protocolOptions = new ProtocolOptions(9042); Configuration jdConfig = Configuration.builder() .withProtocolOptions(protocolOptions) .build(); AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder() .forKeyspace(keyspaceName) .withHostSupplier(HostSupplier) .withAstyanaxConfiguration(new AstyanaxConfigurationImpl()) .withConnectionPoolConfiguration(new JavaDriverConnectionPoolConfigurationImpl(jdConfig)) .buildKeyspace(CqlFamilyFactory.getInstance()); return context; } private static AstyanaxContext<Keyspace> keyspaceWithThriftDriver(String keyspaceName) { final String SEEDS = "localhost"; Supplier<List<Host>> HostSupplier = new Supplier<List<Host>>() { @Override public List<Host> get() { Host host = new Host(SEEDS, 9160); return Collections.singletonList(host); } }; AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder() .forCluster(TEST_CLUSTER_NAME) .forKeyspace(keyspaceName) .withAstyanaxConfiguration( new AstyanaxConfigurationImpl() .setDiscoveryType(NodeDiscoveryType.DISCOVERY_SERVICE) .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN) .setDiscoveryDelayInSeconds(60000) .setTargetCassandraVersion("1.2") ) .withConnectionPoolConfiguration( new ConnectionPoolConfigurationImpl(TEST_CLUSTER_NAME + "_" + TEST_KEYSPACE_NAME) .setSocketTimeout(30000) .setMaxTimeoutWhenExhausted(2000) .setMaxConnsPerHost(20) .setInitConnsPerHost(10) .setSeeds(SEEDS) .setPort(9160) ) .withHostSupplier(HostSupplier) .withConnectionPoolMonitor(new CountingConnectionPoolMonitor()) .buildKeyspace(ThriftFamilyFactory.getInstance()); return context; } public static Keyspace getCachedKeyspace() { return keyspaceReference.get(); } }
7,610
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/utils/ClusterConfiguration.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.utils; /** * Configuration class that dictates what Driver to use under the covers for the Astyanax Client. * Users can explicitly set the driver to use - default if JAVA_DRIVER. * * Note that this class provides helpful utilities to setup the AstyanaxContext using the * specified driver. * * @author poberai * */ public class ClusterConfiguration { public static String TEST_CLUSTER_NAME = "Test Cluster"; // use cass_sandbox public static String TEST_KEYSPACE_NAME = "astyanaxunittests"; public static Driver TheDriver = Driver.JAVA_DRIVER; //public static Driver TheDriver = Driver.THRIFT; public static enum Driver { THRIFT, JAVA_DRIVER; } public static void setDriver(Driver driver) { TheDriver = driver; } public static Driver getDriver() { return TheDriver; } }
7,611
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/utils/ReadTests.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.utils; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.UUID; import junit.framework.Assert; import org.joda.time.DateTime; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.test.KeyspaceTests; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.serializers.BytesArraySerializer; import com.netflix.astyanax.serializers.StringSerializer; public class ReadTests extends KeyspaceTests { public static DateTime OriginalDate = new DateTime().withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0).withHourOfDay(0); public static byte[] TestBytes = new String("TestBytes").getBytes(); public static UUID TestUUID = UUID.fromString("edeb3d70-15ce-11e3-8ffd-0800200c9a66"); //public static int RowCount = 1; public static String[] columnNamesArr = {"firstname", "lastname", "address","age","ageShort", "ageLong","percentile", "married","single", "birthdate", "bytes", "uuid", "empty"}; public static List<String> columnNames = new ArrayList<String>(Arrays.asList(columnNamesArr)); public static ColumnFamily<String, String> CF_USER_INFO = ColumnFamily.newColumnFamily( "UserInfo", // Column Family Name StringSerializer.get(), // Key Serializer StringSerializer.get()); // Column Serializer public static void initReadTests() throws Exception { initContext(); Collections.sort(columnNames); } public void testAllColumnsForRow(ColumnList<String> resultColumns, int i) throws Exception { Date date = OriginalDate.plusMinutes(i).toDate(); testColumnValue(resultColumns, "firstname", columnNames, "john_" + i); testColumnValue(resultColumns, "lastname", columnNames, "smith_" + i); testColumnValue(resultColumns, "address", columnNames, "john smith address " + i); testColumnValue(resultColumns, "age", columnNames, 30 + i); testColumnValue(resultColumns, "ageShort", columnNames, new Integer(30+i).shortValue()); testColumnValue(resultColumns, "ageLong", columnNames, new Integer(30+i).longValue()); testColumnValue(resultColumns, "percentile", columnNames, 30.1); testColumnValue(resultColumns, "married", columnNames, true); testColumnValue(resultColumns, "single", columnNames, false); testColumnValue(resultColumns, "birthdate", columnNames, date); testColumnValue(resultColumns, "bytes", columnNames, TestBytes); testColumnValue(resultColumns, "uuid", columnNames, TestUUID); testColumnValue(resultColumns, "empty", columnNames, null); /** TEST THE ITERATOR INTERFACE */ Iterator<Column<String>> iter = resultColumns.iterator(); while (iter.hasNext()) { Column<String> col = iter.next(); Assert.assertNotNull(col.getName()); } } private <T> void testColumnValue(ColumnList<String> result, String columnName, List<String> columnNames, T expectedValue) { // by column name Column<String> column = result.getColumnByName(columnName); Assert.assertEquals(columnName, column.getName()); testColumnValue(column, expectedValue); // // by column index // int index = columnNames.indexOf(columnName); // column = result.getColumnByIndex(index); // testColumnValue(column, expectedValue); } private <T> void testColumnValue(Column<String> column, T value) { // Check the column name // check if value exists if (value != null) { Assert.assertTrue(column.hasValue()); if (value instanceof String) { Assert.assertEquals(value, column.getStringValue()); } else if (value instanceof Integer) { Assert.assertEquals(value, column.getIntegerValue()); } else if (value instanceof Short) { Assert.assertEquals(value, column.getShortValue()); } else if (value instanceof Long) { Assert.assertEquals(value, column.getLongValue()); } else if (value instanceof Double) { Assert.assertEquals(value, column.getDoubleValue()); } else if (value instanceof Boolean) { Assert.assertEquals(value, column.getBooleanValue()); } else if (value instanceof Date) { Assert.assertEquals(value, column.getDateValue()); } else if (value instanceof byte[]) { ByteBuffer bbuf = column.getByteBufferValue(); String result = new String(BytesArraySerializer.get().fromByteBuffer(bbuf)); Assert.assertEquals(new String((byte[])value), result); } else if (value instanceof UUID) { Assert.assertEquals(value, column.getUUIDValue()); } else { Assert.fail("Value not recognized for column: " + column.getName()); } } else { // check that value does not exist Assert.assertFalse(column.hasValue()); } } public void populateRows(int numRows) throws Exception { MutationBatch mb = keyspace.prepareMutationBatch(); for (int i=0; i<numRows; i++) { Date date = OriginalDate.plusMinutes(i).toDate(); mb.withRow(CF_USER_INFO, "acct_" + i) .putColumn("firstname", "john_" + i, null) .putColumn("lastname", "smith_" + i, null) .putColumn("address", "john smith address " + i, null) .putColumn("age", 30+i, null) .putColumn("ageShort", new Integer(30+i).shortValue(), null) .putColumn("ageLong", new Integer(30+i).longValue(), null) .putColumn("percentile", 30.1) .putColumn("married", true) .putColumn("single", false) .putColumn("birthdate", date) .putColumn("bytes", TestBytes) .putColumn("uuid", TestUUID) .putEmptyColumn("empty"); mb.execute(); mb.discardMutations(); } } public void deleteRows(int numRows) throws Exception { MutationBatch mb = keyspace.prepareMutationBatch(); for (int i=0; i<numRows; i++) { mb.withRow(CF_USER_INFO, "acct_" + i).delete(); mb.execute(); mb.discardMutations(); } } public Collection<String> getRandomColumns(int numColumns) { Random random = new Random(); Set<String> hashSet = new HashSet<String>(); while(hashSet.size() < numColumns) { int pick = random.nextInt(26); char ch = (char) ('a' + pick); hashSet.add(String.valueOf(ch)); } return hashSet; } }
7,612
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/recipes/ChunkedObjectStoreTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.recipes; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.cql.test.KeyspaceTests; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.recipes.storage.CassandraChunkedStorageProvider; import com.netflix.astyanax.recipes.storage.ChunkedStorage; import com.netflix.astyanax.recipes.storage.ObjectMetadata; import com.netflix.astyanax.serializers.StringSerializer; public class ChunkedObjectStoreTest extends KeyspaceTests { public static ColumnFamily<String, String> CF_CHUNK = ColumnFamily.newColumnFamily("cfchunk", StringSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_CHUNK, null); CF_CHUNK.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_CHUNK); } @Test public void testAll() throws Exception { CassandraChunkedStorageProvider provider = new CassandraChunkedStorageProvider(keyspace, CF_CHUNK); StringBuilder sb = new StringBuilder(); for (int i=0; i<100; i++) { sb.append("abcdefghijklmnopqrstuvwxyz_"); } String input = sb.toString(); ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes()); ObjectMetadata meta = ChunkedStorage.newWriter(provider, "MyObject", in) .withChunkSize(100) .call(); meta = ChunkedStorage.newInfoReader(provider, "MyObject").call(); System.out.println(meta.getObjectSize().intValue()); System.out.println(meta.getChunkCount()); ByteArrayOutputStream os = new ByteArrayOutputStream(meta.getObjectSize().intValue()); meta = ChunkedStorage.newReader(provider, "MyObject", os) .withBatchSize(11) // Randomize fetching blocks within a batch. .withConcurrencyLevel(3) .call(); String output = os.toString(); Assert.assertEquals(input, output); ChunkedStorage.newDeleter(provider, "MyObject").call(); for (int i=0; i<meta.getChunkCount(); i++) { ColumnList<String> result = keyspace.prepareQuery(CF_CHUNK).getKey("MyObject$" + i).execute().getResult(); Assert.assertTrue(result.isEmpty()); } } }
7,613
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/recipes/ColumnPrefixDistributedLockTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.recipes; import java.util.concurrent.TimeUnit; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.test.KeyspaceTests; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.ConsistencyLevel; import com.netflix.astyanax.recipes.locks.BusyLockException; import com.netflix.astyanax.recipes.locks.ColumnPrefixDistributedRowLock; import com.netflix.astyanax.recipes.locks.StaleLockException; import com.netflix.astyanax.serializers.StringSerializer; public class ColumnPrefixDistributedLockTest extends KeyspaceTests { public static ColumnFamily<String, String> CF_DIST_LOCK = ColumnFamily .newColumnFamily( "distlock", StringSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_DIST_LOCK, null); CF_DIST_LOCK.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_DIST_LOCK); } @Test public void testLockSuccess() throws Exception { ColumnPrefixDistributedRowLock<String> lock = new ColumnPrefixDistributedRowLock<String>(keyspace, CF_DIST_LOCK, "RowKeyToLock") .expireLockAfter(1, TimeUnit.SECONDS) .withConsistencyLevel(ConsistencyLevel.CL_ONE); try { lock.acquire(); System.out.println("Successfully acquired lock"); } catch (StaleLockException e) { // The row contains a stale or abandoned lock // These can either be manually clean up or automatically // cleaned up (and ignored) by calling failOnStaleLock(false) e.printStackTrace(); Assert.fail(e.getMessage()); } catch (BusyLockException e) { // The row is currently locked. e.printStackTrace(); Assert.fail(e.getMessage()); } finally { lock.release(); } // VERIFY THAT THE LOCK ROW IS EMPTY ColumnList<String> result = keyspace.prepareQuery(CF_DIST_LOCK).getRow("RowKeyToLock").execute().getResult(); Assert.assertTrue(result.isEmpty()); } @Test public void testStaleLock() throws Exception { String rowKey = "StaleRowKeyToLock"; String lockPrefix = "TestLockPrefix"; Long pastTime = System.currentTimeMillis() - 2000L; Long timeInMicros = TimeUnit.MICROSECONDS.convert(pastTime, TimeUnit.MILLISECONDS); MutationBatch m = keyspace.prepareMutationBatch(); m.withRow(CF_DIST_LOCK, rowKey).putColumn(lockPrefix + "1", timeInMicros); m.execute(); ColumnPrefixDistributedRowLock<String> lock = new ColumnPrefixDistributedRowLock<String>(keyspace, CF_DIST_LOCK, rowKey) .withColumnPrefix(lockPrefix) .expireLockAfter(1, TimeUnit.SECONDS) .failOnStaleLock(true) .withConsistencyLevel(ConsistencyLevel.CL_ONE); try { lock.acquire(); Assert.fail("Acquired lock when there was a STALE LOCK"); } catch (StaleLockException e) { // The row contains a stale or abandoned lock // These can either be manually clean up or automatically // cleaned up (and ignored) by calling failOnStaleLock(false) System.out.println("STALE LOCK " + e.getMessage()); lock.releaseExpiredLocks(); lock.release(); } // VERIFY THAT THE LOCK ROW IS EMPTY ColumnList<String> result = keyspace.prepareQuery(CF_DIST_LOCK).getRow(rowKey).execute().getResult(); Assert.assertTrue(result.isEmpty()); } @Test public void testBusyLock() throws Exception { String rowKey = "BusyRowKeyToLock"; String lockPrefix = "TestLockPrefix"; Long futureTime = System.currentTimeMillis() + 20000L; Long timeInMicros = TimeUnit.MICROSECONDS.convert(futureTime, TimeUnit.MILLISECONDS); MutationBatch m = keyspace.prepareMutationBatch(); m.withRow(CF_DIST_LOCK, rowKey).putColumn(lockPrefix + "1", timeInMicros); m.execute(); ColumnPrefixDistributedRowLock<String> lock = new ColumnPrefixDistributedRowLock<String>(keyspace, CF_DIST_LOCK, rowKey) .withColumnPrefix(lockPrefix) .expireLockAfter(1, TimeUnit.SECONDS) .failOnStaleLock(true) .withConsistencyLevel(ConsistencyLevel.CL_ONE); try { lock.acquire(); Assert.fail("Acquired lock when there was a STALE LOCK"); } catch (BusyLockException e) { // The row is currently locked. System.out.println("BUSY LOCK " + e.getMessage()); lock.releaseAllLocks(); } // VERIFY THAT THE LOCK ROW IS EMPTY ColumnList<String> result = keyspace.prepareQuery(CF_DIST_LOCK).getRow(rowKey).execute().getResult(); Assert.assertTrue(result.isEmpty()); } }
7,614
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/recipes/AllRowsReaderTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.recipes; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.base.Function; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.test.KeyspaceTests; 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.Murmur3Partitioner; import com.netflix.astyanax.recipes.reader.AllRowsReader; import com.netflix.astyanax.serializers.StringSerializer; public class AllRowsReaderTest extends KeyspaceTests { public static ColumnFamily<String, String> CF_ALL_ROWS_READER = ColumnFamily .newColumnFamily( "allrowsreader", StringSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_ALL_ROWS_READER, null); CF_ALL_ROWS_READER.describe(keyspace); /** POPULATE ROWS FOR TESTS */ MutationBatch m = keyspace.prepareMutationBatch(); for (char keyName = 'A'; keyName <= 'Z'; keyName++) { String rowKey = Character.toString(keyName); ColumnListMutation<String> cfmStandard = m.withRow(CF_ALL_ROWS_READER, rowKey); for (char cName = 'a'; cName <= 'z'; cName++) { cfmStandard.putColumn(Character.toString(cName), (int) (cName - 'a') + 1, null); } m.execute(); m.discardMutations(); } } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_ALL_ROWS_READER); } @Test public void testAllRowsReader() throws Exception { final AtomicInteger rowCount = new AtomicInteger(0); new AllRowsReader.Builder<String, String>(keyspace, CF_ALL_ROWS_READER) .withPageSize(100) // Read 100 rows at a time .withConcurrencyLevel(10) // Split entire token range into 10. Default is by number of nodes. .withPartitioner(Murmur3Partitioner.get()) .forEachPage(new Function<Rows<String, String>, Boolean>() { @Override public Boolean apply(Rows<String, String> rows) { // Process the row here ... // This will be called from multiple threads so make sure your code is thread safe for (Row<String, String> row : rows) { ColumnList<String> colList = row.getColumns(); Assert.assertTrue("ColList: " + colList.size(), 26 == colList.size()); rowCount.incrementAndGet(); } return true; } }) .build() .call(); Assert.assertTrue("RowCount: " + rowCount.get(), 26 == rowCount.get()); } }
7,615
0
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test
Create_ds/astyanax/astyanax-test/src/main/java/com/netflix/astyanax/cql/test/recipes/ColumnPrefixUniquenessConstraintTest.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.cql.test.recipes; import java.util.UUID; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.cql.test.KeyspaceTests; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.ConsistencyLevel; import com.netflix.astyanax.recipes.locks.BusyLockException; import com.netflix.astyanax.recipes.uniqueness.ColumnPrefixUniquenessConstraint; import com.netflix.astyanax.serializers.LongSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class ColumnPrefixUniquenessConstraintTest extends KeyspaceTests { public static ColumnFamily<Long, String> CF_UNIQUE_CONSTRAINT = ColumnFamily .newColumnFamily( "cfunique2", LongSerializer.get(), StringSerializer.get()); @BeforeClass public static void init() throws Exception { initContext(); keyspace.createColumnFamily(CF_UNIQUE_CONSTRAINT, null); CF_UNIQUE_CONSTRAINT.describe(keyspace); } @AfterClass public static void tearDown() throws Exception { keyspace.dropColumnFamily(CF_UNIQUE_CONSTRAINT); } Supplier<String> UniqueColumnSupplier = new Supplier<String>() { @Override public String get() { return UUID.randomUUID().toString(); } }; @Test public void testUnique() throws Exception { ColumnPrefixUniquenessConstraint<Long> unique = new ColumnPrefixUniquenessConstraint<Long>(keyspace, CF_UNIQUE_CONSTRAINT, 1L) .withConsistencyLevel(ConsistencyLevel.CL_ONE); unique.acquire(); try { unique = new ColumnPrefixUniquenessConstraint<Long>(keyspace, CF_UNIQUE_CONSTRAINT, 1L) .withConsistencyLevel(ConsistencyLevel.CL_ONE); unique.acquire(); Assert.fail("Should have gotten a BusyLockException"); } catch (BusyLockException e) { System.out.println(e.getMessage()); } } @Test public void testUniqueAndRelease() throws Exception { ColumnPrefixUniquenessConstraint<Long> unique = new ColumnPrefixUniquenessConstraint<Long>(keyspace, CF_UNIQUE_CONSTRAINT, 2L) .withConsistencyLevel(ConsistencyLevel.CL_ONE); unique.acquire(); unique.release(); unique = new ColumnPrefixUniquenessConstraint<Long>(keyspace, CF_UNIQUE_CONSTRAINT, 2L) .withConsistencyLevel(ConsistencyLevel.CL_ONE); unique.acquire(); } @Test public void testUniquenessWithCustomMutation() throws Exception { ColumnList<String> result = keyspace.prepareQuery(CF_UNIQUE_CONSTRAINT).getRow(10L).execute().getResult(); Assert.assertTrue(result.isEmpty()); ColumnPrefixUniquenessConstraint<Long> unique = new ColumnPrefixUniquenessConstraint<Long>(keyspace, CF_UNIQUE_CONSTRAINT, 3L) .withConsistencyLevel(ConsistencyLevel.CL_ONE); unique.acquireAndApplyMutation(new Function<MutationBatch, Boolean>() { public Boolean apply(MutationBatch input) { input.withRow(CF_UNIQUE_CONSTRAINT, 10L).putEmptyColumn("MyCustomColumn", null); return true; } }); result = keyspace.prepareQuery(CF_UNIQUE_CONSTRAINT).getRow(10L).execute().getResult(); Assert.assertFalse(result.isEmpty()); } }
7,616
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/Execution.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax; import com.google.common.util.concurrent.ListenableFuture; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * Interface for an operation that can be executed on the cluster. * * @param <R> - The return type for the concrete operation * * @author elandau */ public interface Execution<R> { /** * Block while executing the operations * * @return Result object that wraps the actual result and provides information about * how the operation was executed. * @throws ConnectionException */ OperationResult<R> execute() throws ConnectionException; /** * Return a future to the operation. The operation will most likely be * executed in a separate thread where both the connection pool logic as * well as the actual operation will be executed. * * @return A listenable future * @throws ConnectionException */ ListenableFuture<OperationResult<R>> executeAsync() throws ConnectionException; }
7,617
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/AuthenticationCredentials.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax; /** * Representation for a user/password used to log into a keyspace. * * @author elandau * */ public interface AuthenticationCredentials { /** * @return The username */ String getUsername(); /** * @return The password */ String getPassword(); /** * @return Array of all custom attribute names */ String[] getAttributeNames(); /** * Retrieve a single attribute by name * * @param name Attribute name */ Object getAttribute(String name); }
7,618
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/Clock.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax; /** * Interface for a clock used for setting the column timestamp * * @author elandau * */ public interface Clock { long getCurrentTime(); }
7,619
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/ExceptionCallback.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * ExceptionCallback is used in situation where it is not possible to return a * checked exception, such as when implementing a custom iterator. The callback * implementation * * @author elandau * */ public interface ExceptionCallback { /** * * @param e * @return true to retry or false to end the iteration */ boolean onException(ConnectionException e); }
7,620
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/impl/FilteringHostSupplier.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.impl; import java.util.List; import java.util.Map; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.astyanax.connectionpool.Host; /** * Node discovery supplier that only return suppliers that come from both * sources * * @author elandau * */ public class FilteringHostSupplier implements Supplier<List<Host>> { private final Supplier<List<Host>> sourceSupplier; private final Supplier<List<Host>> filterSupplier; public FilteringHostSupplier( Supplier<List<Host>> filterSupplier, // This is a ring describe Supplier<List<Host>> sourceSupplier) { this.sourceSupplier = sourceSupplier; this.filterSupplier = filterSupplier; } @Override public List<Host> get() { // Get a list of hosts from two sources and use the first to filter // out hosts from the second List<Host> filterList = Lists.newArrayList(); List<Host> sourceList = Lists.newArrayList(); try { sourceList = sourceSupplier.get(); filterList = filterSupplier.get(); } catch (RuntimeException e) { if (sourceList != null) return sourceList; throw e; } if (filterList.isEmpty()) return sourceList; // Generate a lookup of all alternate IP addresses for the hosts in the // filter list final Map<String, Host> lookup = Maps.newHashMap(); for (Host host : filterList) { lookup.put(host.getIpAddress(), host); for (String addr : host.getAlternateIpAddresses()) { lookup.put(addr, host); } } List<Host> result = Lists.newArrayList(Collections2.filter(sourceList, new Predicate<Host>() { @Override public boolean apply(Host host) { Host foundHost = lookup.get(host.getHostName()); if (foundHost == null) { for (String addr : host.getAlternateIpAddresses()) { foundHost = lookup.get(addr); if (foundHost != null) { break; } } } if (foundHost != null) { host.setTokenRanges(foundHost.getTokenRanges()); return true; } return false; } })); if (result.isEmpty()) return sourceList; return result; } }
7,621
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/tracing/OperationTracer.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.tracing; import com.netflix.astyanax.connectionpool.Operation; public interface OperationTracer { public AstyanaxContext getAstyanaxContext(); public <CL, R> void onCall(AstyanaxContext ctx, Operation<CL, R> op); public <CL, R> void onSuccess(AstyanaxContext ctx, Operation<CL, R> op); public <CL, R> void onException(AstyanaxContext ctx, Operation<CL, R> op, Throwable t); }
7,622
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/tracing/AstyanaxContext.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.tracing; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class AstyanaxContext { private final Map<Object, Object> context; public AstyanaxContext() { this(new ConcurrentHashMap<Object, Object>()); } public AstyanaxContext(Map<Object, Object> context) { super(); this.context = context; } public Object get(Object name) { return context.get(name); } public Object set(Object name, Object value) { return context.put(name, value); } }
7,623
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestHostConnectionPool.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.astyanax.connectionpool.Connection; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; public class TestHostConnectionPool implements HostConnectionPool<TestClient> { private final Host host; private AtomicBoolean isShutDown = new AtomicBoolean(); public TestHostConnectionPool(Host host) { this.host = host; } @Override public Connection<TestClient> borrowConnection(int timeout) throws ConnectionException { return null; } @Override public boolean returnConnection(Connection<TestClient> connection) { return false; } @Override public void markAsDown(ConnectionException reason) { isShutDown.set(true); } @Override public void shutdown() { isShutDown.set(true); } @Override public int primeConnections(int numConnections) throws ConnectionException, InterruptedException { return 0; } @Override public Host getHost() { return host; } @Override public int getActiveConnectionCount() { return 0; } @Override public int getPendingConnectionCount() { return 0; } @Override public int getBlockedThreadCount() { return 0; } @Override public int getIdleConnectionCount() { return 0; } @Override public int getBusyConnectionCount() { return 0; } @Override public boolean isReconnecting() { return false; } @Override public double getScore() { return 0; } @Override public void addLatencySample(long lastLatency, long now) { } @Override public boolean closeConnection(Connection<TestClient> connection) { return false; } @Override public int getOpenedConnectionCount() { return 0; } @Override public int getFailedOpenConnectionCount() { return 0; } @Override public int getClosedConnectionCount() { return 0; } @Override public int getErrorsSinceLastSuccess() { return 0; } @Override public boolean isActive() { return false; } @Override public boolean isShutdown() { return false; } @Override public int getConnectAttemptCount() { return 0; } }
7,624
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestClient.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; public class TestClient { }
7,625
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestHostType.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.BadRequestException; import com.netflix.astyanax.connectionpool.exceptions.ConnectionAbortedException; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.HostDownException; import com.netflix.astyanax.connectionpool.exceptions.OperationTimeoutException; import com.netflix.astyanax.connectionpool.exceptions.TimeoutException; import com.netflix.astyanax.connectionpool.exceptions.TransportException; import com.netflix.astyanax.connectionpool.impl.OperationResultImpl; public enum TestHostType { ALWAYS_DOWN { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { throw new TransportException("TransportException"); } }, CONNECT_WITH_UNCHECKED_EXCEPTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return null; } @Override public void open(long timeout) throws ConnectionException { throw new RuntimeException("UNCHECKED_OPEN_EXCEPTION"); } }, CONNECT_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new IllegalStateException(CONNECT_TIMEOUT.name()); } @Override public void open(long timeout) throws ConnectionException { try { Thread.sleep(50); } catch (InterruptedException e) { } throw new TimeoutException("TimeoutException"); } }, CONNECT_TRANSPORT_ERROR { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new IllegalStateException(CONNECT_TRANSPORT_ERROR.name()); } @Override public void open(long timeout) throws ConnectionException { throw new TransportException(CONNECT_TRANSPORT_ERROR.name()); } }, CONNECT_FAIL_FIRST { private AtomicInteger count = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { if (count.getAndIncrement() == 0) { throw new TransportException("connection refused"); } } }, CONNECT_FAIL_FIRST_TWO { private AtomicInteger count = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { if (count.incrementAndGet() <= 2) { throw new TransportException("connection refused"); } } }, LOST_CONNECTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { } }, SOCKET_TIMEOUT_AFTER10 { private AtomicInteger count = new AtomicInteger(0); private int failAfter = 10; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (count.incrementAndGet() >= failAfter) { throw new TimeoutException("TimeoutException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(5)); } @Override public void open(long timeout) throws ConnectionException { if (count.get() >= failAfter) { think(1000); throw new TimeoutException("Timeout"); // count.set(0); } } }, OPERATION_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new OperationTimeoutException("TimedOutException"); } @Override public void open(long timeout) throws ConnectionException { } }, SOCKET_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(2000); throw new TimeoutException("SocketTimeException"); } @Override public void open(long timeout) throws ConnectionException { } }, ALTERNATING_SOCKET_TIMEOUT_200 { private AtomicLong counter = new AtomicLong(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() / 200 % 2 == 1) { think(200); throw new TimeoutException("SocketTimeException"); } else { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(0)); } } @Override public void open(long timeout) throws ConnectionException { } }, CONNECT_BAD_REQUEST_EXCEPTION { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { throw new BadRequestException("BadRequestException"); } }, GOOD_SLOW { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(500)); } @Override public void open(long timeout) throws ConnectionException { think(500); } }, GOOD_FAST { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), think(5)); } @Override public void open(long timeout) throws ConnectionException { } }, GOOD_IMMEDIATE { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_100 { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() > 100) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_100_RANDOM { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (counter.incrementAndGet() > new Random().nextInt(1000)) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, THRASHING_TIMEOUT { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(50 + new Random().nextInt(1000)); throw new TimeoutException("thrashing_timeout"); } @Override public void open(long timeout) throws ConnectionException { } }, RECONNECT_2ND_TRY { int retry = 0; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { throw new TransportException("TransportException"); } @Override public void open(long timeout) throws ConnectionException { if (++retry == 2) { // success } else { throw new TransportException("TransportException"); } } }, ABORTED_CONNECTION { boolean aborted = true; @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if (aborted) { aborted = false; throw new ConnectionAbortedException( "ConnectionAbortedException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } }, FAIL_AFTER_10_SLOW_CLOSE { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { think(100); if (counter.incrementAndGet() > 10) { counter.set(0); throw new TransportException("TransportException"); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } @Override public void close() { // LOG.info("Closing"); think(15000); } }, SWAP_EVERY_200 { private AtomicInteger counter = new AtomicInteger(0); @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { if ((counter.incrementAndGet() / 20) % 2 == 0) { think(100); } else { think(1); } return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { } @Override public void close() { // LOG.info("Closing"); think(15000); } }, RANDOM_ALL { @Override public <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException { return new OperationResultImpl<R>(pool.getHost(), op.execute(null, null), 0); } @Override public void open(long timeout) throws ConnectionException { double p = new Random().nextDouble(); if (p < 0.002) { throw new HostDownException("HostDownException"); } else if (p < 0.004) { throw new TimeoutException("HostDownException"); } else if (p < 0.006) { throw new TransportException("TransportException"); } think(200); } @Override public void close() { // LOG.info("Closing"); think(10); } }; private static final Logger LOG = LoggerFactory .getLogger(TestHostType.class); private static final Map<Integer, TestHostType> lookup = new HashMap<Integer, TestHostType>(); static { for (TestHostType type : EnumSet.allOf(TestHostType.class)) lookup.put(type.ordinal(), type); } public static TestHostType get(int ordinal) { return lookup.get(ordinal); } public abstract <R> OperationResult<R> execute( HostConnectionPool<TestClient> pool, Operation<TestClient, R> op) throws ConnectionException; public abstract void open(long timeout) throws ConnectionException; public void close() { } private static int think(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { } return time; } }
7,626
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestCompositeType2.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import com.netflix.astyanax.annotations.Component; public class TestCompositeType2 { @Component private boolean part1; @Component private String part2; public TestCompositeType2() { } public TestCompositeType2(boolean part1, String part2) { this.part1 = part1; this.part2 = part2; } public String toString() { return new StringBuilder().append("MockCompositeType2(").append(part1) .append(",").append(part2).append(")").toString(); } }
7,627
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/SessionEvent.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.util.UUID; import com.netflix.astyanax.annotations.Component; import com.netflix.astyanax.util.TimeUUIDUtils; public class SessionEvent { @Component private String sessionId; @Component private UUID timestamp; public SessionEvent(String sessionId, UUID timestamp) { this.sessionId = sessionId; this.timestamp = timestamp; } public SessionEvent() { } public String getSessionId() { return this.sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public UUID getTimestamp() { return this.timestamp; } public void setTimestamp(UUID timestamp) { this.timestamp = timestamp; } public String toString() { return new StringBuilder().append(sessionId).append(':') .append(TimeUUIDUtils.getTimeFromUUID(timestamp)).toString(); } }
7,628
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestTokenRange.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.math.BigInteger; import java.util.List; import com.google.common.collect.Lists; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.TokenRange; import com.netflix.astyanax.connectionpool.impl.TokenRangeImpl; import com.netflix.astyanax.util.TokenGenerator; public class TestTokenRange implements TokenRange { private String start; private String end; private List<String> endpoints; public TestTokenRange(String start, String end, List<String> endpoints) { this.start = start; this.end = end; this.endpoints = endpoints; } @Override public String getStartToken() { return start; } @Override public String getEndToken() { return end; } @Override public List<String> getEndpoints() { return endpoints; } public static List<Host> makeRing( int nHosts, int replication_factor, int id, BigInteger minInitialToken, BigInteger maxInitialToken) { List<Host> hosts = Lists.newArrayList(); for (int i = 0; i < nHosts; i++) { hosts.add(new Host("127.0." + id + "." + i + ":" + TestHostType.GOOD_FAST.ordinal(), 9160)); } for (int i = 0; i < nHosts; i++) { String startToken = TokenGenerator.initialToken(nHosts, i, minInitialToken, maxInitialToken); String endToken = TokenGenerator.initialToken(nHosts, i+1, minInitialToken, maxInitialToken); if (endToken.equals(maxInitialToken.toString())) endToken = minInitialToken.toString(); TokenRange range = new TokenRangeImpl(startToken, endToken, null); for (int j = 0; j < replication_factor; j++) { hosts.get((i+j)%nHosts).getTokenRanges().add(range); } } return hosts; } public static String getRingDetails(List<Host> hosts) { StringBuilder sb = new StringBuilder(); for (Host host : hosts) { sb.append(host.toString()) .append("\n"); for (TokenRange range : host.getTokenRanges()) { sb.append(" ").append(range.toString()).append("\n"); } } return sb.toString(); } }
7,629
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestDriver.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.test; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.netflix.astyanax.connectionpool.Host; public class TestDriver { private int nThreads; private Supplier<Integer> callsPerSecond; private ScheduledExecutorService executor; private Function<TestDriver, Void> callback; private volatile int delta; private AtomicLong callbackCounter = new AtomicLong(); private long iterationCount = 100; private long futuresTimeout = 0; private TimeUnit futuresUnits = TimeUnit.MILLISECONDS; private ExecutorService futuresExecutor; private ArrayList<Event> events = Lists.newArrayList(); private long startTime; private AtomicLong operationCounter = new AtomicLong(0); public static abstract class Event { protected Function<TestDriver, Void> function; public Event(Function<TestDriver, Void> function) { this.function = function; } public abstract void addToExecutor(ScheduledExecutorService service, final TestDriver driver); } public static class RecurringEvent extends Event{ private final long delay; private final TimeUnit units; public RecurringEvent(Function<TestDriver, Void> function, long delay, TimeUnit units) { super(function); this.delay = delay; this.units = units; } public void addToExecutor(ScheduledExecutorService service, final TestDriver driver) { service.scheduleAtFixedRate(new Runnable() { @Override public void run() { function.apply(driver); } }, delay, delay, units); } } public static class Builder { private TestDriver driver = new TestDriver(); public Builder withThreadCount(int nThreads) { driver.nThreads = nThreads; return this; } public Builder withCallsPerSecondSupplier(Supplier<Integer> callsPerSecond) { driver.callsPerSecond = callsPerSecond; return this; } public Builder withCallback(Function<TestDriver, Void> callback) { driver.callback = callback; return this; } public Builder withIterationCount(long iterationCount) { driver.iterationCount = iterationCount; return this; } public Builder withFutures(long timeout, TimeUnit units) { driver.futuresTimeout = timeout; driver.futuresUnits = units; return this; } public Builder withRecurringEvent(long delay, TimeUnit units, Function<TestDriver, Void> event) { driver.events.add(new RecurringEvent(event, delay, units)); return this; } public TestDriver build() { driver.executor = Executors.newScheduledThreadPool(driver.nThreads + 10); if (driver.futuresTimeout != 0) driver.futuresExecutor = Executors.newScheduledThreadPool(driver.nThreads); return driver; } } public void start() { updateDelta(); operationCounter.incrementAndGet(); startTime = System.currentTimeMillis(); for (int i = 0; i < nThreads; i++) { this.executor.submit(new Runnable() { @Override public void run() { try { Thread.sleep(new Random().nextInt(delta)); } catch (InterruptedException e1) { throw new RuntimeException(e1); } long startTime = System.currentTimeMillis(); long nextTime = startTime; while (true) { operationCounter.incrementAndGet(); try { if (iterationCount != 0) { if (callbackCounter.incrementAndGet() > iterationCount) return; } if (futuresTimeout == 0) { callback.apply(TestDriver.this); } else { Future<?> f = futuresExecutor.submit(new Runnable() { @Override public void run() { callback.apply(TestDriver.this); } }); try { f.get(futuresTimeout, futuresUnits); } catch (Throwable t) { f.cancel(true); } } } catch (Throwable t) { } nextTime += delta; long waitTime = nextTime - System.currentTimeMillis(); if (waitTime > 0) { try { Thread.sleep(waitTime); } catch (InterruptedException e) { return; } } } } }); } this.executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { updateDelta(); } }, 1, 1, TimeUnit.SECONDS); for (Event event : events) { event.addToExecutor(this.executor, this); } } public void updateDelta() { delta = 1000 * nThreads / callsPerSecond.get(); } public void stop() { this.executor.shutdownNow(); } public void await() throws InterruptedException { this.executor.awaitTermination(1000, TimeUnit.HOURS); } public long getCallCount() { return callbackCounter.get(); } public long getRuntime() { return System.currentTimeMillis() - startTime; } public long getOperationCount() { return operationCounter.get(); } }
7,630
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/ProbabalisticFunction.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.test; import java.util.ArrayList; import java.util.Random; import com.google.common.base.Function; import com.google.common.collect.Lists; public class ProbabalisticFunction<T, R> implements Function<T,R> { public static class Builder<T, R> { private ProbabalisticFunction<T, R> function = new ProbabalisticFunction<T,R>(); private double counter = 0; public Builder<T, R> withProbability(double probability, Function<T, R> func) { counter += probability; function.functions.add(new Entry<T, R>(counter, func)); return this; } public Builder<T, R> withDefault(Function<T, R> func) { function.defaultFunction = func; return this; } public Builder<T, R> withAlways(Runnable func) { function.always = func; return this; } public Function<T, R> build() { return function; } } public static class Entry<T, R> { Entry(double probability, Function<T,R> function) { this.probability = probability; this.function = function; } double probability; Function<T,R> function; } private ArrayList<Entry<T, R>> functions = Lists.newArrayList(); private Function<T,R> defaultFunction; private Runnable always; @Override public R apply(T arg) { always.run(); double p = new Random().nextDouble(); for (Entry<T,R> entry : functions) { if (entry.probability > p) { return entry.function.apply(arg); } } return defaultFunction.apply(arg); } }
7,631
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestConnectionPool.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.util.Collection; import java.util.List; import com.netflix.astyanax.connectionpool.ConnectionPool; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.OperationException; import com.netflix.astyanax.connectionpool.impl.Topology; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.retry.RetryPolicy; public class TestConnectionPool implements ConnectionPool<TestClient> { Collection<Host> ring; public Collection<Host> getHosts() { return this.ring; } @Override public boolean addHost(Host host, boolean refresh) { return true; } @Override public boolean removeHost(Host host, boolean refresh) { return true; } @Override public void setHosts(Collection<Host> ring) { this.ring = ring; } @Override public <R> OperationResult<R> executeWithFailover( Operation<TestClient, R> op, RetryPolicy retry) throws ConnectionException, OperationException { return null; } @Override public void shutdown() { } @Override public void start() { } @Override public boolean isHostUp(Host host) { return false; } @Override public boolean hasHost(Host host) { return false; } @Override public HostConnectionPool<TestClient> getHostPool(Host host) { return null; } @Override public List<HostConnectionPool<TestClient>> getActivePools() { return null; } @Override public List<HostConnectionPool<TestClient>> getPools() { return null; } @Override public Topology<TestClient> getTopology() { return null; } @Override public Partitioner getPartitioner() { // TODO Auto-generated method stub return null; } }
7,632
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestCompositeType.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import com.netflix.astyanax.annotations.Component; public class TestCompositeType { @Component private String stringPart; @Component private Integer intPart; @Component private Integer intPart2; @Component private boolean boolPart; @Component private String utf8StringPart; public TestCompositeType() { } public TestCompositeType(String part1, Integer part2, Integer part3, boolean boolPart, String utf8StringPart) { this.stringPart = part1; this.intPart = part2; this.intPart2 = part3; this.boolPart = boolPart; this.utf8StringPart = utf8StringPart; } public TestCompositeType setStringPart(String part) { this.stringPart = part; return this; } public String getStringPart() { return this.stringPart; } public TestCompositeType setIntPart1(int value) { this.intPart = value; return this; } public int getIntPart1() { return this.intPart; } public TestCompositeType setIntPart2(int value) { this.intPart2 = value; return this; } public int getIntPart2() { return this.intPart2; } public TestCompositeType setBoolPart(boolean boolPart) { this.boolPart = boolPart; return this; } public boolean getBoolPart() { return this.boolPart; } public TestCompositeType setUtf8StringPart(String str) { this.utf8StringPart = str; return this; } public String getUtf8StringPart() { return this.utf8StringPart; } public String toString() { return new StringBuilder().append("MockCompositeType[") .append(stringPart).append(',').append(intPart).append(',') .append(intPart2).append(',').append(boolPart).append(',') .append(utf8StringPart).append(']').toString(); } }
7,633
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/IncreasingRateSupplier.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.test; import com.google.common.base.Supplier; public class IncreasingRateSupplier implements Supplier<Integer>{ private int rate; private final long delta; public IncreasingRateSupplier(int initialRate, int delta) { this.rate = initialRate; this.delta = delta; } public Integer get() { rate += this.delta; return rate; } }
7,634
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestConnectionFactory.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.astyanax.connectionpool.Connection; import com.netflix.astyanax.connectionpool.ConnectionFactory; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.IsTimeoutException; import com.netflix.astyanax.connectionpool.exceptions.ThrottledException; import com.netflix.astyanax.connectionpool.exceptions.UnknownException; import com.netflix.astyanax.connectionpool.impl.OperationResultImpl; public class TestConnectionFactory implements ConnectionFactory<TestClient> { private final ConnectionPoolConfiguration config; private final ExecutorService executor = Executors.newFixedThreadPool(10, new ThreadFactoryBuilder().setDaemon(true).build()); private final ConnectionPoolMonitor monitor; public TestConnectionFactory(ConnectionPoolConfiguration config, ConnectionPoolMonitor monitor) { this.config = config; this.monitor = monitor; } @Override public Connection<TestClient> createConnection( final HostConnectionPool<TestClient> pool) throws ThrottledException { return new Connection<TestClient>() { private ConnectionException lastException; private boolean isOpen = false; private AtomicLong operationCounter = new AtomicLong(); @Override public <R> OperationResult<R> execute(Operation<TestClient, R> op) throws ConnectionException { long startTime = System.nanoTime(); long latency = 0; // Execute the operation try { TestHostType type = TestHostType.get(getHost().getPort()); OperationResult<R> result = type.execute(pool, op); long now = System.nanoTime(); latency = now - startTime; pool.addLatencySample(latency, now); return new OperationResultImpl<R>(result.getHost(), result.getResult(), latency); } catch (Exception e) { long now = System.nanoTime(); latency = now - startTime; ConnectionException connectionException; if (!(e instanceof ConnectionException)) connectionException = new UnknownException(e); else connectionException = (ConnectionException)e; connectionException.setLatency(latency); if (!(connectionException instanceof IsTimeoutException)) { pool.addLatencySample(latency, now); } else { pool.addLatencySample(TimeUnit.NANOSECONDS.convert(config.getSocketTimeout(), TimeUnit.MILLISECONDS), System.nanoTime()); } lastException = connectionException; throw lastException; } } @Override public void close() { if (isOpen) { monitor.incConnectionClosed(getHost(), lastException); executor.submit(new Runnable() { @Override public void run() { final TestHostType type = TestHostType .get(getHost().getPort()); type.close(); isOpen = false; } }); } } @Override public HostConnectionPool<TestClient> getHostConnectionPool() { return pool; } @Override public ConnectionException getLastException() { return lastException; } @Override public void open() throws ConnectionException { TestHostType type = TestHostType.get(getHost().getPort()); try { type.open(0); isOpen = true; monitor.incConnectionCreated(getHost()); } catch (ConnectionException e) { lastException = e; e.setHost(getHost()); monitor.incConnectionCreateFailed(getHost(), e); throw e; } } @Override public void openAsync(final AsyncOpenCallback<TestClient> callback) { final Connection<TestClient> This = this; executor.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("MockConnectionFactory"); try { open(); callback.success(This); } catch (ConnectionException e) { callback.failure(This, e); } catch (Exception e) { callback.failure(This, new UnknownException( "Error openning async connection", e)); } } }); } @Override public long getOperationCount() { return operationCounter.get(); } @Override public Host getHost() { return pool.getHost(); } @Override public void setMetadata(String key, Object obj) { // TODO Auto-generated method stub } @Override public Object getMetadata(String key) { // TODO Auto-generated method stub return null; } @Override public boolean hasMetadata(String key) { // TODO Auto-generated method stub return false; } }; } }
7,635
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/test/TestOperation.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.test; import java.nio.ByteBuffer; import com.netflix.astyanax.connectionpool.ConnectionContext; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; public class TestOperation implements Operation<TestClient, String> { @Override public ByteBuffer getRowKey() { return null; } @Override public String getKeyspace() { return null; } @Override public Host getPinnedHost() { return null; } @Override public String execute(TestClient client, ConnectionContext state) throws ConnectionException { return "RESULT"; } }
7,636
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/SleepingRetryPolicy.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import org.apache.commons.lang.builder.ToStringBuilder; /** * Base sleeping retry policy with optional count limit. The sleep time * is delegated to the subclass. * * @author elandau * */ public abstract class SleepingRetryPolicy implements RetryPolicy { private final int maxAttempts; private int attempts; public SleepingRetryPolicy(int max) { this.maxAttempts = max; this.attempts = 0; } public boolean allowRetry() { if (maxAttempts == -1 || attempts < maxAttempts) { try { Thread.sleep(getSleepTimeMs()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } attempts++; return true; } return false; } public abstract long getSleepTimeMs(); @Override public void begin() { this.attempts = 0; } @Override public void success() { } @Override public void failure(Exception e) { } public int getAttemptCount() { return attempts; } @Deprecated public int getMax() { return getMaxAttemptCount(); } public int getMaxAttemptCount() { return maxAttempts; } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,637
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/RunOnce.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import org.apache.commons.lang.builder.ToStringBuilder; public class RunOnce implements RetryPolicy { public static RunOnce instance = new RunOnce(); public static RunOnce get() { return instance; } @Override public void begin() { } @Override public void success() { } @Override public void failure(Exception e) { } @Override public boolean allowRetry() { return false; } @Override public int getAttemptCount() { return 1; } @Override public RetryPolicy duplicate() { return RunOnce.get(); } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,638
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/RetryPolicy.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; /** * Interface for any retry logic * * @author elandau * */ public interface RetryPolicy { /** * Operation is starting */ void begin(); /** * Operation has completed successfully */ void success(); /** * Operation has failed */ void failure(Exception e); /** * Ask the policy if a retry is allowed. This may internally sleep * * @return */ boolean allowRetry(); /** * Return the number of attempts since begin was called * * @return */ int getAttemptCount(); /** * Duplicate this policy into a fresh instance * * @return */ RetryPolicy duplicate(); public interface RetryPolicyFactory { public RetryPolicy createRetryPolicy(); } }
7,639
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/RetryNTimes.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import org.apache.commons.lang.builder.ToStringBuilder; public class RetryNTimes implements RetryPolicy { private final int maxAttemptCount; private int attempts; public RetryNTimes(int maxAttemptCount) { this.maxAttemptCount = maxAttemptCount; this.attempts = 0; } @Override public void begin() { this.attempts = 0; } @Override public void success() { } @Override public void failure(Exception e) { } @Override public boolean allowRetry() { if (maxAttemptCount == -1 || attempts < maxAttemptCount) { attempts++; return true; } return false; } @Override public int getAttemptCount() { return attempts; } public int getMaxAttemptCount() { return maxAttemptCount; } @Override public RetryPolicy duplicate() { return new RetryNTimes(maxAttemptCount); } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,640
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/ExponentialBackoff.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import java.util.Random; import org.apache.commons.lang.builder.ToStringBuilder; /** * Unbounded exponential backoff will sleep a random number of intervals within an * exponentially increasing number of intervals. * * @author elandau * */ public class ExponentialBackoff extends SleepingRetryPolicy { private final int MAX_SHIFT = 30; private final Random random = new Random(); private final long baseSleepTimeMs; public ExponentialBackoff(long baseSleepTimeMs, int maxAttempts) { super(maxAttempts); this.baseSleepTimeMs = baseSleepTimeMs; } @Deprecated public ExponentialBackoff(int baseSleepTimeMs, int maxAttempts) { super(maxAttempts); this.baseSleepTimeMs = baseSleepTimeMs; } @Override public long getSleepTimeMs() { int attempt = this.getAttemptCount() + 1; if (attempt > MAX_SHIFT) { attempt = MAX_SHIFT; } return baseSleepTimeMs * Math.max(1, random.nextInt(1 << attempt)); } public long getBaseSleepTimeMs() { return baseSleepTimeMs; } @Override public RetryPolicy duplicate() { return new ExponentialBackoff(baseSleepTimeMs, getMaxAttemptCount()); } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,641
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/ConstantBackoff.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import org.apache.commons.lang.builder.ToStringBuilder; public class ConstantBackoff extends SleepingRetryPolicy { private final int sleepTimeMs; public ConstantBackoff(int sleepTimeMs, int max) { super(max); this.sleepTimeMs = sleepTimeMs; } @Override public long getSleepTimeMs() { return sleepTimeMs; } @Override public RetryPolicy duplicate() { return new ConstantBackoff(sleepTimeMs, getMax()); } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,642
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/IndefiniteRetry.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.retry; public class IndefiniteRetry implements RetryPolicy { private int counter = 1; @Override public void begin() { counter = 1; } @Override public void success() { } @Override public void failure(Exception e) { counter++; } @Override public boolean allowRetry() { return true; } @Override public int getAttemptCount() { return counter; } @Override public RetryPolicy duplicate() { return new IndefiniteRetry(); } }
7,643
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/BoundedExponentialBackoff.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.retry; import org.apache.commons.lang.builder.ToStringBuilder; /** * Bounded exponential backoff that will wait for no more than a provided max amount of time. * * The following examples show the maximum wait time for each attempt * ExponentalBackoff(250, 10) * 250 500 1000 2000 4000 8000 16000 32000 64000 128000 * * BoundedExponentialBackoff(250, 5000, 10) * 250 500 1000 2000 4000 5000 5000 5000 5000 5000 * * @author elandau * */ public class BoundedExponentialBackoff extends ExponentialBackoff { private final long maxSleepTimeMs; public BoundedExponentialBackoff(long baseSleepTimeMs, long maxSleepTimeMs, int max) { super(baseSleepTimeMs, max); this.maxSleepTimeMs = maxSleepTimeMs; } @Deprecated public BoundedExponentialBackoff(long baseSleepTimeMs, int maxSleepTimeMs, int max) { super(baseSleepTimeMs, max); this.maxSleepTimeMs = maxSleepTimeMs; } public long getSleepTimeMs() { return Math.min(maxSleepTimeMs, super.getSleepTimeMs()); } @Override public RetryPolicy duplicate() { return new BoundedExponentialBackoff(getBaseSleepTimeMs(), maxSleepTimeMs, getMaxAttemptCount()); } public long getMaxSleepTimeMs() { return maxSleepTimeMs; } public String toString() { return ToStringBuilder.reflectionToString(this); } }
7,644
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/retry/RunOnceRetryPolicyFactory.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.retry; import com.netflix.astyanax.retry.RetryPolicy.RetryPolicyFactory; public class RunOnceRetryPolicyFactory implements RetryPolicyFactory { @Override public RetryPolicy createRetryPolicy() { return new RunOnce(); } }
7,645
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/util/BlockingConcurrentWindowCounter.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.util; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class BlockingConcurrentWindowCounter { private final PriorityBlockingQueue<Integer> queue; private volatile int tail = 0; private volatile int head = 0; private final Semaphore semaphore; public BlockingConcurrentWindowCounter(int size) { this(size, 0); } public BlockingConcurrentWindowCounter(int size, int init) { this.queue = new PriorityBlockingQueue<Integer>(size); this.semaphore = new Semaphore(size); this.head = this.tail = init; } public int incrementAndGet() throws Exception { semaphore.acquire(); synchronized (this) { return head++; } } public int incrementAndGet(long timeout, TimeUnit unit) throws Exception { semaphore.tryAcquire(timeout, unit); synchronized (this) { return head++; } } public synchronized int release(int index) { int count = 0; this.queue.add(index); while (!this.queue.isEmpty() && this.queue.peek() == tail) { this.queue.remove(); tail++; count++; } if (count > 0) semaphore.release(count); return count; } }
7,646
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/util/TokenGenerator.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.util; import java.math.BigInteger; public class TokenGenerator { public static final BigInteger MINIMUM = new BigInteger("" + 0); public static final BigInteger MAXIMUM = new BigInteger("" + 2).pow(127); public static String initialToken(int size, int position) { return TokenGenerator.initialToken(size,position,MINIMUM,MAXIMUM); } public static String initialToken(int size, int position, BigInteger minInitialToken, BigInteger maxInitialToken ) { BigInteger decValue = minInitialToken; if (position != 0) decValue = maxInitialToken.multiply(new BigInteger("" + position)).divide(new BigInteger("" + size)); return decValue.toString(); } public static String tokenMinusOne(String payload) { BigInteger bigInt = new BigInteger(payload); // if zero rotate to the Maximum else minus one. if (bigInt.equals(MINIMUM)) bigInt = MAXIMUM; bigInt = bigInt.subtract(new BigInteger("1")); return bigInt.toString(); } public static BigInteger tokenDifference(BigInteger startToken, BigInteger endToken) { if (startToken.compareTo(endToken) < 0) { return endToken.subtract(startToken); } else { return endToken.add(MAXIMUM).subtract(startToken); } } public static BigInteger tokenDifference(String startToken, String endToken) { return tokenDifference(new BigInteger(startToken), new BigInteger(endToken)); } public static String getMaximumToken() { return MAXIMUM.toString(); } public static String getMinimumToken() { return MINIMUM.toString(); } }
7,647
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/util/TimeUUIDUtils.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.util; import java.nio.ByteBuffer; import java.util.UUID; import com.eaio.uuid.UUIDGen; import com.netflix.astyanax.Clock; import com.netflix.astyanax.clock.MicrosecondsSyncClock; /** * Utilitary class to generate TimeUUID (type 1) * * @author Patricio Echague (pechague@gmail.com) * */ public final class TimeUUIDUtils { static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; static final Clock microsClock = new MicrosecondsSyncClock(); /** * Gets a new and unique time uuid in milliseconds. It is useful to use in a * TimeUUIDType sorted column family. * * @return the time uuid */ public static java.util.UUID getUniqueTimeUUIDinMillis() { return new java.util.UUID(UUIDGen.newTime(), UUIDGen.getClockSeqAndNode()); } public static java.util.UUID getUniqueTimeUUIDinMicros() { return new java.util.UUID(createTimeFromMicros(microsClock.getCurrentTime()), UUIDGen.getClockSeqAndNode()); } /** * Gets a new time uuid using {@link ClockResolution#createClock()} as a * time generator. It is useful to use in a TimeUUIDType sorted column * family. * * @param clock * a ClockResolution * @return the time uuid */ public static java.util.UUID getTimeUUID(Clock clock) { return getTimeUUID(clock.getCurrentTime()); } /** * Gets a new time uuid based on <code>time<code>. * NOTE: this algorithm does not resolve duplicates. To avoid duplicates use * {@link getTimeUUID(ClockResolution clock)} with an implementaion that provides unique timestamp resolution, like * {@link MicrosecondsSyncClockResolution} * It is useful to use in a TimeUUIDType sorted column family. * * @param clock * a ClockResolution * @return the time uuid */ public static java.util.UUID getTimeUUID(long time) { return new java.util.UUID(createTime(time), UUIDGen.getClockSeqAndNode()); } public static java.util.UUID getMicrosTimeUUID(long time) { return new java.util.UUID(createTimeFromMicros(time), UUIDGen.getClockSeqAndNode()); } private static long createTime(long currentTime) { long time; // UTC time long timeToUse = (currentTime * 10000) + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH; // time low time = timeToUse << 32; // time mid time |= (timeToUse & 0xFFFF00000000L) >> 16; // time hi and version time |= 0x1000 | ((timeToUse >> 48) & 0x0FFF); // version 1 return time; } private static long createTimeFromMicros(long currentTime) { long time; // UTC time long timeToUse = (currentTime * 10) + NUM_100NS_INTERVALS_SINCE_UUID_EPOCH; // time low time = timeToUse << 32; // time mid time |= (timeToUse & 0xFFFF00000000L) >> 16; // time hi and version time |= 0x1000 | ((timeToUse >> 48) & 0x0FFF); // version 1 return time; } /** * Returns an instance of uuid. Useful for when you read out of cassandra * you are getting a byte[] that needs to be converted into a TimeUUID. * * @param uuid * the uuid * @return the java.util.uuid */ public static java.util.UUID toUUID(byte[] uuid) { return uuid(uuid, 0); } /** * Retrieves the time as long based on the byte[] representation of a UUID. * * @param uuid * byte[] uuid representation * @return a long representing the time */ public static long getTimeFromUUID(byte[] uuid) { return getTimeFromUUID(TimeUUIDUtils.toUUID(uuid)); } public static long getTimeFromUUID(UUID uuid) { return (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000; } public static long getMicrosTimeFromUUID(UUID uuid) { return (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10; } /** * As byte array. This method is often used in conjunction with @link * {@link #getTimeUUID()} * * @param uuid * the uuid * * @return the byte[] */ public static byte[] asByteArray(java.util.UUID uuid) { long msb = uuid.getMostSignificantBits(); long lsb = uuid.getLeastSignificantBits(); byte[] buffer = new byte[16]; for (int i = 0; i < 8; i++) { buffer[i] = (byte) (msb >>> 8 * (7 - i)); } for (int i = 8; i < 16; i++) { buffer[i] = (byte) (lsb >>> 8 * (7 - i)); } return buffer; } /** * Coverts a java.util.UUID into a ByteBuffer. * * @param uuid * a java.util.UUID * @return a ByteBuffer representaion of the param UUID */ public static ByteBuffer asByteBuffer(java.util.UUID uuid) { if (uuid == null) { return null; } return ByteBuffer.wrap(asByteArray(uuid)); } public static UUID uuid(byte[] uuid, int offset) { ByteBuffer bb = ByteBuffer.wrap(uuid, offset, 16); return new UUID(bb.getLong(), bb.getLong()); } /** * Converts a ByteBuffer containing a UUID into a java.util.UUID * * @param bb * a ByteBuffer containing a UUID * @return a java.util.UUID */ public static UUID uuid(ByteBuffer bb) { bb = bb.slice(); return new UUID(bb.getLong(), bb.getLong()); } }
7,648
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/util/Callables.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.util; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; public class Callables { /** * Create a callable that waits on a barrier before starting execution * @param barrier * @param callable * @return */ public static <T> Callable<T> decorateWithBarrier(CyclicBarrier barrier, Callable<T> callable) { return new BarrierCallableDecorator<T>(barrier, callable); } }
7,649
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/util/BarrierCallableDecorator.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.util; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; public class BarrierCallableDecorator<T> implements Callable<T> { public CyclicBarrier barrier; public Callable<T> callable; public BarrierCallableDecorator(CyclicBarrier barrier, Callable<T> callable) { this.barrier = barrier; this.callable = callable; } @Override public T call() throws Exception { barrier.await(); return callable.call(); } }
7,650
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/partitioner/Partitioner.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.partitioner; import java.nio.ByteBuffer; import java.util.List; import com.netflix.astyanax.connectionpool.TokenRange; /** * Base interface for token partitioning utilities * * @author elandau * */ public interface Partitioner { /** * @return Return the smallest token in the token space */ String getMinToken(); /** * @return Return the largest token in the token space */ String getMaxToken(); /** * @return Return the token immediately before this one */ String getTokenMinusOne(String token); /** * Split the token range into N equal size segments and return the start token * of each segment * * @param first * @param last * @param count */ List<TokenRange> splitTokenRange(String first, String last, int count); /** * Split the entire token range into 'count' equal size segments * @param count */ List<TokenRange> splitTokenRange(int count); /** * Return the token for the specifie key * @param key */ String getTokenForKey(ByteBuffer key); }
7,651
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyOperationFilterFactory.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.OperationFilterFactory; public class EmptyOperationFilterFactory implements OperationFilterFactory { private final static OperationFilterFactory instance = new EmptyOperationFilterFactory(); public static OperationFilterFactory getInstance() { return instance; } @Override public <R, CL> Operation<R, CL> attachFilter(Operation<R, CL> operation) { return operation; } }
7,652
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyNodeDiscoveryImpl.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import org.joda.time.DateTime; import com.netflix.astyanax.connectionpool.NodeDiscovery; public class EmptyNodeDiscoveryImpl implements NodeDiscovery { private static final EmptyNodeDiscoveryImpl instance = new EmptyNodeDiscoveryImpl(); private EmptyNodeDiscoveryImpl() { } public static EmptyNodeDiscoveryImpl get() { return instance; } @Override public void start() { } @Override public void shutdown() { } @Override public DateTime getLastRefreshTime() { return null; } @Override public long getRefreshCount() { return 0; } @Override public long getErrorCount() { return 0; } @Override public Exception getLastException() { return null; } @Override public String getRawHostList() { return ""; } public String toString() { return "EmptyNodeDiscovery"; } }
7,653
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyConnectionPoolMonitor.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.HostStats; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EmptyConnectionPoolMonitor implements ConnectionPoolMonitor { private static final Logger LOGGER = LoggerFactory.getLogger(EmptyConnectionPoolMonitor.class); private static EmptyConnectionPoolMonitor instance = new EmptyConnectionPoolMonitor(); public static EmptyConnectionPoolMonitor getInstance() { return instance; } private EmptyConnectionPoolMonitor() { } public String toString() { return "EmptyConnectionPoolMonitor[]"; } @Override public void incOperationSuccess(Host host, long latency) { } @Override public void incConnectionBorrowed(Host host, long delay) { } @Override public void incConnectionReturned(Host host) { } @Override public void onHostAdded(Host host, HostConnectionPool<?> pool) { LOGGER.info(String.format("Added host " + host)); } @Override public void onHostRemoved(Host host) { LOGGER.info(String.format("Remove host " + host)); } @Override public void onHostDown(Host host, Exception reason) { LOGGER.warn(String.format("Downed host " + host + " reason=\"" + reason + "\"")); } @Override public void onHostReactivated(Host host, HostConnectionPool<?> pool) { LOGGER.info(String.format("Reactivating host " + host)); } @Override public void incFailover(Host host, Exception e) { } @Override public void incConnectionCreated(Host host) { } @Override public void incConnectionCreateFailed(Host host, Exception e) { } @Override public void incOperationFailure(Host host, Exception e) { } @Override public void incConnectionClosed(Host host, Exception e) { } @Override public Map<Host, HostStats> getHostStats() { return null; } @Override public long getOperationFailureCount() { return 0; } @Override public long getOperationSuccessCount() { return 0; } @Override public long getConnectionCreatedCount() { return 0; } @Override public long getConnectionClosedCount() { return 0; } @Override public long getConnectionCreateFailedCount() { return 0; } @Override public long getConnectionBorrowedCount() { return 0; } @Override public long getConnectionReturnedCount() { return 0; } @Override public long getPoolExhaustedTimeoutCount() { return 0; } @Override public long getOperationTimeoutCount() { return 0; } @Override public long getFailoverCount() { return 0; } @Override public long getNoHostCount() { return 0; } @Override public long getSocketTimeoutCount() { return 0; } @Override public long getUnknownErrorCount() { return 0; } @Override public long getBadRequestCount() { return 0; } @Override public long notFoundCount() { return 0; } @Override public long getInterruptedCount() { return 0; } @Override public long getHostCount() { return 0; } @Override public long getHostAddedCount() { return 0; } @Override public long getHostRemovedCount() { return 0; } @Override public long getHostDownCount() { return 0; } @Override public long getTransportErrorCount() { return 0; } @Override public long getHostActiveCount() { return 0; } }
7,654
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyPartitioner.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.shallows; import java.nio.ByteBuffer; import java.util.List; import com.netflix.astyanax.connectionpool.TokenRange; import com.netflix.astyanax.partitioner.Partitioner; public class EmptyPartitioner implements Partitioner { @Override public String getMinToken() { // TODO Auto-generated method stub return null; } @Override public String getMaxToken() { // TODO Auto-generated method stub return null; } @Override public String getTokenMinusOne(String token) { // TODO Auto-generated method stub return null; } @Override public List<TokenRange> splitTokenRange(String first, String last, int count) { // TODO Auto-generated method stub return null; } @Override public List<TokenRange> splitTokenRange(int count) { // TODO Auto-generated method stub return null; } @Override public String getTokenForKey(ByteBuffer key) { // TODO Auto-generated method stub return null; } }
7,655
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyBadHostDetectorImpl.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import com.netflix.astyanax.connectionpool.BadHostDetector; public class EmptyBadHostDetectorImpl implements BadHostDetector { private static EmptyBadHostDetectorImpl instance = new EmptyBadHostDetectorImpl(); public static EmptyBadHostDetectorImpl getInstance() { return instance; } private EmptyBadHostDetectorImpl() { } @Override public Instance createInstance() { return new Instance() { @Override public boolean addTimeoutSample() { return false; } }; } @Override public void removeInstance(Instance instance) { } }
7,656
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyIterator.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import java.util.Iterator; import java.util.NoSuchElementException; @SuppressWarnings("rawtypes") public class EmptyIterator implements Iterator { public static final Iterator Instance = new EmptyIterator(); @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new NoSuchElementException(); } }
7,657
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyLatencyScoreStrategyImpl.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.shallows; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.LatencyScoreStrategy; public class EmptyLatencyScoreStrategyImpl implements LatencyScoreStrategy { public static EmptyLatencyScoreStrategyImpl instance = new EmptyLatencyScoreStrategyImpl(); public static EmptyLatencyScoreStrategyImpl get() { return instance; } @Override public Instance createInstance() { return new Instance() { @Override public void addSample(long sample) { } @Override public double getScore() { return 0; } @Override public void reset() { } @Override public void update() { } }; } @Override public void removeInstance(Instance instance) { } @Override public void start(Listener listener) { } @Override public void shutdown() { } @Override public void update() { } @Override public void reset() { } @Override public <CL> List<HostConnectionPool<CL>> sortAndfilterPartition(List<HostConnectionPool<CL>> pools, AtomicBoolean prioritized) { prioritized.set(false); return pools; } public String toString() { return "EmptyLatencyScoreStrategy[]"; } @Override public int getUpdateInterval() { return 0; } @Override public int getResetInterval() { return 0; } @Override public double getScoreThreshold() { return 10.0; } @Override public int getBlockedThreshold() { return 100; } @Override public double getKeepRatio() { return 1.0; } }
7,658
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/shallows/EmptyOperationTracer.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.shallows; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.tracing.AstyanaxContext; import com.netflix.astyanax.tracing.OperationTracer; public class EmptyOperationTracer implements OperationTracer { @Override public AstyanaxContext getAstyanaxContext() { // TODO Auto-generated method stub return null; } @Override public <CL, R> void onCall(AstyanaxContext ctx, Operation<CL, R> op) { // TODO Auto-generated method stub } @Override public <CL, R> void onSuccess(AstyanaxContext ctx, Operation<CL, R> op) { // TODO Auto-generated method stub } @Override public <CL, R> void onException(AstyanaxContext ctx, Operation<CL, R> op, Throwable t) { // TODO Auto-generated method stub } }
7,659
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/annotations/Component.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.ElementType; /** * Annotation for components of a composite type. * * @author elandau * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Component { int ordinal() default -1; }
7,660
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionPoolConfiguration.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import com.netflix.astyanax.AuthenticationCredentials; import com.netflix.astyanax.connectionpool.impl.HostSelectorStrategy; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.tracing.OperationTracer; public interface ConnectionPoolConfiguration { /** * TODO */ LatencyScoreStrategy getLatencyScoreStrategy(); /** * TODO */ BadHostDetector getBadHostDetector(); /** * @return Data port to be used when no port is specified to a list of seeds or when * doing a ring describe since the ring describe does not include a host */ int getPort(); /** * @return Unique name assigned to this connection pool */ String getName(); /** * @return Maximum number of connections to allocate for a single host's pool */ int getMaxConnsPerHost(); /** * @return Initial number of connections created when a connection pool is started */ int getInitConnsPerHost(); /** * @return Maximum number of connections in the pool, not used by all connection * pool implementations */ int getMaxConns(); /** * @return Maximum amount of time to wait for a connection to free up when a * connection pool is exhausted. * * @return */ int getMaxTimeoutWhenExhausted(); /** * @return Get the max number of failover attempts */ int getMaxFailoverCount(); /** * @return Return the backoff strategy to use. * * @see com.netflix.astyanax.connectionpool.RetryBackoffStrategy */ RetryBackoffStrategy getRetryBackoffStrategy(); /** * @return Return the host selector strategy to use. * * @see com.netflix.astyanax.connectionpool.impl.HostSelectorStrategy */ HostSelectorStrategy getHostSelectorStrategy(); /** * @return List of comma delimited host:port combinations. If port is not provided * then getPort() will be used by default. This list must contain at least * one valid host other it would not be possible to do a ring describe. */ String getSeeds(); /** * @return Return a list of Host objects from the list of seeds returned by * getSeeds(). This list must contain at least one valid host other it would * not be possible to do a ring describe. */ List<Host> getSeedHosts(); /** * @return Return local datacenter name. */ public String getLocalDatacenter(); /** * @return Socket read/write timeout */ int getSocketTimeout(); /** * @return Socket connect timeout */ int getConnectTimeout(); /** * @return Window size for limiting the number of connection open requests */ int getConnectionLimiterWindowSize(); /** * @return Maximum number of connection attempts in a given window */ int getConnectionLimiterMaxPendingCount(); /** * @return Latency samples window size for scoring algorithm */ int getLatencyAwareWindowSize(); /** * @return Sentinel compare value for Phi Accrual */ float getLatencyAwareSentinelCompare(); /** * @return Return the threshold after which a host will not be considered good * enough for executing operations. */ float getLatencyAwareBadnessThreshold(); /** * @return Return the threshold for disabling hosts that have nBlockedThreads more than * the least blocked host. The idea here is to quarantine hosts that are slow to respond * and free up connections. */ int getBlockedThreadThreshold(); /** * @return Return the ratio for keeping a minimum number of hosts in the pool even if they are slow * or are blocked. For example, a ratio of 0.75 with a connection pool of 12 hosts will * ensure that no more than 4 hosts can be quaratined. */ float getMinHostInPoolRatio(); /** * TODO */ int getLatencyAwareUpdateInterval(); /** * TODO */ int getLatencyAwareResetInterval(); /** * @return Maximum number of pending connect attempts per host */ int getMaxPendingConnectionsPerHost(); /** * @return Get max number of blocked clients for a host. */ int getMaxBlockedThreadsPerHost(); /** * @return Shut down a host if it times out too many time within this window */ int getTimeoutWindow(); /** * @return Number of allowed timeouts within getTimeoutWindow() milliseconds */ int getMaxTimeoutCount(); /** * TODO */ int getRetrySuspendWindow(); /** * TODO */ int getRetryMaxDelaySlice(); /** * TODO */ int getRetryDelaySlice(); /** * @return Maximum allowed operations per connections before forcing the connection * to close */ int getMaxOperationsPerConnection(); /** * @return Can return null if no login required */ AuthenticationCredentials getAuthenticationCredentials(); /** * @return Return factory that will wrap an operation with filters, such as logging filters * and simulation filters */ OperationFilterFactory getOperationFilterFactory(); /** * @return Return tracing factory that helps to trace a request */ OperationTracer getOperationTracer(); /** * @return Get the partitioner used to convert row keys to TOKEN */ Partitioner getPartitioner(); /** * @return Retrieve a context to determine if connections should be made using SSL. */ SSLConnectionContext getSSLConnectionContext(); /** * @return Return executor service used for maintenance tasks. This pool is used for internal * operations that update stats such as token aware scores. Threads in this pool * and not expected to block on I/O and the pool can therefore be very small */ ScheduledExecutorService getMaintainanceScheduler(); /** * @return Return executor service used to reconnect hosts. Keep in mind that the threads * may be blocked for an extended duration while trying to reconnect to a downed host */ ScheduledExecutorService getHostReconnectExecutor(); /** * Initialization prior to starting the connection pool */ void initialize(); /** * Shutdown after stopping the connection pool */ void shutdown(); }
7,661
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/NodeDiscovery.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import org.joda.time.DateTime; /** * Interface for a module that periodically updates the nodes in a connection * pool. * * @author elandau * */ public interface NodeDiscovery { /** * Start the node discovery thread */ void start(); /** * Stop the node discovery thread */ void shutdown(); /** * @return Get the last refresh time in the discovery thread */ DateTime getLastRefreshTime(); /** * @return Get the number of refreshes */ long getRefreshCount(); /** * @return Get total number of errors encountered during a refresh */ long getErrorCount(); /** * @return Get the last exception that was encountered */ Exception getLastException(); /** * @return Get the raw list of nodes from the underlying refresh mechanism */ String getRawHostList(); }
7,662
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/JmxConnectionPoolMonitor.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; import org.apache.commons.lang.StringUtils; import com.google.common.base.Function; import com.google.common.collect.Lists; /** * MBean monitoring for a connection pool * * @author elandau * */ public class JmxConnectionPoolMonitor implements JmxConnectionPoolMonitorMBean { private final ConnectionPool<?> pool; private final static int DEFAULT_PORT = 7102; public JmxConnectionPoolMonitor(ConnectionPool<?> pool) { this.pool = pool; } @Override public boolean addHost(String host) { return pool.addHost(new Host(host, DEFAULT_PORT), true); } @Override public boolean removeHost(String host) { return pool.removeHost(new Host(host, DEFAULT_PORT), true); } @Override public boolean isHostUp(String host) { return pool.isHostUp(new Host(host, DEFAULT_PORT)); } @Override public boolean hasHost(String host) { return pool.hasHost(new Host(host, DEFAULT_PORT)); } @Override public String getActiveHosts() { return StringUtils.join(Lists.transform(pool.getActivePools(), new Function<HostConnectionPool<?>, String>() { @Override public String apply(HostConnectionPool<?> host) { return host.getHost().getName(); } }), ","); } }
7,663
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/NodeDiscoveryMonitor.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; public class NodeDiscoveryMonitor implements NodeDiscoveryMonitorMBean { private NodeDiscovery discovery; public NodeDiscoveryMonitor(NodeDiscovery discovery) { this.discovery = discovery; } @Override public long getRefreshCount() { return discovery.getRefreshCount(); } @Override public long getErrorCount() { return discovery.getErrorCount(); } @Override public String getLastException() { Exception e = discovery.getLastException(); return (e != null) ? e.getMessage() : "none"; } @Override public String getLastRefreshTime() { return discovery.getLastRefreshTime().toString(); } @Override public String getRawHostList() { return discovery.getRawHostList(); } }
7,664
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/OperationFilterFactory.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; public interface OperationFilterFactory { <R, CL> Operation<R, CL> attachFilter(Operation<R,CL> operation); }
7,665
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionPool.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.List; import java.util.Collection; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.OperationException; import com.netflix.astyanax.connectionpool.impl.Topology; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.retry.RetryPolicy; /** * Base interface for a pool of connections. A concrete connection pool will * track hosts in a cluster. * * @author elandau * @param <CL> */ public interface ConnectionPool<CL> { /** * Add a host to the connection pool. * * @param host * @returns True if host was added or false if host already exists * @throws ConnectionException */ boolean addHost(Host host, boolean refresh); /** * Remove a host from the connection pool. Any pending connections will be * allowed to complete * * @returns True if host was removed or false if host does not exist * @param host */ boolean removeHost(Host host, boolean refresh); /** * @return Return true if the host is up * @param host */ boolean isHostUp(Host host); /** * @return Return true if host is contained within the connection pool * @param host */ boolean hasHost(Host host); /** * @return Return list of active hosts on which connections can be created */ List<HostConnectionPool<CL>> getActivePools(); /** * @return Get all pools */ List<HostConnectionPool<CL>> getPools(); /** * Set the complete set of hosts in the ring * @param hosts */ void setHosts(Collection<Host> hosts); /** * @return Return an immutable connection pool for this host * @param host */ HostConnectionPool<CL> getHostPool(Host host); /** * Execute an operation with failover within the context of the connection * pool. The operation will only fail over for connection pool errors and * not application errors. * * @param <R> * @param op * @param token * @throws ConnectionException * @throws OperationException */ <R> OperationResult<R> executeWithFailover(Operation<CL, R> op, RetryPolicy retry) throws ConnectionException, OperationException; /** * Shut down the connection pool and terminate all existing connections */ void shutdown(); /** * Setup the connection pool and start any maintenance threads */ void start(); /** * @return Return the internal topology which represents the partitioning of data across hosts in the pool */ Topology<CL> getTopology(); /** * @return Return the partitioner used by this pool. */ Partitioner getPartitioner(); }
7,666
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/LatencyScoreStrategy.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public interface LatencyScoreStrategy { public interface Listener { void onUpdate(); void onReset(); } /** * Single instance of this strategy associated with an endpoint */ public interface Instance { /** * Add a single latency sample * * @param sample * @param now */ void addSample(long sample); /** * @return Get the cached score for this endpoint */ double getScore(); /** * Reset the score and any internal stats */ void reset(); /** * Update the score */ void update(); } /** * @return Return interval for updating the scores */ int getUpdateInterval(); /** * @return Return interval for clearing scores */ int getResetInterval(); /** * @return Return threshold after which hosts will be excluded if their score * is getScoreThreshold() times larger than the best performing node */ double getScoreThreshold(); /** * @return Return threshold of blocked connections after which a host is excluded */ int getBlockedThreshold(); /** * @return Get ratio for calculating minimum number of hosts that most remain in the pool */ double getKeepRatio(); /** * Update all instance scores */ void update(); /** * Reset all instance scores */ void reset(); /** * Create a new instance to associate with an endpoint * * @return */ Instance createInstance(); /** * Remove the instance for an endpoint that is no longer being tracked * * @param instance */ void removeInstance(Instance instance); /** * Start updating stats for instances created using createInstance. This * usually spawns an update thread as well as a reset thread operating at * configurable intervals * * @param listener */ void start(Listener listener); /** * Shutdown the threads created by calling start() */ void shutdown(); /** * Sorts and filters a list of hosts by looking at their up state and score. * * @param <CL> * @param pools * @param prioritized * - Will be set to true if the filtered data is prioritized or * not. If prioritized then the first element should be selected * from by the load balancing strategy. Otherwise round robin * could be used. * @return */ <CL> List<HostConnectionPool<CL>> sortAndfilterPartition(List<HostConnectionPool<CL>> pools, AtomicBoolean prioritized); }
7,667
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/TokenRange.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.List; /** * Represents a contiguous range of tokens. * * @author elandau * */ public interface TokenRange { String getStartToken(); String getEndToken(); List<String> getEndpoints(); }
7,668
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/HostConnectionPool.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool; /** * Interface for a pool of {@link Connection}(s) for a single {@link Host} * * The interface prescribes certain key features required by clients of this class, such as * <ol> * <li> Basic connection pool life cycle management such as prime connections (init) and shutdown </li> <br/> * * <li> Basic {@link Connection} life cycle management such as borrow / return / close / markAsDown </li> <br/> * * <li> Tracking the {@link Host} associated with the connection pool. </li> <br/> * * <li> Visibility into the status of the connection pool and it's connections. * <ol> * <li> Tracking status of pool - isConnecting / isActive / isShutdown </li> * <li> Tracking basic counters for connections - active / pending / blocked / idle / busy / closed etc </li> * <li> Tracking latency scores for connections to this host. </li> * <li> Tracking failures for connections to this host. </li> * </ol> * </ol> * * This class is intended to be used within a collection of {@link HostConnectionPool} tracked by a * {@link ConnectionPool} for all the {@link Host}(s) within a cassandra cluster. * * @see {@link SimpleHostConnectionPool} for sample implementations of this class. * @see {@link ConnectionPool} for references to this class. * * @author elandau * * @param <CL> */ public interface HostConnectionPool<CL> { /** * Borrow a connection from the host. May create a new connection if one is * not available. * * @param timeout * @return A borrowed connection. Connection must be returned either by calling returnConnection * or closeConnection. * @throws ConnectionException */ Connection<CL> borrowConnection(int timeout) throws ConnectionException; /** * Return a connection to the host's pool. May close the connection if the * pool is down or the last exception on the connection is determined to be * fatal. * * @param connection * @return True if connection was closed */ boolean returnConnection(Connection<CL> connection); /** * Close this connection and update internal state * * @param connection */ boolean closeConnection(Connection<CL> connection); /** * Shut down the host so no more connections may be created when * borrowConnections is called and connections will be terminated when * returnConnection is called. */ void markAsDown(ConnectionException reason); /** * Completely shut down this connection pool as part of a client shutdown */ void shutdown(); /** * Create numConnections new connections and add them to the * * @throws ConnectionException * @throws InterruptedException * @returns Actual number of connections created */ int primeConnections(int numConnections) throws ConnectionException, InterruptedException; /** * @return Get the host to which this pool is associated */ Host getHost(); /** * @return Get number of open connections including any that are currently borrowed * and those that are currently idel */ int getActiveConnectionCount(); /** * @return Get the number of pending connection open attempts */ int getPendingConnectionCount(); /** * @return Get number of threads blocked waiting for a free connection */ int getBlockedThreadCount(); /** * @return Return the number of idle active connections. These are connections that * can be borrowed immediatley without having to make a new connection to * the remote server. */ int getIdleConnectionCount(); /** * @return Get number of currently borrowed connections */ int getBusyConnectionCount(); /** * @return Return true if the pool is marked as down and is trying to reconnect */ boolean isReconnecting(); /** * @return Return true if the pool is active. */ boolean isActive(); /** * @return Return true if the has been shut down and is no longer accepting traffic. */ boolean isShutdown(); /** * @return Return implementation specific score to be used by weighted pool * selection algorithms */ double getScore(); /** * Add a single latency sample after an operation on a connection belonging * to this pool * * @param lastLatency */ void addLatencySample(long lastLatency, long now); /** * @return Get total number of connections opened since the pool was created */ int getOpenedConnectionCount(); /** * @return Get the total number of failed connection open attempts */ int getFailedOpenConnectionCount(); /** * @return Get total number of connections closed */ int getClosedConnectionCount(); /** * @return Get number of errors since the last successful operation */ int getErrorsSinceLastSuccess(); /** * @return Return the number of open connection attempts */ int getConnectAttemptCount(); }
7,669
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/Operation.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.nio.ByteBuffer; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * Callback interface to perform an operation on a client associated with a * connection pool's connection resource * * @author elandau * * @param <C> * @param <R> */ public interface Operation<CL, R> { /** * Execute the operation on the client object and return the results. * * @param client - The client object * @param state - State and metadata specific to the connection * @return * @throws ConnectionException */ R execute(CL client, ConnectionContext state) throws ConnectionException; /** * Return the unique key on which the operation is performed or null if the * operation is performed on multiple keys. * * @return */ ByteBuffer getRowKey(); /** * Return keyspace for this operation. Return null if using the current * keyspace, or a keyspace is not needed for the operation. * * @return */ String getKeyspace(); /** * Return the host to run on or null to select a host using the load * blancer. Failover is disabled for this scenario. * * @param host * @return */ Host getPinnedHost(); }
7,670
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/RetryBackoffStrategy.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; /** * Strategy used to calculate how much to back off for each subsequent attempt * to reconnect to a downed host * * @author elandau * */ public interface RetryBackoffStrategy { public interface Callback { boolean tryConnect(int attemptCount); } public interface Instance { /** * Start the reconnect process */ void begin(); /** * Called when a connection was established successfully */ void success(); /** * @return Return the next backoff delay in the strategy */ long getNextDelay(); /** * Suspend the host for being bad (i.e. timing out too much) */ void suspend(); /** * @return Number of failed attempts */ int getAttemptCount(); }; /** * Create an instance of the strategy for a single host */ Instance createInstance(); }
7,671
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionPoolMonitor.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.Map; /** * Monitoring interface to receive notification of pool events. A concrete * monitor will make event stats available to a monitoring application and may * also log events to a log file. * * @author elandau */ public interface ConnectionPoolMonitor { /** * Errors trying to execute an operation. * * @param reason * @param host */ void incOperationFailure(Host host, Exception reason); long getOperationFailureCount(); /** * An operation failed but the connection pool will attempt to fail over to * another host/connection. */ void incFailover(Host host, Exception reason); long getFailoverCount(); /** * Succeeded in executing an operation * * @param host * @param latency */ void incOperationSuccess(Host host, long latency); long getOperationSuccessCount(); /** * Created a connection successfully */ void incConnectionCreated(Host host); long getConnectionCreatedCount(); /** * Closed a connection * * @param reason * TODO: Make the host available to this */ void incConnectionClosed(Host host, Exception reason); long getConnectionClosedCount(); /** * Attempt to create a connection failed * * @param host * @param reason */ void incConnectionCreateFailed(Host host, Exception reason); long getConnectionCreateFailedCount(); /** * Incremented for each connection borrowed * * @param host * Host from which the connection was borrowed * @param delay * Time spent in the connection pool borrowing the connection */ void incConnectionBorrowed(Host host, long delay); long getConnectionBorrowedCount(); /** * Incremented for each connection returned. * * @param host * Host to which connection is returned */ void incConnectionReturned(Host host); long getConnectionReturnedCount(); /** * Timeout trying to get a connection from the pool */ long getPoolExhaustedTimeoutCount(); /** * Timeout waiting for a response from the cluster */ long getOperationTimeoutCount(); /** * @return Count of socket timeouts trying to execute an operation */ long getSocketTimeoutCount(); /** * @return Get number of unknown errors */ long getUnknownErrorCount(); /** * @return Get number of invalid requests (i.e. bad argument values) */ long getBadRequestCount(); /** * @return Count of times no hosts at all were available to execute an operation. */ long getNoHostCount(); /** * @return Tracks the number of column not found error */ long notFoundCount(); /** * @return Number of times operations were cancelled */ long getInterruptedCount(); /** * @return Number of times transport errors occurred */ long getTransportErrorCount(); /** * @return Return the number of hosts in the pool */ long getHostCount(); /** * Return the number of times a host was added to the pool. This * number will be incremented multiple times if the same hosts is * added and removed multiple times. * A constantly increating number of host added and host removed * may indicate a problem with the host discovery service */ long getHostAddedCount(); /** * Return the number of times any host was removed to the pool. This * number will be incremented multiple times if the same hosts is * added and removed multiple times. * A constantly increating number of host added and host removed * may indicate a problem with the host discovery service */ long getHostRemovedCount(); /** * @return Return the number of times any host was marked as down. */ long getHostDownCount(); /** * @return Return the number of active hosts */ long getHostActiveCount(); /** * A host was added and given the associated pool. The pool is immutable and * can be used to get info about the number of open connections * * @param host * @param pool */ void onHostAdded(Host host, HostConnectionPool<?> pool); /** * A host was removed from the pool. This is usually called when a downed * host is removed from the ring. * * @param host */ void onHostRemoved(Host host); /** * A host was identified as downed. * * @param host * @param reason * Exception that caused the host to be identified as down */ void onHostDown(Host host, Exception reason); /** * A host was reactivated after being marked down * * @param host * @param pool */ void onHostReactivated(Host host, HostConnectionPool<?> pool); /** * @return Return a mapping of all hosts and their statistics */ Map<Host, HostStats> getHostStats(); }
7,672
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/RateLimiter.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; /** * Very very simple interface for a rate limiter. The basic idea is that clients * will call check() to determine if an operation may be performed. The concrete * rate limiter will update its internal state for each call to check * * @author elandau */ public interface RateLimiter { boolean check(); boolean check(long currentTimeMillis); }
7,673
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionPoolProxy.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.OperationException; import com.netflix.astyanax.connectionpool.impl.Topology; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.retry.RetryPolicy; public class ConnectionPoolProxy<T> implements ConnectionPool<T> { private static final Logger Logger = LoggerFactory.getLogger(ConnectionPoolProxy.class); private AtomicReference<SeedHostListener> listener = new AtomicReference<SeedHostListener>(null); private AtomicReference<Collection<Host>> lastHostList = new AtomicReference<Collection<Host>>(null); private final ConnectionPoolConfiguration cpConfig; private final ConnectionPoolMonitor monitor; public ConnectionPoolProxy(ConnectionPoolConfiguration cpConfig, ConnectionFactory<T> connectionFactory, ConnectionPoolMonitor monitor) { this.cpConfig = cpConfig; this.monitor = monitor; } public ConnectionPoolConfiguration getConnectionPoolConfiguration() { return cpConfig; } public ConnectionPoolMonitor getConnectionPoolMonitor() { return monitor; } @Override public void setHosts(Collection<Host> hosts) { if (hosts != null) { Logger.info("Setting hosts for listener here: " + listener.getClass().getName() + " " + hosts); lastHostList.set(hosts); } if (listener.get() != null) { Logger.info("Setting hosts for listener: " + listener.getClass().getName() + " " + hosts); listener.get().setHosts(hosts, cpConfig.getPort()); } } public Collection<Host> getHosts() { return lastHostList.get(); } public interface SeedHostListener { public void setHosts(Collection<Host> hosts, int port); public void shutdown(); } public void addListener(SeedHostListener listener) { this.listener.set(listener); if (this.lastHostList.get() != null) { this.listener.get().setHosts(lastHostList.get(), cpConfig.getPort()); } } @Override public boolean addHost(Host host, boolean refresh) { // TODO Auto-generated method stub return false; } @Override public boolean removeHost(Host host, boolean refresh) { // TODO Auto-generated method stub return false; } @Override public boolean isHostUp(Host host) { // TODO Auto-generated method stub return false; } @Override public boolean hasHost(Host host) { // TODO Auto-generated method stub return false; } @Override public List<HostConnectionPool<T>> getActivePools() { // TODO Auto-generated method stub return null; } @Override public List<HostConnectionPool<T>> getPools() { // TODO Auto-generated method stub return null; } @Override public HostConnectionPool<T> getHostPool(Host host) { // TODO Auto-generated method stub return null; } @Override public <R> OperationResult<R> executeWithFailover(Operation<T, R> op, RetryPolicy retry) throws ConnectionException, OperationException { // TODO Auto-generated method stub return null; } @Override public void shutdown() { if (this.lastHostList.get() != null) { this.listener.get().shutdown(); } } @Override public void start() { // TODO Auto-generated method stub } @Override public Topology<T> getTopology() { // TODO Auto-generated method stub return null; } @Override public Partitioner getPartitioner() { // TODO Auto-generated method stub return null; } }
7,674
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/Connection.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * Interface to an instance of a connection on a host. * * @author elandau * * @param <CL> */ public interface Connection<CL> extends ConnectionContext { public interface AsyncOpenCallback<CL> { void success(Connection<CL> conn); void failure(Connection<CL> conn, ConnectionException e); } /** * Execute an operation on the connection and return a result * * @param <R> * @param op * @throws ConnectionException */ <R> OperationResult<R> execute(Operation<CL, R> op) throws ConnectionException; /** * Shut down the connection. isOpen() will now return false. */ void close(); /** * @return Get the parent host connection pool. */ HostConnectionPool<CL> getHostConnectionPool(); /** * @return Get the host for this connection */ Host getHost(); /** * @return Get the last exception that caused the connection to be closed */ ConnectionException getLastException(); /** * Open a new connection * * @throws ConnectionException */ void open() throws ConnectionException; /** * Open a connection asynchronously and call the callback on connection or * failure * * @param callback */ void openAsync(AsyncOpenCallback<CL> callback); /** * @return Number of operations performed on this connections since it was opened */ long getOperationCount(); }
7,675
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/BadHostDetector.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; /** * Interface for algorithm to detect when a host is considered down. Once a host * is considered to be down it will be added to the retry service * * @author elandau * */ public interface BadHostDetector { public interface Instance { /** * Add a timeout sample and return false if the host should be * quarantined * * @return true to quarantine or false to continue using this host */ boolean addTimeoutSample(); } Instance createInstance(); void removeInstance(Instance instance); }
7,676
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/NodeDiscoveryType.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; public enum NodeDiscoveryType { /** * Discover nodes exclusively from doing a ring describe */ RING_DESCRIBE, /** * Discover nodes exclusively from an external node discovery service */ DISCOVERY_SERVICE, /** * Intersect ring describe and nodes from an external service. This solve * the multi-region ring describe problem where ring describe returns nodes * from other regions. */ TOKEN_AWARE, /** * Use only nodes in the list of seeds */ NONE }
7,677
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/OperationResult.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.concurrent.TimeUnit; public interface OperationResult<R> { /** * @return Get the host on which the operation was performed */ Host getHost(); /** * @return Get the result data */ R getResult(); /** * @return Return the length of time to perform the operation. Does not include * connection pool overhead. This time is in nanoseconds */ long getLatency(); /** * @return Return the length of time to perform the operation to the remote service. Does not include * connection pool overhead. * * @param units */ long getLatency(TimeUnit units); /** * @return Return the number of times the operation had to be retried. This includes * retries for aborted connections. */ int getAttemptsCount(); /** * Set the number of attempts executing this connection * @param count */ void setAttemptsCount(int count); }
7,678
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/SSLConnectionContext.java
/******************************************************************************* * Copyright 2013 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.util.Arrays; import java.util.List; public class SSLConnectionContext { public static final String DEFAULT_SSL_PROTOCOL = "TLS"; public static final List<String> DEFAULT_SSL_CIPHER_SUITES = Arrays.asList("TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"); private final String sslProtocol; private final List<String> sslCipherSuites; private final String sslTruststore; private final String sslTruststorePassword; public SSLConnectionContext(String sslTruststore, String sslTruststorePassword){ this(sslTruststore, sslTruststorePassword, DEFAULT_SSL_PROTOCOL, DEFAULT_SSL_CIPHER_SUITES); } public SSLConnectionContext(String sslTruststore, String sslTruststorePassword, String sslProtocol, List<String> sslCipherSuites){ this.sslTruststore = sslTruststore; this.sslTruststorePassword = sslTruststorePassword; this.sslProtocol = sslProtocol; this.sslCipherSuites = sslCipherSuites; } /** SSL protocol (typically, TLS) */ public String getSslProtocol(){ return sslProtocol; } /** * The SSL ciphers to use. Common examples, often default, are TLS_RSA_WITH_AES_128_CBC_SHA and * TLS_RSA_WITH_AES_256_CBC_SHA */ public List<String> getSslCipherSuites() { return sslCipherSuites; } public String getSslTruststore() { return sslTruststore; } public String getSslTruststorePassword() { return sslTruststorePassword; } }
7,679
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionFactory.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import com.netflix.astyanax.connectionpool.exceptions.ThrottledException; /** * Factory used to create and open new connections on a host. * * @author elandau * * @param <CL> */ public interface ConnectionFactory<CL> { Connection<CL> createConnection(HostConnectionPool<CL> pool) throws ThrottledException; }
7,680
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/LatencyScoreStrategyType.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; public enum LatencyScoreStrategyType { NONE, SMA, EMA }
7,681
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/Host.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * Wrapper for the representation of the address for a cassandra node. * This Host object is used by the connection pool to uniquely identify the host * and track it's connections. * * @author elandau * */ public class Host implements Comparable<Host> { public static final Host NO_HOST = new Host(); public static final String UKNOWN_RACK = ""; private final String host; private final String ipAddress; private final int port; private final String name; private final String url; private String rack = UKNOWN_RACK; private String id; private Set<String> alternateIpAddress = Sets.newHashSet(); private List<TokenRange> ranges = Lists.newArrayList(); public static Pattern IP_ADDR_PATTERN = Pattern .compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"); /** * Empty host used in error return codes */ private Host() { this.host = "None"; this.ipAddress = "0.0.0.0"; this.port = 0; this.name = String.format("%s(%s):%d", this.host, this.ipAddress, this.port); this.url = String.format("%s:%d", this.host, this.port); } /** * Construct a Host from a host:port combination. The defaultPort is provided in case * the hostAndPort2 value does not have a port specified. * * @param hostAndPort * @param defaultPort */ public Host(String hostAndPort, int defaultPort) { String tempHost = parseHostFromHostAndPort(hostAndPort); this.port = parsePortFromHostAndPort(hostAndPort, defaultPort); Matcher match = IP_ADDR_PATTERN.matcher(tempHost); String workHost; String workIpAddress; if (match.matches()) { workHost = tempHost; workIpAddress = tempHost; } else { try { InetAddress address = InetAddress.getByName(tempHost); workHost = address.getHostName(); workIpAddress = address.getHostAddress(); } catch (UnknownHostException e) { workHost = tempHost; workIpAddress = tempHost; } } this.host = workHost; this.ipAddress = workIpAddress; this.name = String.format("%s(%s):%d", tempHost, this.ipAddress, this.port); this.url = String.format("%s:%d", this.host, this.port); } /** * Parse the hostname from a "hostname:port" formatted string * * @param hostAndPort * @return */ public static String parseHostFromHostAndPort(String hostAndPort) { return hostAndPort.lastIndexOf(':') > 0 ? hostAndPort.substring(0, hostAndPort.lastIndexOf(':')) : hostAndPort; } /** * Parse the port from a "hostname:port" formatted string * * @param urlPort * @param defaultPort * @return */ public static int parsePortFromHostAndPort(String urlPort, int defaultPort) { return urlPort.lastIndexOf(':') > 0 ? Integer.valueOf(urlPort.substring(urlPort.lastIndexOf(':') + 1, urlPort.length())) : defaultPort; } @Override public String toString() { return name; } public boolean equals(Object obj) { if (!(obj instanceof Host)) { return false; } Host other = (Host) obj; return (other.host.equals(host) || other.ipAddress.equals(ipAddress)) && other.port == port; } public int hashCode() { return host.hashCode() + port; } public String getName() { return this.name; } public String getUrl() { return this.url; } public String getIpAddress() { return this.ipAddress; } public String getHostName() { return this.host; } public int getPort() { return this.port; } public Set<String> getAlternateIpAddresses() { return this.alternateIpAddress; } public Host addAlternateIpAddress(String ipAddress) { this.alternateIpAddress.add(ipAddress); return this; } public String getId() { return this.id; } public Host setId(String id) { this.id = id; return this; } public Host setRack(String rack) { this.rack = rack; return this; } public String getRack() { return rack; } public synchronized Host setTokenRanges(List<TokenRange> ranges) { this.ranges = ranges; return this; } public synchronized List<TokenRange> getTokenRanges() { return this.ranges; } @Override public int compareTo(Host other) { int comp = this.host.compareTo(other.host); if (comp != 0) { comp = this.ipAddress.compareTo(other.ipAddress); } if (comp == 0) { comp = this.port - other.port; } return comp; } }
7,682
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/NodeDiscoveryMonitorMBean.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; public interface NodeDiscoveryMonitorMBean { long getRefreshCount(); long getErrorCount(); String getLastException(); String getLastRefreshTime(); String getRawHostList(); }
7,683
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/JmxConnectionPoolMonitorMBean.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; public interface JmxConnectionPoolMonitorMBean { boolean addHost(String host); boolean removeHost(String host); boolean isHostUp(String host); boolean hasHost(String host); String getActiveHosts(); }
7,684
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ConnectionContext.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; /** * Context specific to a connection. This interface makes it possible to store * connection specific state such as prepared CQL statement ids. * @author elandau * */ public interface ConnectionContext { /** * Set metadata identified by 'key' * @param key * @param obj */ public void setMetadata(String key, Object obj); /** * @return Get metadata stored by calling setMetadata * @param key */ public Object getMetadata(String key); /** * @return Return true if the metadata with the specified key exists. * @param key */ public boolean hasMetadata(String key); }
7,685
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/HostStats.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool; import java.util.Date; public interface HostStats { boolean isUp(); boolean isInRing(); Date getTimeCreated(); HostConnectionPool<?> getPool(); long getUpTime(); long getSuccessCount(); long getErrorCount(); long getConnectionsClosed(); long getConnectionsCreated(); long getConnectionsCreateFailed(); long getTimesUp(); long getTimesDown(); void setPool(HostConnectionPool<?> pool); }
7,686
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/ExecuteWithFailover.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool; /** * Interface that encapsulates functionality to execute an {@link Operation} with a failover strategy as well. * * This class is used when attempting to find a healthy {@link Connection} from a set of {@link HostConnectionPool}(s) for a set of {@link Host}(s) * This can be used by an extending class of the {@link AbstractHostPartitionConnectionPool} which reliably tries to execute an {@link Operation} * within the {@link AbstractHostPartitionConnectionPool#executeWithFailover(Operation, com.netflix.astyanax.retry.RetryPolicy)} method for the * given host partitions. * * @see {@link AbstractHostPartitionConnectionPool} for references to this class. * * @author elandau * * @param <CL> * @param <R> */ public interface ExecuteWithFailover<CL, R> { OperationResult<R> tryOperation(Operation<CL, R> operation) throws ConnectionException; }
7,687
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/LeastOutstandingExecuteWithFailover.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.util.Iterator; import java.util.List; import com.google.common.collect.Lists; import com.netflix.astyanax.connectionpool.Connection; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException; /** * Finds the {@link HostConnectionPool} with the max idle connections when borrowing a connection from the pool. * This execute with failover impl is used within the {@link TokenAwareConnectionPoolImpl} class depending on the configured * {@link HostSelectorStrategy} * * @author elandau * * @param <CL> * @param <R> * * @see {@link TokenAwareConnectionPoolImpl#executeWithFailover(Operation, com.netflix.astyanax.retry.RetryPolicy)} for details on where this class is referenced */ public class LeastOutstandingExecuteWithFailover<CL, R> extends AbstractExecuteWithFailoverImpl<CL, R> { protected HostConnectionPool<CL> pool; private int retryCountdown; protected final List<HostConnectionPool<CL>> pools; protected int waitDelta; protected int waitMultiplier = 1; public LeastOutstandingExecuteWithFailover(ConnectionPoolConfiguration config, ConnectionPoolMonitor monitor, List<HostConnectionPool<CL>> pools) throws ConnectionException { super(config, monitor); this.pools = Lists.newArrayList(pools); if (this.pools == null || this.pools.isEmpty()) { throw new NoAvailableHostsException("No hosts to borrow from"); } int size = this.pools.size(); retryCountdown = Math.min(config.getMaxFailoverCount(), size); if (retryCountdown < 0) retryCountdown = size; else if (retryCountdown == 0) retryCountdown = 1; waitDelta = config.getMaxTimeoutWhenExhausted() / retryCountdown; } public boolean canRetry() { return --retryCountdown > 0; } @Override public HostConnectionPool<CL> getCurrentHostConnectionPool() { return pool; } @Override public Connection<CL> borrowConnection(Operation<CL, R> operation) throws ConnectionException { // find the pool with the least outstanding (i.e most idle) active connections Iterator<HostConnectionPool<CL>> iterator = this.pools.iterator(); HostConnectionPool eligible = iterator.next(); while (iterator.hasNext()) { HostConnectionPool<CL> candidate = iterator.next(); if (candidate.getIdleConnectionCount() > eligible.getIdleConnectionCount()) { eligible = candidate; } } return eligible.borrowConnection(waitDelta * waitMultiplier); } }
7,688
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/HostSelectorStrategy.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool.impl; /** * See {@link TokenAwareConnectionPoolImpl#executeWithFailover(com.netflix.astyanax.connectionpool.Operation, com.netflix.astyanax.retry.RetryPolicy)} * for details on how the strategy is consulted when executing an operation with a specific operation failover strategy. * * @author elandau * */ public enum HostSelectorStrategy { ROUND_ROBIN, LEAST_OUTSTANDING }
7,689
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractOperationFilter.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.nio.ByteBuffer; import com.netflix.astyanax.connectionpool.ConnectionContext; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; /** * * Class that wraps an {@link Operation} to provide extra functionality. It can be used by extending class to wrap operation executions * and then decorate the execute functionality with their own logic * * @author elandau * * @param <CL> * @param <R> */ public class AbstractOperationFilter<CL, R> implements Operation<CL, R>{ private Operation<CL, R> next; public AbstractOperationFilter(Operation<CL, R> next) { this.next = next; } @Override public R execute(CL client, ConnectionContext state) throws ConnectionException { return next.execute(client, state); } @Override public ByteBuffer getRowKey() { return next.getRowKey(); } @Override public String getKeyspace() { return next.getKeyspace(); } @Override public Host getPinnedHost() { return next.getPinnedHost(); } }
7,690
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SmaLatencyScoreStrategyImpl.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.util.NoSuchElementException; import java.util.concurrent.LinkedBlockingQueue; public class SmaLatencyScoreStrategyImpl extends AbstractLatencyScoreStrategyImpl { private static final String NAME = "SMA"; private final int windowSize; public SmaLatencyScoreStrategyImpl(int updateInterval, int resetInterval, int windowSize, int blockedThreshold, double keepRatio, double scoreThreshold) { super(NAME, updateInterval, resetInterval, blockedThreshold, keepRatio, scoreThreshold); this.windowSize = windowSize; } public SmaLatencyScoreStrategyImpl(int updateInterval, int resetInterval, int windowSize, double badnessThreshold) { this(updateInterval, resetInterval, windowSize, DEFAULT_BLOCKED_THREAD_THRESHOLD, DEFAULT_KEEP_RATIO, badnessThreshold); } public SmaLatencyScoreStrategyImpl() { super(NAME); this.windowSize = 20; } public final Instance newInstance() { return new Instance() { private final LinkedBlockingQueue<Long> latencies = new LinkedBlockingQueue<Long>(windowSize); private volatile Double cachedScore = 0.0d; @Override public void addSample(long sample) { if (!latencies.offer(sample)) { try { latencies.remove(); } catch (NoSuchElementException e) { } latencies.offer(sample); } } @Override public double getScore() { return cachedScore; } @Override public void reset() { latencies.clear(); } @Override public void update() { cachedScore = getMean(); } private double getMean() { long sum = 0; int count = 0; for (long d : latencies) { sum += d; count++; } return (count > 0) ? sum / count : 0.0; } }; } }
7,691
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/SimpleRateLimiterImpl.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.util.concurrent.LinkedBlockingDeque; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.RateLimiter; public class SimpleRateLimiterImpl implements RateLimiter { private final LinkedBlockingDeque<Long> queue = new LinkedBlockingDeque<Long>(); private final ConnectionPoolConfiguration config; public SimpleRateLimiterImpl(ConnectionPoolConfiguration config) { this.config = config; } @Override public boolean check() { return check(System.currentTimeMillis()); } @Override public boolean check(long currentTimeMillis) { int maxCount = config.getConnectionLimiterMaxPendingCount(); if (maxCount == 0) return true; // Haven't reached the count limit yet if (queue.size() < maxCount) { queue.addFirst(currentTimeMillis); return true; } else { long last = queue.getLast(); if (currentTimeMillis - last < config.getConnectionLimiterWindowSize()) { return false; } queue.addFirst(currentTimeMillis); queue.removeLast(); return true; } } }
7,692
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/RoundRobinExecuteWithFailover.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.util.List; import com.netflix.astyanax.connectionpool.Connection; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.HostConnectionPool; import com.netflix.astyanax.connectionpool.Operation; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.NoAvailableHostsException; /** * Class that extends {@link AbstractExecuteWithFailoverImpl} to provide functionality for borrowing a {@link Connection} from a list of {@link HostConnectionPool}(s) * in a round robin fashion. <br/> <br/> * * It maintains state of the current and next pool to be used by a revolving index over the list of pools, hence round robin. * It also maintains state of how many retries have been done for this instance and consults the * {@link ConnectionPoolConfiguration#getMaxFailoverCount()} threshold. * * @author elandau * * @param <CL> * @param <R> * * @see {@link AbstractExecuteWithFailoverImpl} for details on how failover is repeatedly called for ensuring that an {@link Operation} can be executed with resiliency. * @see {@link RoundRobinConnectionPoolImpl} for the impl that references this class. * @see {@link AbstractHostPartitionConnectionPool} for more context on how failover functionality is used within the context of an operation execution * */ public class RoundRobinExecuteWithFailover<CL, R> extends AbstractExecuteWithFailoverImpl<CL, R> { private int index; protected HostConnectionPool<CL> pool; private int retryCountdown; protected final List<HostConnectionPool<CL>> pools; protected final int size; protected int waitDelta; protected int waitMultiplier = 1; public RoundRobinExecuteWithFailover(ConnectionPoolConfiguration config, ConnectionPoolMonitor monitor, List<HostConnectionPool<CL>> pools, int index) throws ConnectionException { super(config, monitor); this.index = index; this.pools = pools; if (pools == null || pools.isEmpty()) { throw new NoAvailableHostsException("No hosts to borrow from"); } size = pools.size(); retryCountdown = Math.min(config.getMaxFailoverCount(), size); if (retryCountdown < 0) retryCountdown = size; else if (retryCountdown == 0) retryCountdown = 1; waitDelta = config.getMaxTimeoutWhenExhausted() / retryCountdown; } public int getNextHostIndex() { try { return index % size; } finally { index++; if (index < 0) index = 0; } } public boolean canRetry() { return --retryCountdown > 0; } @Override public HostConnectionPool<CL> getCurrentHostConnectionPool() { return pool; } @Override public Connection<CL> borrowConnection(Operation<CL, R> operation) throws ConnectionException { pool = pools.get(getNextHostIndex()); return pool.borrowConnection(waitDelta * waitMultiplier); } }
7,693
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/EmaLatencyScoreStrategyImpl.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.concurrent.LinkedBlockingQueue; import com.google.common.collect.Lists; /** * Calculate latency as an exponential moving average. * * @author elandau */ public class EmaLatencyScoreStrategyImpl extends AbstractLatencyScoreStrategyImpl { private final static String NAME = "EMA"; private final int N; // Number of samples private final double k; // cached value for calculation private final double one_minus_k; // cached value for calculation public EmaLatencyScoreStrategyImpl(int updateInterval, int resetInterval, int windowSize, int blockedThreshold, double keepRatio, double scoreThreshold) { super(NAME, updateInterval, resetInterval, blockedThreshold, keepRatio, scoreThreshold); this.N = windowSize; this.k = (double)2 / (double)(this.N + 1); this.one_minus_k = 1 - this.k; } public EmaLatencyScoreStrategyImpl(int updateInterval, int resetInterval, int windowSize) { super(NAME, updateInterval, resetInterval); this.N = windowSize; this.k = (double)2 / (double)(this.N + 1); this.one_minus_k = 1 - this.k; } public EmaLatencyScoreStrategyImpl(int windowSize) { super(NAME); this.N = windowSize; this.k = (double)2 / (double)(this.N + 1); this.one_minus_k = 1 - this.k; } @Override public final Instance newInstance() { return new Instance() { private final LinkedBlockingQueue<Long> latencies = new LinkedBlockingQueue<Long>(N); private volatile double cachedScore = 0.0d; @Override public void addSample(long sample) { if (!latencies.offer(sample)) { try { latencies.remove(); } catch (NoSuchElementException e) { } latencies.offer(sample); } } @Override public double getScore() { return cachedScore; } @Override public void reset() { cachedScore = 0.0; latencies.clear(); } /** * Drain all the samples and update the cached score */ @Override public void update() { Double ema = cachedScore; ArrayList<Long> samples = Lists.newArrayList(); latencies.drainTo(samples); if (samples.size() == 0) { samples.add(0L); } if (ema == 0.0) { ema = (double)samples.remove(0); } for (Long sample : samples) { ema = sample * k + ema * one_minus_k; } cachedScore = ema; } }; } }
7,694
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/RoundRobinConnectionPoolImpl.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool.impl; import com.netflix.astyanax.connectionpool.*; import com.netflix.astyanax.connectionpool.exceptions.*; import java.util.Arrays; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * Connection pool implementation using simple round robin. <br/> <br/> * It maintains a rotating index over a collection of {@link HostConnectionPool}(s) maintained using a {@link Topology} that reflects the given * partitioned set of pools. Note that the impl uses the <b>pinned host</b> on the operation if it finds one. If there is none, then it uses * all the host connection pools in the topology. * * @see {@link RoundRobinExecuteWithFailover} for more details on how failover works with round robin connections. * @see {@link Topology} for details on where the collection of {@link HostConnectionPool}(s) are maintained. * @see {@link AbstractHostPartitionConnectionPool} for the base impl of {@link ConnectionPool} * * @author elandau * * @param <CL> */ public class RoundRobinConnectionPoolImpl<CL> extends AbstractHostPartitionConnectionPool<CL> { private final AtomicInteger roundRobinCounter = new AtomicInteger(new Random().nextInt(997)); private static final int MAX_RR_COUNTER = Integer.MAX_VALUE/2; public RoundRobinConnectionPoolImpl(ConnectionPoolConfiguration config, ConnectionFactory<CL> factory, ConnectionPoolMonitor monitor) { super(config, factory, monitor); } @SuppressWarnings("unchecked") public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> operation) throws ConnectionException { try { if (operation.getPinnedHost() != null) { HostConnectionPool<CL> pool = hosts.get(operation.getPinnedHost()); if (pool == null) { throw new NoAvailableHostsException("Host " + operation.getPinnedHost() + " not active"); } return new RoundRobinExecuteWithFailover<CL, R>(config, monitor, Arrays.<HostConnectionPool<CL>> asList(pool), 0); } int index = roundRobinCounter.incrementAndGet(); if (index > MAX_RR_COUNTER) { roundRobinCounter.set(0); } return new RoundRobinExecuteWithFailover<CL, R>(config, monitor, topology.getAllPools().getPools(), index); } catch (ConnectionException e) { monitor.incOperationFailure(e.getHost(), e); throw e; } } }
7,695
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/Topology.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.nio.ByteBuffer; import java.util.Collection; import java.util.List; import java.util.Map; import com.netflix.astyanax.connectionpool.HostConnectionPool; public interface Topology<CL> { /** * Refresh the internal topology structure * * @param ring * @return True if anything changed in the internal state */ boolean setPools(Collection<HostConnectionPool<CL>> ring); /** * Add a pool without knowing its token. This pool will be added to the all * pools partition only * * @param pool */ void addPool(HostConnectionPool<CL> pool); /** * Remove this pool from all partitions * * @param pool */ void removePool(HostConnectionPool<CL> pool); /** * Resume a host that was previously down * * @param pool */ void resumePool(HostConnectionPool<CL> pool); /** * Suspend a host that is down * * @param pool */ void suspendPool(HostConnectionPool<CL> pool); /** * Refresh the internal state and apply the latency score strategy */ void refresh(); /** * Get the partition best suited to handle a row key * * @param token */ TokenHostConnectionPoolPartition<CL> getPartition(ByteBuffer rowkey); /** * TODO * * Get the partition best suited for handling a set of row keys * @param tokens * @return */ // HostConnectionPoolPartition<CL> getPartition(Collection<ByteBuffer> tokens); /** * Return a partition that represents all hosts in the ring */ TokenHostConnectionPoolPartition<CL> getAllPools(); /** * @return Get total number of tokens in the topology */ int getPartitionCount(); /** * @return Return a list of all unqiue ids or first token for partitions in the topology */ List<String> getPartitionNames(); /** * @return Return a mapping of partition ids to partition details */ Map<String, TokenHostConnectionPoolPartition<CL>> getPartitions(); /** * Return the partition for a specific token * @param token */ TokenHostConnectionPoolPartition<CL> getPartition(String token); }
7,696
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/AbstractExecutionImpl.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import com.netflix.astyanax.Execution; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.IsRetryableException; import com.netflix.astyanax.retry.RetryPolicy; /** * Abstract impl that repeatedly executes while consulting a {@link RetryPolicy} * * @author elandau * * @param <R> * * @see {@link RetryPolicy} */ public abstract class AbstractExecutionImpl<R> implements Execution<R> { public OperationResult<R> executeWithRetry(RetryPolicy retry) throws ConnectionException { ConnectionException lastException = null; retry.begin(); do { try { return execute(); } catch (ConnectionException ex) { if (ex instanceof IsRetryableException) lastException = ex; else throw ex; } } while (retry.allowRetry()); throw lastException; } }
7,697
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/ConnectionPoolConfigurationImpl.java
/******************************************************************************* * Copyright 2011 Netflix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.netflix.astyanax.connectionpool.impl; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.apache.commons.lang.builder.ToStringBuilder; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.astyanax.AuthenticationCredentials; import com.netflix.astyanax.connectionpool.BadHostDetector; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.Host; import com.netflix.astyanax.connectionpool.LatencyScoreStrategy; import com.netflix.astyanax.connectionpool.OperationFilterFactory; import com.netflix.astyanax.connectionpool.RetryBackoffStrategy; import com.netflix.astyanax.connectionpool.SSLConnectionContext; import com.netflix.astyanax.partitioner.Partitioner; import com.netflix.astyanax.shallows.EmptyBadHostDetectorImpl; import com.netflix.astyanax.shallows.EmptyLatencyScoreStrategyImpl; import com.netflix.astyanax.shallows.EmptyOperationFilterFactory; import com.netflix.astyanax.shallows.EmptyOperationTracer; import com.netflix.astyanax.tracing.OperationTracer; /** * * Basic impl for {@link ConnectionPoolConfiguration} that uses a bunch of defaults for al the connection pool config. * * @author elandau */ public class ConnectionPoolConfigurationImpl implements ConnectionPoolConfiguration { /** * Default values */ public static final int DEFAULT_MAX_TIME_WHEN_EXHAUSTED = 2000; public static final int DEFAULT_SOCKET_TIMEOUT = 11000; // ms public static final int DEFAULT_CONNECT_TIMEOUT = 2000; // ms public static final int DEFAULT_MAX_ACTIVE_PER_PARTITION = 3; public static final int DEFAULT_INIT_PER_PARTITION = 0; public static final int DEFAULT_PORT = 9160; public static final int DEFAULT_FAILOVER_COUNT = -1; public static final int DEFAULT_MAX_CONNS = 1; public static final int DEFAULT_LATENCY_AWARE_WINDOW_SIZE = 100; public static final float DEFAULT_LATENCY_AWARE_SENTINEL_COMPARE = 0.768f; public static final int DEFAULT_LATENCY_AWARE_UPDATE_INTERVAL = 10000; public static final int DEFAULT_LATENCY_AWARE_RESET_INTERVAL = 60000; public static final float DEFAULT_LATENCY_AWARE_BADNESS_THRESHOLD = 0.10f; public static final int DEFAULT_CONNECTION_LIMITER_WINDOW_SIZE = 2000; public static final int DEFAULT_CONNECTION_LIMITER_MAX_PENDING_COUNT = 50; public static final int DEFAULT_MAX_PENDING_CONNECTIONS_PER_HOST = 5; public static final int DEFAULT_MAX_BLOCKED_THREADS_PER_HOST = 25; public static final int DEFAULT_MAX_TIMEOUT_COUNT = 3; public static final int DEFAULT_TIMEOUT_WINDOW = 10000; public static final int DEFAULT_RETRY_SUSPEND_WINDOW = 20000; public static final int DEFAULT_RETRY_DELAY_SLICE = 10000; public static final int DEFAULT_RETRY_MAX_DELAY_SLICE = 10; public static final int DEFAULT_MAX_OPERATIONS_PER_CONNECTION = 10000; public static final float DEFAULT_MIN_HOST_IN_POOL_RATIO = 0.65f; public static final int DEFAULT_BLOCKED_THREAD_THRESHOLD = 10; public static final BadHostDetector DEFAULT_BAD_HOST_DETECTOR = EmptyBadHostDetectorImpl.getInstance(); // public static final Partitioner DEFAULT_PARTITIONER = BigInteger127Partitioner.get(); private static final int DEFAULT_RECONNECT_THREAD_COUNT = 5; private static final int DEFAULT_MAINTAINANCE_THREAD_COUNT = 1; private static final String DEFAULT_PARTITIONER_CLASS = "com.netflix.astyanax.partitioner.BigInteger127Partitioner"; private final String name; private int maxConnsPerPartition = DEFAULT_MAX_ACTIVE_PER_PARTITION; private int initConnsPerPartition = DEFAULT_INIT_PER_PARTITION; private int maxConns = DEFAULT_MAX_CONNS; private int port = DEFAULT_PORT; private int socketTimeout = DEFAULT_SOCKET_TIMEOUT; private int connectTimeout = DEFAULT_CONNECT_TIMEOUT; private int maxFailoverCount = DEFAULT_FAILOVER_COUNT; private int latencyAwareWindowSize = DEFAULT_LATENCY_AWARE_WINDOW_SIZE; private float latencyAwareSentinelCompare = DEFAULT_LATENCY_AWARE_SENTINEL_COMPARE; private float latencyAwareBadnessThreshold = DEFAULT_LATENCY_AWARE_BADNESS_THRESHOLD; private int latencyAwareUpdateInterval = DEFAULT_LATENCY_AWARE_UPDATE_INTERVAL; private int latencyAwareResetInterval = DEFAULT_LATENCY_AWARE_RESET_INTERVAL; private int connectionLimiterWindowSize = DEFAULT_CONNECTION_LIMITER_WINDOW_SIZE; private int connectionLimiterMaxPendingCount = DEFAULT_CONNECTION_LIMITER_MAX_PENDING_COUNT; private int maxPendingConnectionsPerHost = DEFAULT_MAX_PENDING_CONNECTIONS_PER_HOST; private int maxBlockedThreadsPerHost = DEFAULT_MAX_BLOCKED_THREADS_PER_HOST; private int maxTimeoutCount = DEFAULT_MAX_TIMEOUT_COUNT; private int timeoutWindow = DEFAULT_TIMEOUT_WINDOW; private int retrySuspendWindow = DEFAULT_RETRY_SUSPEND_WINDOW; private int retryDelaySlice = DEFAULT_RETRY_DELAY_SLICE; private int retryMaxDelaySlice = DEFAULT_RETRY_MAX_DELAY_SLICE; private int maxOperationsPerConnection = DEFAULT_MAX_OPERATIONS_PER_CONNECTION; private int maxTimeoutWhenExhausted = DEFAULT_MAX_TIME_WHEN_EXHAUSTED; private float minHostInPoolRatio = DEFAULT_MIN_HOST_IN_POOL_RATIO; private int blockedThreadThreshold = DEFAULT_BLOCKED_THREAD_THRESHOLD; private String seeds = null; private RetryBackoffStrategy hostRetryBackoffStrategy = null; private HostSelectorStrategy hostSelectorStrategy = HostSelectorStrategy.ROUND_ROBIN; private LatencyScoreStrategy latencyScoreStrategy = new EmptyLatencyScoreStrategyImpl(); private BadHostDetector badHostDetector = DEFAULT_BAD_HOST_DETECTOR; private AuthenticationCredentials credentials = null; private OperationFilterFactory filterFactory = EmptyOperationFilterFactory.getInstance(); private OperationTracer opTracer = new EmptyOperationTracer(); private Partitioner partitioner = null; private SSLConnectionContext sslCtx; private ScheduledExecutorService maintainanceExecutor; private ScheduledExecutorService reconnectExecutor; private boolean bOwnMaintainanceExecutor = false; private boolean bOwnReconnectExecutor = false; private String localDatacenter = null; public ConnectionPoolConfigurationImpl(String name) { this.name = name; this.badHostDetector = new BadHostDetectorImpl(this); this.hostRetryBackoffStrategy = new ExponentialRetryBackoffStrategy(this); } @Override public void initialize() { if (partitioner == null) { try { partitioner = (Partitioner) Class.forName(DEFAULT_PARTITIONER_CLASS).newInstance(); } catch (Throwable t) { throw new RuntimeException("Can't instantiate default partitioner " + DEFAULT_PARTITIONER_CLASS, t); } } if (maintainanceExecutor == null) { maintainanceExecutor = Executors.newScheduledThreadPool(DEFAULT_MAINTAINANCE_THREAD_COUNT, new ThreadFactoryBuilder().setDaemon(true).build()); bOwnMaintainanceExecutor = true; } if (reconnectExecutor == null) { reconnectExecutor = Executors.newScheduledThreadPool(DEFAULT_RECONNECT_THREAD_COUNT, new ThreadFactoryBuilder().setDaemon(true).build()); bOwnReconnectExecutor = true; } } @Override public void shutdown() { if (bOwnMaintainanceExecutor) { maintainanceExecutor.shutdownNow(); } if (bOwnReconnectExecutor) { reconnectExecutor.shutdownNow(); } } /* * (non-Javadoc) * * @see com.netflix.cassandra.ConnectionPoolConfiguration#getKeyspaceName() */ @Override public String getName() { return this.name; } /* * (non-Javadoc) * * @see com.netflix.cassandra.ConnectionPoolConfiguration#getSocketTimeout() */ @Override public int getSocketTimeout() { return socketTimeout; } public ConnectionPoolConfigurationImpl setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; return this; } /* * (non-Javadoc) * * @see * com.netflix.cassandra.ConnectionPoolConfiguration#getConnectTimeout() */ @Override public int getConnectTimeout() { return connectTimeout; } public ConnectionPoolConfigurationImpl setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; return this; } /* * (non-Javadoc) * * @see com.netflix.cassandra.ConnectionPoolConfiguration#getSeeds() */ @Override public String getSeeds() { return this.seeds; } public ConnectionPoolConfigurationImpl setSeeds(String seeds) { this.seeds = seeds; return this; } /** * Returns local datacenter name * * @return */ public String getLocalDatacenter() { return localDatacenter; } public ConnectionPoolConfigurationImpl setLocalDatacenter(String localDatacenter) { this.localDatacenter = localDatacenter; return this; } /* * (non-Javadoc) * * @see * com.netflix.cassandra.ConnectionPoolConfiguration#getMaxTimeoutWhenExhausted * () */ @Override public int getMaxTimeoutWhenExhausted() { return this.maxTimeoutWhenExhausted; } public ConnectionPoolConfigurationImpl setMaxTimeoutWhenExhausted(int timeout) { this.maxTimeoutWhenExhausted = timeout; return this; } /* * (non-Javadoc) * * @see com.netflix.cassandra.ConnectionPoolConfiguration#getPort() */ @Override public int getPort() { return this.port; } public ConnectionPoolConfigurationImpl setPort(int port) { this.port = port; return this; } /* * (non-Javadoc) * * @see * com.netflix.cassandra.ConnectionPoolConfiguration#getMaxConnsPerHost() */ @Override public int getMaxConnsPerHost() { return this.maxConnsPerPartition; } public ConnectionPoolConfigurationImpl setMaxConnsPerHost(int maxConns) { Preconditions.checkArgument(maxConns > 0, "maxConnsPerHost must be >0"); this.maxConnsPerPartition = maxConns; return this; } /* * (non-Javadoc) * * @see * com.netflix.cassandra.ConnectionPoolConfiguration#getInitConnsPerHost() */ @Override public int getInitConnsPerHost() { return this.initConnsPerPartition; } public ConnectionPoolConfigurationImpl setInitConnsPerHost(int initConns) { Preconditions.checkArgument(initConns >= 0, "initConnsPerHost must be >0"); this.initConnsPerPartition = initConns; return this; } /* * (non-Javadoc) * * @see * com.netflix.cassandra.ConnectionPoolConfiguration#getRetryBackoffStrategy * () */ @Override public RetryBackoffStrategy getRetryBackoffStrategy() { return this.hostRetryBackoffStrategy; } public ConnectionPoolConfigurationImpl setRetryBackoffStrategy(RetryBackoffStrategy hostRetryBackoffStrategy) { this.hostRetryBackoffStrategy = hostRetryBackoffStrategy; return this; } @Override public HostSelectorStrategy getHostSelectorStrategy() { return this.hostSelectorStrategy; } public ConnectionPoolConfigurationImpl setHostSelectorStrategy(HostSelectorStrategy hostSelectorStrategy) { this.hostSelectorStrategy = hostSelectorStrategy; return this; } /* * (non-Javadoc) * * @see com.netflix.cassandra.ConnectionPoolConfiguration#getSeedHosts() */ @Override public List<Host> getSeedHosts() { List<Host> hosts = new ArrayList<Host>(); if (seeds != null) { for (String seed : seeds.split(",")) { seed = seed.trim(); if (seed.length() > 0) { hosts.add(new Host(seed, this.port)); } } } return hosts; } @Override public int getMaxFailoverCount() { return this.maxFailoverCount; } public ConnectionPoolConfigurationImpl setMaxFailoverCount(int maxFailoverCount) { this.maxFailoverCount = maxFailoverCount; return this; } @Override public int getMaxConns() { return this.maxConns; } public ConnectionPoolConfigurationImpl setMaxConns(int maxConns) { this.maxConns = maxConns; return this; } @Override public int getLatencyAwareWindowSize() { return this.latencyAwareWindowSize; } public ConnectionPoolConfigurationImpl setLatencyAwareWindowSize(int latencyAwareWindowSize) { this.latencyAwareWindowSize = latencyAwareWindowSize; return this; } @Override public float getLatencyAwareSentinelCompare() { return latencyAwareSentinelCompare; } public ConnectionPoolConfigurationImpl setLatencyAwareSentinelCompare(float latencyAwareSentinelCompare) { this.latencyAwareSentinelCompare = latencyAwareSentinelCompare; return this; } @Override public float getLatencyAwareBadnessThreshold() { return this.latencyAwareBadnessThreshold; } public ConnectionPoolConfigurationImpl setLatencyAwareBadnessThreshold(float threshold) { this.latencyAwareBadnessThreshold = threshold; return this; } @Override public int getConnectionLimiterWindowSize() { return this.connectionLimiterWindowSize; } public ConnectionPoolConfigurationImpl setConnectionLimiterWindowSize(int pendingConnectionWindowSize) { this.connectionLimiterWindowSize = pendingConnectionWindowSize; return this; } @Override public int getConnectionLimiterMaxPendingCount() { return this.connectionLimiterMaxPendingCount; } public ConnectionPoolConfigurationImpl setConnectionLimiterMaxPendingCount(int connectionLimiterMaxPendingCount) { this.connectionLimiterMaxPendingCount = connectionLimiterMaxPendingCount; return this; } @Override public int getMaxPendingConnectionsPerHost() { return this.maxPendingConnectionsPerHost; } public ConnectionPoolConfigurationImpl setMaxPendingConnectionsPerHost(int maxPendingConnectionsPerHost) { this.maxPendingConnectionsPerHost = maxPendingConnectionsPerHost; return this; } @Override public int getMaxBlockedThreadsPerHost() { return this.maxBlockedThreadsPerHost; } public ConnectionPoolConfigurationImpl setMaxBlockedThreadsPerHost(int maxBlockedThreadsPerHost) { this.maxBlockedThreadsPerHost = maxBlockedThreadsPerHost; return this; } @Override public int getTimeoutWindow() { return this.timeoutWindow; } public ConnectionPoolConfigurationImpl setTimeoutWindow(int timeoutWindow) { this.timeoutWindow = timeoutWindow; return this; } @Override public int getMaxTimeoutCount() { return this.maxTimeoutCount; } public ConnectionPoolConfigurationImpl setMaxTimeoutCount(int maxTimeoutCount) { this.maxTimeoutCount = maxTimeoutCount; return this; } @Override public int getLatencyAwareUpdateInterval() { return latencyAwareUpdateInterval; } public ConnectionPoolConfigurationImpl setLatencyAwareUpdateInterval(int latencyAwareUpdateInterval) { this.latencyAwareUpdateInterval = latencyAwareUpdateInterval; return this; } @Override public int getLatencyAwareResetInterval() { return latencyAwareResetInterval; } public ConnectionPoolConfigurationImpl setLatencyAwareResetInterval(int latencyAwareResetInterval) { this.latencyAwareResetInterval = latencyAwareResetInterval; return this; } @Override public int getRetrySuspendWindow() { return this.retrySuspendWindow; } public ConnectionPoolConfigurationImpl setRetrySuspendWindow(int retrySuspendWindow) { this.retrySuspendWindow = retrySuspendWindow; return this; } @Override public int getMaxOperationsPerConnection() { return maxOperationsPerConnection; } public ConnectionPoolConfigurationImpl setMaxOperationsPerConnection(int maxOperationsPerConnection) { this.maxOperationsPerConnection = maxOperationsPerConnection; return this; } @Override public LatencyScoreStrategy getLatencyScoreStrategy() { return this.latencyScoreStrategy; } public ConnectionPoolConfigurationImpl setLatencyScoreStrategy(LatencyScoreStrategy latencyScoreStrategy) { this.latencyScoreStrategy = latencyScoreStrategy; return this; } @Override public BadHostDetector getBadHostDetector() { return badHostDetector; } public ConnectionPoolConfigurationImpl setBadHostDetector(BadHostDetector badHostDetector) { this.badHostDetector = badHostDetector; return this; } @Override public int getRetryMaxDelaySlice() { return retryMaxDelaySlice; } public ConnectionPoolConfigurationImpl setRetryMaxDelaySlice(int retryMaxDelaySlice) { this.retryMaxDelaySlice = retryMaxDelaySlice; return this; } @Override public int getRetryDelaySlice() { return this.retryDelaySlice; } public ConnectionPoolConfigurationImpl setRetryDelaySlice(int retryDelaySlice) { this.retryDelaySlice = retryDelaySlice; return this; } public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public AuthenticationCredentials getAuthenticationCredentials() { return credentials; } public ConnectionPoolConfigurationImpl setAuthenticationCredentials(AuthenticationCredentials credentials) { this.credentials = credentials; return this; } @Override public OperationFilterFactory getOperationFilterFactory() { return filterFactory; } public ConnectionPoolConfigurationImpl setOperationFilterFactory(OperationFilterFactory filterFactory) { this.filterFactory = filterFactory; return this; } @Override public Partitioner getPartitioner() { return this.partitioner; } public ConnectionPoolConfigurationImpl setPartitioner(Partitioner partitioner) { this.partitioner = partitioner; return this; } @Override public int getBlockedThreadThreshold() { return this.blockedThreadThreshold; } public ConnectionPoolConfigurationImpl setBlockedThreadThreshold(int threshold) { this.blockedThreadThreshold = threshold; return this; } @Override public float getMinHostInPoolRatio() { return this.minHostInPoolRatio; } public ConnectionPoolConfigurationImpl setMinHostInPoolRatio(float ratio) { this.minHostInPoolRatio = ratio; return this; } public SSLConnectionContext getSSLConnectionContext() { return sslCtx; } public ConnectionPoolConfigurationImpl setSSLConnectionContext(SSLConnectionContext sslCtx) { this.sslCtx = sslCtx; return this; } @Override public ScheduledExecutorService getMaintainanceScheduler() { return maintainanceExecutor; } public ConnectionPoolConfigurationImpl setMaintainanceScheduler(ScheduledExecutorService executor) { maintainanceExecutor = executor; bOwnMaintainanceExecutor = false; return this; } @Override public ScheduledExecutorService getHostReconnectExecutor() { return this.reconnectExecutor; } public ConnectionPoolConfigurationImpl setHostReconnectExecutor(ScheduledExecutorService executor) { reconnectExecutor = executor; bOwnReconnectExecutor = false; return this; } @Override public OperationTracer getOperationTracer() { return opTracer; } public ConnectionPoolConfigurationImpl setOperationTracer(OperationTracer opTracer) { this.opTracer = opTracer; return this; } }
7,698
0
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool
Create_ds/astyanax/astyanax-core/src/main/java/com/netflix/astyanax/connectionpool/impl/ConnectionPoolMBeanManager.java
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.astyanax.connectionpool.impl; import java.lang.management.ManagementFactory; import java.util.HashMap; import javax.management.MBeanServer; import javax.management.ObjectName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.netflix.astyanax.connectionpool.ConnectionPool; import com.netflix.astyanax.connectionpool.JmxConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.JmxConnectionPoolMonitorMBean; /** * Simple jmx bean manager. * * @see {@link JmxConnectionPoolMonitorMBean} {@link JmxConnectionPoolMonitor} * @author elandau * */ public class ConnectionPoolMBeanManager { private static Logger LOG = LoggerFactory.getLogger(ConnectionPoolMBeanManager.class); private MBeanServer mbs; private static ConnectionPoolMBeanManager monitorInstance; private HashMap<String, JmxConnectionPoolMonitorMBean> monitors; private ConnectionPoolMBeanManager() { mbs = ManagementFactory.getPlatformMBeanServer(); monitors = Maps.newHashMap(); } public static ConnectionPoolMBeanManager getInstance() { if (monitorInstance == null) { monitorInstance = new ConnectionPoolMBeanManager(); } return monitorInstance; } public synchronized void registerMonitor(String name, ConnectionPool<?> pool) { String monitorName = generateMonitorName(name); if (!monitors.containsKey(monitorName)) { JmxConnectionPoolMonitorMBean mbean; try { LOG.info("Registering mbean: " + monitorName); ObjectName oName = new ObjectName(monitorName); mbean = new JmxConnectionPoolMonitor(pool); monitors.put(monitorName, mbean); mbs.registerMBean(mbean, oName); } catch (Exception e) { LOG.error(e.getMessage()); monitors.remove(monitorName); } } } public synchronized void unregisterMonitor(String name, ConnectionPool<?> pool) { String monitorName = generateMonitorName(name); monitors.remove(monitorName); try { mbs.unregisterMBean(new ObjectName(monitorName)); } catch (Exception e) { LOG.error(e.getMessage()); } } public synchronized JmxConnectionPoolMonitorMBean getCassandraMonitor(String name) { String monitorName = generateMonitorName(name); return monitors.get(monitorName); } private String generateMonitorName(String name) { StringBuilder sb = new StringBuilder(); sb.append("com.netflix.MonitoredResources"); sb.append(":type=ASTYANAX"); sb.append(",name=" + name); sb.append(",ServiceType=connectionpool"); return sb.toString(); } }
7,699