src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BatchMetaCollection implements MutableMetaCollection { public final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts() { return docPartsByRef.values().stream(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField( MutableMetaDocPart docPart, MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }
@Test public void testConstructor() { assertTrue("The constructor do not copy doc parts contained by the delegate", collection.streamContainedMetaDocParts() .findAny() .isPresent() ); assertTrue("There is at least one doc part that is marked as created on the current branch", collection.streamContainedMetaDocParts() .noneMatch((docPart) -> docPart.isCreatedOnCurrentBatch()) ); }
BatchMetaCollection implements MutableMetaCollection { @Override public BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier) throws IllegalArgumentException { MutableMetaDocPart delegateDocPart = delegate.addMetaDocPart(tableRef, identifier); BatchMetaDocPart myDocPart = new BatchMetaDocPart( delegateDocPart, this::onDocPartChange, true); docPartsByRef.put(myDocPart.getTableRef(), myDocPart); changesOnBatch.put(myDocPart.getTableRef(), myDocPart); modifiedDocParts.put(myDocPart.getTableRef(), myDocPart); return myDocPart; } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField( MutableMetaDocPart docPart, MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }
@Test public void testAddMetaDocPart() { TableRef tableRef = tableRefFactory.createChild(tableRefFactory.createRoot(), "aPath"); String tableId = "aTableId"; BatchMetaDocPart newDocPart = collection.addMetaDocPart(tableRef, tableId); assertNotNull(newDocPart); assertEquals(newDocPart, collection.getMetaDocPartByTableRef(tableRef)); assertTrue("A newly created document thinks it was created on a previous batch", newDocPart.isCreatedOnCurrentBatch()); assertTrue("A newly created doc part is not a member of on batch modified meta doc parts", Iterables.contains(collection.getOnBatchModifiedMetaDocParts(), newDocPart)); verify(delegate).addMetaDocPart(tableRef, tableId); }
BatchMetaCollection implements MutableMetaCollection { @Override public String getName() { return delegate.getName(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField( MutableMetaDocPart docPart, MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }
@Test public void testGetName() { assertEquals(collection.getName(), delegate.getName()); }
BatchMetaCollection implements MutableMetaCollection { @Override public String getIdentifier() { return delegate.getIdentifier(); } BatchMetaCollection(MutableMetaCollection delegate); @Override ImmutableMetaCollection getOrigin(); final Stream<? extends BatchMetaDocPart> streamContainedMetaDocParts(); @DoNotChange Iterable<BatchMetaDocPart> getOnBatchModifiedMetaDocParts(); @Override BatchMetaDocPart getMetaDocPartByTableRef(TableRef tableRef); @Override BatchMetaDocPart getMetaDocPartByIdentifier(String docPartId); @Override BatchMetaDocPart addMetaDocPart(TableRef tableRef, String identifier); @Override Stream<? extends MutableMetaDocPart> streamModifiedMetaDocParts(); @Override MutableMetaIndex getMetaIndexByName(String indexName); @Override Stream<? extends MutableMetaIndex> streamContainedMetaIndexes(); @Override MutableMetaIndex addMetaIndex(String name, boolean unique); @Override boolean removeMetaIndexByName(String indexName); @Override Stream<ChangedElement<MutableMetaIndex>> streamModifiedMetaIndexes(); @Override Optional<ChangedElement<MutableMetaIndex>> getModifiedMetaIndexByName(String idxName); @Override List<Tuple2<MetaIndex, List<String>>> getMissingIndexesForNewField( MutableMetaDocPart docPart, MetaField newField); @Override Optional<ImmutableMetaDocPart> getAnyDocPartWithMissedDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override Optional<? extends MetaIdentifiedDocPartIndex> getAnyOrphanDocPartIndex( ImmutableMetaCollection oldStructure, MutableMetaIndex changed); @Override ImmutableMetaCollection immutableCopy(); @Override String getName(); @Override String getIdentifier(); @Override String toString(); }
@Test public void testGetIdentifier() { assertEquals(collection.getIdentifier(), delegate.getIdentifier()); }
CompletionExceptions { public static Throwable getFirstNonCompletionException(Throwable ex) { Throwable throwableResult = ex; while (isCompletionException(throwableResult)) { Throwable cause = throwableResult.getCause(); if (cause == null || cause == throwableResult) { return throwableResult; } throwableResult = cause; } assert throwableResult != null; assert !(throwableResult instanceof CompletionException) || throwableResult.getCause() == null; return throwableResult; } private CompletionExceptions(); static Throwable getFirstNonCompletionException(Throwable ex); }
@Test public void firstNonCompletionExceptionIsReturned() throws Exception { Throwable nullPointerException = new NullPointerException(); Throwable completionException = new CompletionException("message", nullPointerException); Throwable result = CompletionExceptions.getFirstNonCompletionException(completionException); assertEquals(nullPointerException, result); } @Test public void ifHasNoNestedExceptionCompletionExceptionIsReturned() throws Exception { Throwable completionException = new CompletionException("message", null); Throwable result = CompletionExceptions.getFirstNonCompletionException(completionException); assertEquals(completionException, result); }
HexUtils { public static String bytes2Hex(@Nonnull byte[] bytes) { checkNotNull(bytes, "bytes"); final int length = bytes.length; final char[] chars = new char[length << 1]; int index; int charPos = 0; for (int i = 0; i < length; i++) { index = (bytes[i] & 0xFF) << 1; chars[charPos++] = BYTE_HEX_VALUES[index++]; chars[charPos++] = BYTE_HEX_VALUES[index]; } return new String(chars); } static String bytes2Hex(@Nonnull byte[] bytes); static String bytes2Hex(@Nonnull Collection<Byte> bytes); static void bytes2Hex(@Nonnull byte[] bytes, StringBuilder output); static byte[] hex2Bytes(@Nonnull String value); }
@Test public void bytes2HexArray() { String expected = DatatypeConverter.printHexBinary(bytes); String result = HexUtils.bytes2Hex(bytes); assertEquals(expected, result); } @Test public void bytes2HexCollection() { String expected = DatatypeConverter.printHexBinary(bytes); List<Byte> collectionBytes = new ArrayList<>(bytes.length); for (byte b : bytes) { collectionBytes.add(b); } String result = HexUtils.bytes2Hex(collectionBytes); assertEquals(expected, result); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public ToroMetricRegistry createSubRegistry(String key, String value) { return new DirectoryToroMetricRegistry( directory.createDirectory(key, value), safeMetricRegistry ); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalKey() { registry.createSubRegistry("a-illegal-key", "avalue"); } @Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_2_illegalValue() { registry.createSubRegistry("aValue", "a-illegal-value"); } @Test(expected = IllegalArgumentException.class) public void testCreateSubRegistry_default_illegalValue() { registry.createSubRegistry("a-illegal-value"); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Counter counter(String finalName) { return safeMetricRegistry.counter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testCounter() { String sName = "legalName"; Name name = directory.createName(sName); Counter metric = registry.counter(sName); verify(safeRegistry).counter(name); assertThat(metric, is(safeRegistry.counter(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalCounter() { String sName = "illegal-Name"; registry.counter(sName); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Meter meter(String finalName) { return safeMetricRegistry.meter(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testMeter() { String sName = "legalName"; Name name = directory.createName(sName); Meter metric = registry.meter(sName); verify(safeRegistry).meter(name); assertThat(metric, is(safeRegistry.meter(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalMeter() { String sName = "illegal-Name"; registry.meter(sName); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Histogram histogram(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.histogram(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testHistogram() { String sName = "legalName"; Name name = directory.createName(sName); Histogram metric = registry.histogram(sName); verify(safeRegistry).histogram(name, false); assertThat(metric, is(safeRegistry.histogram(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalHistogram() { String sName = "illegal-Name"; registry.histogram(sName); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public Timer timer(String finalName, boolean resetOnSnapshot) { return safeMetricRegistry.timer(directory.createName(finalName), resetOnSnapshot); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testTimer() { String sName = "legalName"; Name name = directory.createName(sName); Timer metric = registry.timer(sName); verify(safeRegistry).timer(name, false); assertThat(metric, is(safeRegistry.timer(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalTimer() { String sName = "illegal-Name"; registry.timer(sName); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T> SettableGauge<T> gauge(String finalName) { return safeMetricRegistry.gauge(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testGauge() { String sName = "legalName"; Name name = directory.createName(sName); SettableGauge<?> metric = registry.gauge(sName); verify(safeRegistry).gauge(name); assertThat(metric, is(safeRegistry.gauge(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalGauge() { String sName = "illegal-Name"; registry.gauge(sName); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public <T extends Metric> T register(String finalName, T metric) { return safeMetricRegistry.register(directory.createName(finalName), metric); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testRegister() { String sName = "legalName"; Name name = directory.createName(sName); Counter actualCounter = new Counter(); Counter metric = registry.register(sName, actualCounter); verify(safeRegistry).register(name, actualCounter); assertThat(metric, is(safeRegistry.register(name, actualCounter))); assertThat(metric, is(safeRegistry.counter(name))); } @Test(expected = IllegalArgumentException.class) public void testIllegalRegister() { String sName = "illegal-Name"; registry.register(sName, new Counter()); }
DirectoryToroMetricRegistry implements ToroMetricRegistry { @Override public boolean remove(String finalName) { return safeMetricRegistry.remove(directory.createName(finalName)); } DirectoryToroMetricRegistry(Directory directory, SafeRegistry safeMetricRegistry); @Override ToroMetricRegistry createSubRegistry(String key, String value); @Override ToroMetricRegistry createSubRegistry(String middleName); @Override Counter counter(String finalName); @Override Meter meter(String finalName); @Override Histogram histogram(String finalName, boolean resetOnSnapshot); @Override Timer timer(String finalName, boolean resetOnSnapshot); @Override SettableGauge<T> gauge(String finalName); @Override T register(String finalName, T metric); @Override boolean remove(String finalName); }
@Test public void testRemove() { String sName = "legalName"; Name name = directory.createName(sName); registry.remove(sName); verify(safeRegistry).remove(name); } @Test(expected = IllegalArgumentException.class) public void testIllegalRemove() { String sName = "illegal-Name"; registry.remove(sName); }
ConcurrentOplogBatchExecutor extends SimpleAnalyzedOplogBatchExecutor { @Override public void execute(CudAnalyzedOplogBatch cudBatch, ApplierContext context) throws UserException { assert isRunning() : "The service is on state " + state() + " instead of RUNNING"; List<NamespaceJob> namespaceJobList = cudBatch.streamNamespaceJobs() .flatMap(this::split) .collect(Collectors.toList()); concurrentMetrics.getSubBatchSizeMeter().mark(namespaceJobList.size()); concurrentMetrics.getSubBatchSizeHistogram().update(namespaceJobList.size()); Stream<Callable<Empty>> callables = namespaceJobList.stream() .map(namespaceJob -> toCallable(namespaceJob, context)); try { streamExecutor.execute(callables) .join(); } catch (CompletionException ex) { Throwable cause = ex.getCause(); if (cause instanceof UserException) { throw (UserException) cause; } else if (cause instanceof RollbackException) { throw (RollbackException) cause; } throw ex; } } @Inject ConcurrentOplogBatchExecutor(OplogOperationApplier oplogOperationApplier, MongodServer server, Retrier retrier, ConcurrentToolsFactory concurrentToolsFactory, NamespaceJobExecutor namespaceJobExecutor, LoggerFactory lf, ConcurrentOplogBatchExecutorMetrics concurrentMetrics, SubBatchHeuristic subBatchHeuristic); @Override void execute(CudAnalyzedOplogBatch cudBatch, ApplierContext context); }
@Test public void testExecute() throws Exception { int batchSize = 100; int opsPerJob = 20; int subBatchSize = 11; int subBatchesPerJob = opsPerJob / subBatchSize + (opsPerJob % subBatchSize != 0 ? 1 : 0); int expectedSize = batchSize * subBatchesPerJob; CudAnalyzedOplogBatch batch = mock(CudAnalyzedOplogBatch.class); List<NamespaceJob> jobs = new ArrayList<>(); for (int i = 0; i < batchSize; i++) { jobs.add( new NamespaceJob( "db", "col", Lists.newArrayList( Stream.iterate(createAnalyzedOp(null), this::createAnalyzedOp) .limit(opsPerJob) .iterator() ) ) ); } AtomicInteger callablesCounter = new AtomicInteger(0); ApplierContext context = new ApplierContext.Builder() .setReapplying(true) .setUpdatesAsUpserts(true) .build(); Histogram mockHistogram = mock(Histogram.class); Meter mockMeter = mock(Meter.class); given(batch.streamNamespaceJobs()).willReturn(jobs.stream()); given(subBatchHeuristic.getSubBatchSize(any())).willReturn(subBatchSize); given(metrics.getSubBatchSizeHistogram()).willReturn(mockHistogram); given(metrics.getSubBatchSizeMeter()).willReturn(mockMeter); given(streamExecutor.execute(any())) .willAnswer(new Answer<CompletableFuture<?>>() { @Override public CompletableFuture<?> answer(InvocationOnMock invocation) throws Throwable { CompletableFuture<Object> completableFuture = new CompletableFuture<>(); completableFuture.complete(new Object()); Stream<Callable<?>> callables = invocation.getArgument(0); callablesCounter.addAndGet((int) callables.count()); return completableFuture; } }); executor.execute(batch, context); then(mockHistogram).should().update(expectedSize); then(mockMeter).should().mark(expectedSize); assertEquals(expectedSize, callablesCounter.get()); }
EssentialInjectorFactory { public static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory) { return createEssentialInjector(lifecycleLoggerFactory, () -> true, Clock.systemUTC()); } private EssentialInjectorFactory(); static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory); static Injector createEssentialInjector(LoggerFactory lifecycleLoggerFactory, MetricsConfig metricsConfig, Clock clock); static Injector createEssentialInjector( LoggerFactory lifecycleLoggerFactory, MetricsConfig metricsConfig, Clock clock, Stage stage); }
@Test public void testCreateEssentialInjector() { EssentialInjectorFactory.createEssentialInjector(DefaultLoggerFactory.getInstance()); }
SimpleAnalyzedOplogBatchExecutor extends AbstractService implements AnalyzedOplogBatchExecutor { @Override public void execute(OplogOperation op, ApplierContext context) throws OplogApplyingException, RollbackException, UserException { oplogOperationApplier.apply(op, server, context); } @Inject SimpleAnalyzedOplogBatchExecutor( AnalyzedOplogBatchExecutorMetrics metrics, OplogOperationApplier oplogOperationApplier, MongodServer server, Retrier retrier, NamespaceJobExecutor namespaceJobExecutor); @Override void execute(OplogOperation op, ApplierContext context); @Override void execute(CudAnalyzedOplogBatch cudBatch, ApplierContext context); @Override OplogOperation visit(SingleOpAnalyzedOplogBatch batch, ApplierContext arg); @Override OplogOperation visit(CudAnalyzedOplogBatch batch, ApplierContext arg); }
@Test public void testExecute_OplogOperation() throws Exception { OplogOperation op = mock(OplogOperation.class); ApplierContext applierContext = new ApplierContext.Builder() .setReapplying(true) .setUpdatesAsUpserts(true) .build(); executor.execute(op, applierContext); then(applier).should().apply(op, server, applierContext); } @Test public void testExecute_CudAnalyzedOplogBatch() throws Exception { CudAnalyzedOplogBatch cudBatch = mock(CudAnalyzedOplogBatch.class); ApplierContext applierContext = new ApplierContext.Builder() .setReapplying(true) .setUpdatesAsUpserts(true) .build(); NamespaceJob job1 = mock(NamespaceJob.class); NamespaceJob job2 = mock(NamespaceJob.class); NamespaceJob job3 = mock(NamespaceJob.class); doNothing().when(executor).execute(any(NamespaceJob.class), any()); given(cudBatch.streamNamespaceJobs()) .willReturn(Stream.of(job1, job2, job3)); executor.execute(cudBatch, applierContext); then(executor).should().execute(job1, applierContext); then(executor).should().execute(job2, applierContext); then(executor).should().execute(job3, applierContext); } @Test public void testExecute_NamespaceJob() throws Exception { ApplierContext applierContext = new ApplierContext.Builder() .setReapplying(true) .setUpdatesAsUpserts(true) .build(); Context context = mock(Context.class); NamespaceJob job = mock(NamespaceJob.class); given(metrics.getNamespaceBatchTimer().time()).willReturn(context); executor.execute(job, applierContext); then(metrics).should(atLeastOnce()).getNamespaceBatchTimer(); then(metrics.getNamespaceBatchTimer()).should().time(); then(context).should().close(); then(namespaceJobExecutor).should().apply(eq(job), eq(server), any(Boolean.class)); }
AbstractAnalyzedOp extends AnalyzedOp { @Override public Status<?> getMismatchErrorMessage() throws UnsupportedOperationException { if (!requiresMatch()) { throw new UnsupportedOperationException(); } return Status.from(ErrorCode.OPERATION_FAILED); } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type, @Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override KvValue<?> getMongoDocId(); @Override Status<?> getMismatchErrorMessage(); @Override KvDocument calculateDocToInsert(Function<AnalyzedOp, KvDocument> fetchedDocFun); }
@Test public void getMismatchErrorMessageTest() { AnalyzedOp op = getAnalyzedOp(defaultMongoDocId); if (op.getType().requiresMatch()) { Status<?> status = op.getMismatchErrorMessage(); assertNotNull( "The mismatch error of an analyzed operation that requires match must not be null", status); assertFalse("The mismatch error of an analyzed operation that requires match must not be OK", status.isOk()); } else { try { op.getMismatchErrorMessage(); fail("An analyzed operation that does not require match must throw a " + UnsupportedOperationException.class + " when its mismatch error is " + "requested"); } catch (UnsupportedOperationException ex) { } } }
AbstractAnalyzedOp extends AnalyzedOp { @Override public KvValue<?> getMongoDocId() { return mongoDocId; } AbstractAnalyzedOp(KvValue<?> mongoDocId, AnalyzedOpType type, @Nullable Function<KvDocument, KvDocument> calculateFun); @Override abstract String toString(); @Override AnalyzedOpType getType(); @Override KvValue<?> getMongoDocId(); @Override Status<?> getMismatchErrorMessage(); @Override KvDocument calculateDocToInsert(Function<AnalyzedOp, KvDocument> fetchedDocFun); }
@Test public void getMongoDocIdTest() { assertEquals("Unexpected mongo doc id.", defaultMongoDocId, getAnalyzedOp(defaultMongoDocId) .getMongoDocId()); }
FastMath { public static Vector2 rotateVector90(Vector2 v, Vector2 newVector) { float x = -v.y; float y = v.x; newVector.set(x, y); return newVector; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }
@Test public void testRotateVector90() { Vector2 v1 = new Vector2(1, 0); Vector2 expected = new Vector2(0, 1); Vector2 rotatedVector = FastMath.rotateVector90(v1); assertEquals( "wrong rotated vector calculation, expected: " + expected + ", calculated vector: " + rotatedVector, true, (expected.x == rotatedVector.x && expected.y == rotatedVector.y)); }
FastMath { public static boolean checkVectorsParallel(Vector2 v1, Vector2 v2) { Vector2 rotatedVector1 = rotateVector90(v1, Vector2Pool.create()); float dotProduct = rotatedVector1.dot(v2); Vector2Pool.free(rotatedVector1); return dotProduct == 0; } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }
@Test public void testCheckVectorsParallel() { Vector2 v1 = new Vector2(1, 1); Vector2 v2 = new Vector2(1, 1); assertEquals(true, FastMath.checkVectorsParallel(v1, v2)); assertEquals(true, FastMath.checkVectorsParallel(v2, v1)); Vector2 v3 = new Vector2(1, 2); assertEquals(false, FastMath.checkVectorsParallel(v1, v3)); assertEquals(false, FastMath.checkVectorsParallel(v3, v1)); Vector2 v4 = new Vector2(2, 2); assertEquals(true, FastMath.checkVectorsParallel(v1, v4)); assertEquals(true, FastMath.checkVectorsParallel(v4, v1)); }
FastMath { public static boolean checkIfLinesAreEquals(Line a, Line b) { if (!checkVectorsParallel(a.getDirection(), b.getDirection())) { return false; } Vector2 d = Vector2Pool.create(); d.set(a.getBase().x, a.getBase().y); d.sub(b.getBase()); Vector2Pool.free(d); return checkVectorsParallel(d, a.getDirection()); } static Vector2 rotateVector90(Vector2 v, Vector2 newVector); static Vector2 rotateVector90(Vector2 v); static boolean checkVectorsParallel(Vector2 v1, Vector2 v2); static boolean checkIfLinesAreEquals(Line a, Line b); }
@Test public void testCheckIfLinesAreEquals() { Line line1 = new Line(0, 0, 1, 1); Line line2 = new Line(0, 0, 1, 1); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line2)); assertEquals(true, FastMath.checkIfLinesAreEquals(line2, line1)); Line line3 = new Line(1, 1, 1, 1); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line3)); assertEquals(true, FastMath.checkIfLinesAreEquals(line3, line1)); Line line4 = new Line(0, 0, -1, 1); assertEquals(false, FastMath.checkIfLinesAreEquals(line1, line4)); assertEquals(false, FastMath.checkIfLinesAreEquals(line4, line1)); Line line5 = new Line(0, 0, 2, 2); assertEquals(true, FastMath.checkIfLinesAreEquals(line1, line5)); assertEquals(true, FastMath.checkIfLinesAreEquals(line5, line1)); }
CCircle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CCircle) { CCircle circle = (CCircle) obj; float dx = getCenterX() - circle.getCenterX(); float dy = getCenterY() - circle.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = radius + circle.radius; return distance <= radiusSum * radiusSum; } else if (obj instanceof CPoint) { return ColliderUtils.testCirclePointCollision(this, (CPoint) obj); } else { throw new IllegalArgumentException("shape class " + obj.getClass() + " isnt supported."); } } CCircle(float x, float y, float radius); @Override float getCenterX(); @Override float getCenterY(); float getRadius(); @Override boolean overlaps(CShape obj); @Override void drawShape(GameTime time, CameraWrapper camera, ShapeRenderer shapeRenderer, Color color); }
@Test public void testOverlapsCircle() { CCircle circle1 = new CCircle(0, 0, 50); CCircle circle2 = new CCircle(200, 200, 50); assertEquals(false, circle1.overlaps(circle2)); CCircle circle3 = new CCircle(100, 100, 50); assertEquals(false, circle1.overlaps(circle3)); CCircle circle4 = new CCircle(100, 0, 50); assertEquals(true, circle1.overlaps(circle4)); CCircle circle5 = new CCircle(100, 0, 55); assertEquals(true, circle1.overlaps(circle4)); }
CRectangle extends CShape { @Override public boolean overlaps(CShape obj) { if (obj instanceof CRectangle) { CRectangle rect = (CRectangle) obj; return x <= rect.getX() + rect.width && getX() + width >= rect.getX() && getY() <= rect.getY() + rect.height && getY() + height >= rect.getY(); } else { throw new IllegalArgumentException("shape class " + obj.getClass() + " isnt supported."); } } CRectangle(float x, float y, float width, float height); float getX(); float getY(); float getWidth(); float getHeight(); @Override float getCenterX(); @Override float getCenterY(); @Override boolean overlaps(CShape obj); @Override void drawShape(GameTime time, CameraWrapper camera, ShapeRenderer shapeRenderer, Color color); }
@Test public void testOverlapsRectangle() { CRectangle rect1 = new CRectangle(0, 0, 100, 100); CRectangle rect2 = new CRectangle(0, 0, 100, 100); assertEquals(true, rect1.overlaps(rect2)); CRectangle rect3 = new CRectangle(-10, -10, 5, 5); assertEquals(false, rect1.overlaps(rect3)); CRectangle rect4 = new CRectangle(100, 100, 100, 100); assertEquals(true, rect1.overlaps(rect4)); CRectangle rect5 = new CRectangle(50, 50, 100, 100); assertEquals(true, rect1.overlaps(rect5)); }
ColliderUtils { public static boolean overlaping(float minA, float maxA, float minB, float maxB) { if (maxA < minA) { float a = maxA; maxA = minA; minA = a; } if (maxB < minB) { float b = minB; maxB = minB; minB = b; } return minB <= maxA && minA <= maxB; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }
@Test public void testOverlaping() { assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(0, 1, 2, 3)); assertEquals("values arent overlaping, but method returns true.", false, ColliderUtils.overlaping(2, 3, 3.1f, 4)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(0, 3, 2, 3)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(3, 4, 2, 3)); assertEquals("values are overlaping, but method returns false.", true, ColliderUtils.overlaping(4, 3, 2, 3)); }
ColliderUtils { public static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2) { return rect1.overlaps(rect2); } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }
@Test public void testRectangleRectangleCollisionTest() { Rectangle rect1 = new Rectangle(0, 0, 100, 100); Rectangle rect2 = new Rectangle(99, 99, 100, 100); assertEquals("rectangle is overlaping, but collision test returns false.", true, ColliderUtils.testRectangleRectangleCollision(rect1, rect2)); }
ColliderUtils { public static boolean testCirclePointCollision(CCircle circle, CPoint point) { float dx = circle.getCenterX() - point.getCenterX(); float dy = circle.getCenterY() - point.getCenterY(); float distance = dx * dx + dy * dy; float radiusSum = circle.getRadius(); return distance <= radiusSum * radiusSum; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }
@Test public void testOverlapingCirclePoint() { CCircle circle = new CCircle(0, 0, 5); CPoint point1 = new CPoint(0, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point1)); CPoint point2 = new CPoint(5, 0); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point2)); CPoint point3 = new CPoint(10, 10); assertEquals(false, ColliderUtils.testCirclePointCollision(circle, point3)); CPoint point4 = new CPoint(0, -5); assertEquals(true, ColliderUtils.testCirclePointCollision(circle, point4)); }
ColliderUtils { public static boolean testLineCollision(Line a, Line b) { if (FastMath.checkVectorsParallel(a.getDirection(), b.getDirection())) { return FastMath.checkIfLinesAreEquals(a, b); } else { } return true; } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }
@Test public void testLineCollision() { Line line1 = new Line(0, 0, 1, 1); Line line2 = new Line(0, 0, 1, 1); assertEquals(true, ColliderUtils.testLineCollision(line1, line2)); Line line3 = new Line(0, 0, -1, -1); assertEquals(true, ColliderUtils.testLineCollision(line1, line3)); assertEquals(true, ColliderUtils.testLineCollision(line3, line1)); Line line4 = new Line(1, 1, 1, 1); assertEquals(true, ColliderUtils.testLineCollision(line1, line4)); assertEquals(true, ColliderUtils.testLineCollision(line4, line1)); Line line5 = new Line(1, 2, 1, 1); assertEquals(false, ColliderUtils.testLineCollision(line1, line5)); assertEquals(false, ColliderUtils.testLineCollision(line5, line1)); Line line6 = new Line(3, 5, 5, -1); Line line7 = new Line(3, 5, 5, 2); Line line8 = new Line(3, 2, 5, 2); Line line9 = new Line(8, 4, 5, -1); assertEquals(true, ColliderUtils.testLineCollision(line6, line7)); assertEquals(true, ColliderUtils.testLineCollision(line6, line8)); assertEquals(false, ColliderUtils.testLineCollision(line7, line8)); assertEquals(true, ColliderUtils.testLineCollision(line6, line9)); }
ColliderUtils { public static boolean testSegmentCollision(Segment a, Segment b) { Vector2 d = Vector2Pool.create(a.getPoint2()).sub(a.getPoint1()); Line axisA = LinePool.create(); axisA.setBase(a.getPoint1()); axisA.setDirection(d); Line axisB = LinePool.create(); if (onOneSide(axisA, b)) { LinePool.free(axisA, axisB); Vector2Pool.free(d); return false; } axisB.setBase(b.getPoint1()); d.set(b.getPoint2()); d = d.sub(b.getPoint1()); axisB.setDirection(d); if (onOneSide(axisB, a)) { LinePool.free(axisA, axisB); Vector2Pool.free(d); return false; } if (FastMath.checkVectorsParallel(axisA.getDirection(), axisB.getDirection())) { Range rangeA = a.projectSegment(axisA.getDirection()); Range rangeB = b.projectSegment(axisB.getDirection()); LinePool.free(axisA, axisB); Vector2Pool.free(d); return rangeA.overlaps(rangeB); } else { LinePool.free(axisA, axisB); Vector2Pool.free(d); return true; } } static boolean testRectangleRectangleCollision(Rectangle rect1, Rectangle rect2); static boolean testCircleCircleCollision(Circle circle1, Circle circle2); static boolean testCirclePointCollision(CCircle circle, CPoint point); static boolean testLineCollision(Line a, Line b); static boolean onOneSide(Line axis, Segment s); static boolean testSegmentCollision(Segment a, Segment b); static boolean overlaping(float minA, float maxA, float minB, float maxB); }
@Test public void testSegmentCollision() { Segment segment1 = new Segment(new Vector2(0, 0), new Vector2(1, 1)); Segment segment2 = new Segment(new Vector2(0, 0), new Vector2(1, 1)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment2)); assertEquals(true, ColliderUtils.testSegmentCollision(segment2, segment1)); Segment segment3 = new Segment(new Vector2(2, 2), new Vector2(3, 3)); assertEquals(false, ColliderUtils.testSegmentCollision(segment1, segment3)); assertEquals(false, ColliderUtils.testSegmentCollision(segment1, segment3)); Segment segment4 = new Segment(new Vector2(0.5f, 0.5f), new Vector2(0.8f, 0.8f)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment4)); assertEquals(true, ColliderUtils.testSegmentCollision(segment4, segment1)); Segment segment5 = new Segment(new Vector2(1, 1), new Vector2(0, 0)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment5)); assertEquals(true, ColliderUtils.testSegmentCollision(segment5, segment1)); Segment segment6 = new Segment(new Vector2(3, 4), new Vector2(11, 1)); Segment segment7 = new Segment(new Vector2(8, 4), new Vector2(11, 7)); assertEquals(false, ColliderUtils.testSegmentCollision(segment6, segment7)); assertEquals(false, ColliderUtils.testSegmentCollision(segment7, segment6)); Segment segment8 = new Segment(new Vector2(0, 1), new Vector2(1, 0)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment8)); assertEquals(true, ColliderUtils.testSegmentCollision(segment8, segment1)); Segment segment9 = new Segment(new Vector2(1, 0), new Vector2(0, 1)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment9)); assertEquals(true, ColliderUtils.testSegmentCollision(segment9, segment1)); Segment segment10 = new Segment(new Vector2(-1, -1), new Vector2(0, 0)); assertEquals(true, ColliderUtils.testSegmentCollision(segment1, segment10)); assertEquals(true, ColliderUtils.testSegmentCollision(segment10, segment1)); }
DemoController { @RequestMapping("/now") public String now(){ return "hello"; } @RequestMapping("/now") String now(); }
@Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now"); } }).andExpect(status().isOk()).andExpect(content().string("hello")); String contentAsString = resultActions.andReturn().getResponse().getContentAsString(); assertEquals(contentAsString, "hello"); }
Mockito { public static <T> When<T> when(T t){ return new When<T>(); } static T mock(Class<T> t); static When<T> when(T t); }
@Test public void testStub(){ when(mockList.get(0)).thenReturn(1); System.out.println(mockList.get(0)); } @Test public void testArgsMatch(){ when(mockList.get(anyInt())).thenReturn("Hello Chubin"); when(mockList.contains(argThat(new Contains("Chubin")))).thenReturn(true); assertEquals(mockList.get(1), "Hello Chubin"); assertTrue(mockList.contains("Chubin")); verify(mockList).get(anyInt()); } @Test public void testException(){ when(mockList.get(Integer.MAX_VALUE)).thenThrow(new ArrayIndexOutOfBoundsException("下标越界!")); System.out.println(mockList.get(Integer.MAX_VALUE)); } @Test public void testCallBack(){ when(mockList.get(Integer.MAX_VALUE)).thenAnswer(invocation -> { Object mock = invocation.getMock(); Object[] arguments = invocation.getArguments(); return new StringBuilder().append(mock).append(",").append(Arrays.asList(arguments)).toString(); }); System.out.println(mockList.get(Integer.MAX_VALUE)); verify(mockList).get(Integer.MAX_VALUE); }
Mockito { public static <T> T mock(Class<T> t){ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t); enhancer.setCallback(new MockMethodInterceptor()); return (T) enhancer.create(); } static T mock(Class<T> t); static When<T> when(T t); }
@Test public void testOrder(){ List simpleList1 = mock(List.class); List simpleList2 = mock(List.class); simpleList1.add("first call"); simpleList2.add("second call"); InOrder inOrder = inOrder(simpleList1, simpleList2); inOrder.verify(simpleList1).add("first call"); inOrder.verify(simpleList2).add("second call"); }
LogController { @RequestMapping("/now/{id}") @ResponseBody public LocalDateTime now(@PathVariable String id, HttpServletRequest request) { mdcThreadPool.execute(new Runnable() { @Override public void run() { MDC.put("traceId", request.getRequestURI()); logger.info("线程池任务执行-------1"); } }); logger.info("mdc context:{}", MDC.getCopyOfContextMap()); return LocalDateTime.now(); } @RequestMapping("/now/{id}") @ResponseBody LocalDateTime now(@PathVariable String id, HttpServletRequest request); @RequestMapping("/test/{id}") @ResponseBody String test(@PathVariable String id, HttpServletRequest request); @RequestMapping("/java/{id}") @ResponseBody String java(@PathVariable String id, HttpServletRequest request); @RequestMapping("/mdc/{id}") @ResponseBody String mdcController(@PathVariable String id, HttpServletRequest request); }
@Test public void now() throws Exception { ResultActions resultActions = this.mvc.perform(new RequestBuilder() { @Override public MockHttpServletRequest buildRequest(ServletContext servletContext) { return new MockHttpServletRequest(RequestMethod.GET.name(), "/now/1"); } }).andExpect(status().isOk()); String contentAsString = resultActions.andReturn().getResponse().getContentAsString(); assertNotNull(contentAsString); }
MessagingAccessPointAdapter { public static MessagingAccessPoint getMessagingAccessPoint(String url, KeyValue attributes) { AccessPointURI accessPointURI = new AccessPointURI(url); String driverImpl = parseDriverImpl(accessPointURI.getDriverType(), attributes); attributes.put(OMSBuiltinKeys.ACCESS_POINTS, accessPointURI.getHosts()); attributes.put(OMSBuiltinKeys.DRIVER_IMPL, driverImpl); attributes.put(OMSBuiltinKeys.REGION, accessPointURI.getRegion()); attributes.put(OMSBuiltinKeys.ACCOUNT_ID, accessPointURI.getAccountId()); try { Class<?> driverImplClass = Class.forName(driverImpl); Constructor constructor = driverImplClass.getConstructor(KeyValue.class); MessagingAccessPoint vendorImpl = (MessagingAccessPoint) constructor.newInstance(attributes); checkSpecVersion(OMS.specVersion, vendorImpl.version()); return vendorImpl; } catch (Throwable e) { throw generateException(OMSResponseStatus.STATUS_10000, url); } } static MessagingAccessPoint getMessagingAccessPoint(String url, KeyValue attributes); }
@Test public void getMessagingAccessPoint() { String testURI = "oms:test-vendor: KeyValue keyValue = OMS.newKeyValue(); keyValue.put(OMSBuiltinKeys.DRIVER_IMPL, "io.openmessaging.internal.TestVendor"); MessagingAccessPoint messagingAccessPoint = OMS.getMessagingAccessPoint(testURI, keyValue); assertThat(messagingAccessPoint).isExactlyInstanceOf(TestVendor.class); }
DefaultKeyValue implements KeyValue { @Override public Set<String> keySet() { return properties.keySet(); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short getShort(String key); @Override short getShort(String key, short defaultValue); @Override KeyValue put(String key, short value); @Override KeyValue put(String key, int value); @Override KeyValue put(String key, long value); @Override KeyValue put(String key, double value); @Override KeyValue put(String key, String value); @Override int getInt(String key); @Override int getInt(final String key, final int defaultValue); @Override long getLong(String key); @Override long getLong(final String key, final long defaultValue); @Override double getDouble(String key); @Override double getDouble(final String key, final double defaultValue); @Override String getString(String key); @Override String getString(final String key, final String defaultValue); @Override Set<String> keySet(); @Override boolean containsKey(String key); }
@Test public void testKeySet() throws Exception { keyValue.put("IndexKey", 123); assertThat(keyValue.keySet()).contains("IndexKey"); }
DefaultKeyValue implements KeyValue { @Override public boolean containsKey(String key) { return properties.containsKey(key); } DefaultKeyValue(); @Override KeyValue put(String key, boolean value); @Override boolean getBoolean(String key); @Override boolean getBoolean(String key, boolean defaultValue); @Override short getShort(String key); @Override short getShort(String key, short defaultValue); @Override KeyValue put(String key, short value); @Override KeyValue put(String key, int value); @Override KeyValue put(String key, long value); @Override KeyValue put(String key, double value); @Override KeyValue put(String key, String value); @Override int getInt(String key); @Override int getInt(final String key, final int defaultValue); @Override long getLong(String key); @Override long getLong(final String key, final long defaultValue); @Override double getDouble(String key); @Override double getDouble(final String key, final double defaultValue); @Override String getString(String key); @Override String getString(final String key, final String defaultValue); @Override Set<String> keySet(); @Override boolean containsKey(String key); }
@Test public void testContainsKey() throws Exception { keyValue.put("ContainsKey", 123); assertThat(keyValue.containsKey("ContainsKey")).isTrue(); }
AccessPointURI { public String getAccessPointString() { return accessPointString; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }
@Test public void testGetAccessPointString() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccessPointString()).isEqualTo(fullSchemaURI); }
AccessPointURI { public String getDriverType() { return driverType; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }
@Test public void testGetDriverType() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getDriverType()).isEqualTo("rocketmq"); }
AccessPointURI { public String getAccountId() { return accountId; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }
@Test public void testGetAccountId() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getAccountId()).isEqualTo("alice"); }
AccessPointURI { public String getHosts() { return hosts; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }
@Test public void testGetHosts() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org"); String multipleHostsURI = "oms:rocketmq: accessPointURI = new AccessPointURI(multipleHostsURI); assertThat(accessPointURI.getHosts()).isEqualTo("rocketmq.apache.org,pulsar.apache.org:9091"); }
AccessPointURI { public String getRegion() { return region; } AccessPointURI(String accessPointString); String getAccessPointString(); String getDriverType(); String getAccountId(); String getHosts(); String getRegion(); }
@Test public void testGetRegion() { AccessPointURI accessPointURI = new AccessPointURI(fullSchemaURI); assertThat(accessPointURI.getRegion()).isEqualTo("us-east"); }
TwitterMessageProducer extends MessageProducerSupport { StatusListener getStatusListener() { return statusListener; } TwitterMessageProducer(TwitterStream twitterStream, MessageChannel outputChannel); @Override void doStart(); @Override void doStop(); void setFollows(List<Long> follows); void setTerms(List<String> terms); }
@Test public void shouldReceiveStatus() { StatusListener statusListener = twitterMessageProducer.getStatusListener(); Status status = mock(Status.class); statusListener.onStatus(status); Message<?> statusMessage = outputChannel.receive(); assertSame(status, statusMessage.getPayload()); }
PhoenixPigSchemaUtil { public static ResourceSchema getResourceSchema(final Configuration configuration, Dependencies dependencies) throws IOException { final ResourceSchema schema = new ResourceSchema(); try { List<ColumnInfo> columns = null; final SchemaType schemaType = PhoenixConfigurationUtil.getSchemaType(configuration); if(SchemaType.QUERY.equals(schemaType)) { final String sqlQuery = PhoenixConfigurationUtil.getSelectStatement(configuration); Preconditions.checkNotNull(sqlQuery, "No Sql Query exists within the configuration"); final SqlQueryToColumnInfoFunction function = new SqlQueryToColumnInfoFunction(configuration); columns = function.apply(sqlQuery); } else { columns = dependencies.getSelectColumnMetadataList(configuration); } ResourceFieldSchema fields[] = new ResourceFieldSchema[columns.size()]; int i = 0; for(ColumnInfo cinfo : columns) { int sqlType = cinfo.getSqlType(); PDataType phoenixDataType = PDataType.fromTypeId(sqlType); byte pigType = TypeUtil.getPigDataTypeForPhoenixType(phoenixDataType); ResourceFieldSchema field = new ResourceFieldSchema(); field.setType(pigType).setName(cinfo.getDisplayName()); fields[i++] = field; } schema.setFields(fields); } catch(SQLException sqle) { LOG.error(String.format("Error: SQLException [%s] ",sqle.getMessage())); throw new IOException(sqle); } return schema; } private PhoenixPigSchemaUtil(); static ResourceSchema getResourceSchema(final Configuration configuration, Dependencies dependencies); static ResourceSchema getResourceSchema(final Configuration configuration); }
@Test public void testSchema() throws SQLException, IOException { final Configuration configuration = mock(Configuration.class); when(configuration.get(PhoenixConfigurationUtil.SCHEMA_TYPE)).thenReturn(SchemaType.TABLE.name()); final ResourceSchema actual = PhoenixPigSchemaUtil.getResourceSchema( configuration, new Dependencies() { List<ColumnInfo> getSelectColumnMetadataList( Configuration configuration) throws SQLException { return Lists.newArrayList(ID_COLUMN, NAME_COLUMN); } }); final ResourceFieldSchema[] fields = new ResourceFieldSchema[2]; fields[0] = new ResourceFieldSchema().setName("ID") .setType(DataType.LONG); fields[1] = new ResourceFieldSchema().setName("NAME") .setType(DataType.CHARARRAY); final ResourceSchema expected = new ResourceSchema().setFields(fields); assertEquals(expected.toString(), actual.toString()); } @Test(expected=IllegalDataException.class) public void testUnSupportedTypes() throws SQLException, IOException { final Configuration configuration = mock(Configuration.class); when(configuration.get(PhoenixConfigurationUtil.SCHEMA_TYPE)).thenReturn(SchemaType.TABLE.name()); PhoenixPigSchemaUtil.getResourceSchema( configuration, new Dependencies() { List<ColumnInfo> getSelectColumnMetadataList( Configuration configuration) throws SQLException { return Lists.newArrayList(ID_COLUMN, LOCATION_COLUMN); } }); fail("We currently don't support Array type yet. WIP!!"); }
IndexWriter implements Stoppable { public static IndexCommitter getCommitter(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexCommitter committer = conf.getClass(INDEX_COMMITTER_CONF_KEY, ParallelWriterIndexCommitter.class, IndexCommitter.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } IndexWriter(RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy, RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy); static IndexCommitter getCommitter(RegionCoprocessorEnvironment env); static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env); void writeAndKillYourselfOnFailure(Collection<Pair<Mutation, byte[]>> indexUpdates, boolean allowLocalUpdates); void writeAndKillYourselfOnFailure(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); void write(Collection<Pair<Mutation, byte[]>> toWrite); void write(Collection<Pair<Mutation, byte[]>> toWrite, boolean allowLocalUpdates); void write(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); @Override void stop(String why); @Override boolean isStopped(); static final String INDEX_FAILURE_POLICY_CONF_KEY; }
@Test public void getDefaultWriter() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getCommitter(env)); }
IndexWriter implements Stoppable { public static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env) throws IOException { Configuration conf = env.getConfiguration(); try { IndexFailurePolicy committer = conf.getClass(INDEX_FAILURE_POLICY_CONF_KEY, KillServerOnFailurePolicy.class, IndexFailurePolicy.class).newInstance(); return committer; } catch (InstantiationException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } } IndexWriter(RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy, RegionCoprocessorEnvironment env, String name); IndexWriter(IndexCommitter committer, IndexFailurePolicy policy); static IndexCommitter getCommitter(RegionCoprocessorEnvironment env); static IndexFailurePolicy getFailurePolicy(RegionCoprocessorEnvironment env); void writeAndKillYourselfOnFailure(Collection<Pair<Mutation, byte[]>> indexUpdates, boolean allowLocalUpdates); void writeAndKillYourselfOnFailure(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); void write(Collection<Pair<Mutation, byte[]>> toWrite); void write(Collection<Pair<Mutation, byte[]>> toWrite, boolean allowLocalUpdates); void write(Multimap<HTableInterfaceReference, Mutation> toWrite, boolean allowLocalUpdates); @Override void stop(String why); @Override boolean isStopped(); static final String INDEX_FAILURE_POLICY_CONF_KEY; }
@Test public void getDefaultFailurePolicy() throws Exception { Configuration conf = new Configuration(false); RegionCoprocessorEnvironment env = Mockito.mock(RegionCoprocessorEnvironment.class); Mockito.when(env.getConfiguration()).thenReturn(conf); assertNotNull(IndexWriter.getFailurePolicy(env)); }
MutationState implements SQLCloseable { public static int[] joinSortedIntArrays(int[] a, int[] b) { int[] result = new int[a.length + b.length]; int i = 0, j = 0, k = 0, current; while (i < a.length && j < b.length) { current = a[i] < b[j] ? a[i++] : b[j++]; for ( ; i < a.length && a[i] == current; i++); for ( ; j < b.length && b[j] == current; j++); result[k++] = current; } while (i < a.length) { for (current = a[i++] ; i < a.length && a[i] == current; i++); result[k++] = current; } while (j < b.length) { for (current = b[j++] ; j < b.length && b[j] == current; j++); result[k++] = current; } return Arrays.copyOf(result, k); } MutationState(long maxSize, PhoenixConnection connection); MutationState(long maxSize, PhoenixConnection connection, TransactionContext txContext); MutationState(MutationState mutationState); MutationState(long maxSize, PhoenixConnection connection, long sizeOffset); private MutationState(long maxSize, PhoenixConnection connection, Transaction tx, TransactionContext txContext); private MutationState(long maxSize, PhoenixConnection connection, Transaction tx, TransactionContext txContext, long sizeOffset); MutationState(long maxSize, PhoenixConnection connection, Map<TableRef, Map<ImmutableBytesPtr, RowMutationState>> mutations, Transaction tx, TransactionContext txContext); MutationState(TableRef table, Map<ImmutableBytesPtr,RowMutationState> mutations, long sizeOffset, long maxSize, PhoenixConnection connection); long getMaxSize(); void commitDDLFence(PTable dataTable); boolean checkpointIfNeccessary(MutationPlan plan); HTableInterface getHTable(PTable table); PhoenixConnection getConnection(); boolean isTransactionStarted(); long getInitialWritePointer(); long getWritePointer(); VisibilityLevel getVisibilityLevel(); boolean startTransaction(); static MutationState emptyMutationState(long maxSize, PhoenixConnection connection); long getUpdateCount(); void join(MutationState newMutationState); Iterator<Pair<byte[],List<Mutation>>> toMutations(Long timestamp); Iterator<Pair<byte[],List<Mutation>>> toMutations(); Iterator<Pair<byte[],List<Mutation>>> toMutations(final boolean includeMutableIndexes); Iterator<Pair<byte[],List<Mutation>>> toMutations(final boolean includeMutableIndexes, final Long tableTimestamp); static long getMutationTimestamp(final Long tableTimestamp, Long scn); long getMaxSizeBytes(); long getBatchCount(); static List<List<Mutation>> getMutationBatchList(long maxSize, long maxSizeBytes, List<Mutation> allMutationList); byte[] encodeTransaction(); static Transaction decodeTransaction(byte[] txnBytes); @Override void close(); void rollback(); void commit(); boolean sendUncommitted(); boolean sendUncommitted(Iterator<TableRef> tableRefs); void send(); static int[] joinSortedIntArrays(int[] a, int[] b); ReadMetricQueue getReadMetricQueue(); void setReadMetricQueue(ReadMetricQueue readMetricQueue); MutationMetricQueue getMutationMetricQueue(); }
@Test public void testJoinIntArrays() { int[] a = new int[] {1}; int[] b = new int[] {2}; int[] result = joinSortedIntArrays(a, b); assertEquals(2, result.length); assertArrayEquals(new int[] {1,2}, result); a = new int[0]; b = new int[0]; result = joinSortedIntArrays(a, b); assertEquals(0, result.length); assertArrayEquals(new int[] {}, result); a = new int[] {1,2,3}; b = new int[] {1,2,4}; result = joinSortedIntArrays(a, b); assertEquals(4, result.length); assertArrayEquals(new int[] {1,2,3,4}, result); a = new int[] {1,2,2,3}; b = new int[] {1,2,4}; result = joinSortedIntArrays(a, b); assertEquals(4, result.length); assertArrayEquals(new int[] {1,2,3,4}, result); }
OrderedResultIterator implements PeekingResultIterator { @Override public void close() throws SQLException { if (null != resultIterator) { resultIterator.close(); } resultIterator = PeekingResultIterator.EMPTY_ITERATOR; } OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions, int thresholdBytes, Integer limit, Integer offset); OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions, int thresholdBytes); OrderedResultIterator(ResultIterator delegate, List<OrderByExpression> orderByExpressions, int thresholdBytes, Integer limit, Integer offset,int estimatedRowSize); Integer getLimit(); long getEstimatedByteSize(); long getByteSize(); @Override Tuple next(); @Override Tuple peek(); @Override void close(); @Override void explain(List<String> planSteps); @Override String toString(); }
@Test public void testNullIteratorOnClose() throws SQLException { ResultIterator delegate = ResultIterator.EMPTY_ITERATOR; List<OrderByExpression> orderByExpressions = Collections.singletonList(null); int thresholdBytes = Integer.MAX_VALUE; OrderedResultIterator iterator = new OrderedResultIterator(delegate, orderByExpressions, thresholdBytes); iterator.close(); }
TypeUtil { public static Tuple transformToTuple(final PhoenixRecordWritable record, final ResourceFieldSchema[] projectedColumns) throws IOException { Map<String, Object> columnValues = record.getResultMap(); if (columnValues == null || columnValues.size() == 0 || projectedColumns == null || projectedColumns.length != columnValues.size()) { return null; } int numColumns = columnValues.size(); Tuple tuple = TUPLE_FACTORY.newTuple(numColumns); try { int i = 0; for (Map.Entry<String,Object> entry : columnValues.entrySet()) { final ResourceFieldSchema fieldSchema = projectedColumns[i]; Object object = entry.getValue(); if (object == null) { tuple.set(i++, null); continue; } switch (fieldSchema.getType()) { case DataType.BYTEARRAY: byte[] bytes = PDataType.fromTypeId(PBinary.INSTANCE.getSqlType()).toBytes(object); tuple.set(i, new DataByteArray(bytes, 0, bytes.length)); break; case DataType.CHARARRAY: tuple.set(i, DataType.toString(object)); break; case DataType.DOUBLE: tuple.set(i, DataType.toDouble(object)); break; case DataType.FLOAT: tuple.set(i, DataType.toFloat(object)); break; case DataType.INTEGER: tuple.set(i, DataType.toInteger(object)); break; case DataType.LONG: tuple.set(i, DataType.toLong(object)); break; case DataType.BOOLEAN: tuple.set(i, DataType.toBoolean(object)); break; case DataType.DATETIME: if (object instanceof java.sql.Timestamp) tuple.set(i,new DateTime(((java.sql.Timestamp)object).getTime())); else tuple.set(i,new DateTime(object)); break; case DataType.BIGDECIMAL: tuple.set(i, DataType.toBigDecimal(object)); break; case DataType.BIGINTEGER: tuple.set(i, DataType.toBigInteger(object)); break; case DataType.TUPLE: { PhoenixArray array = (PhoenixArray)object; Tuple t = TUPLE_FACTORY.newTuple(array.getDimensions());; for(int j = 0 ; j < array.getDimensions() ; j++) { t.set(j,array.getElement(j)); } tuple.set(i, t); break; } default: throw new RuntimeException(String.format(" Not supported [%s] pig type", fieldSchema)); } i++; } } catch (Exception ex) { final String errorMsg = String.format(" Error transforming PhoenixRecord to Tuple [%s] ", ex.getMessage()); LOG.error(errorMsg); throw new PigException(errorMsg); } return tuple; } private TypeUtil(); static PDataType getType(Object obj, byte type); static Object castPigTypeToPhoenix(Object o, byte objectType, PDataType targetPhoenixType); static Tuple transformToTuple(final PhoenixRecordWritable record, final ResourceFieldSchema[] projectedColumns); static Byte getPigDataTypeForPhoenixType(final PDataType phoenixDataType); }
@Test public void testTransformToTuple() throws Exception { PhoenixRecordWritable record = mock(PhoenixRecordWritable.class); Double[] doubleArr = new Double[2]; doubleArr[0] = 64.87; doubleArr[1] = 89.96; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PDouble.INSTANCE, doubleArr); Map<String,Object> values = Maps.newLinkedHashMap(); values.put("first", "213123"); values.put("second", 1231123); values.put("third", 31231231232131L); values.put("four", "bytearray".getBytes()); values.put("five", arr); when(record.getResultMap()).thenReturn(values); ResourceFieldSchema field = new ResourceFieldSchema().setType(DataType.CHARARRAY); ResourceFieldSchema field1 = new ResourceFieldSchema().setType(DataType.INTEGER); ResourceFieldSchema field2 = new ResourceFieldSchema().setType(DataType.LONG); ResourceFieldSchema field3 = new ResourceFieldSchema().setType(DataType.BYTEARRAY); ResourceFieldSchema field4 = new ResourceFieldSchema().setType(DataType.TUPLE); ResourceFieldSchema[] projectedColumns = { field, field1, field2, field3 , field4 }; Tuple t = TypeUtil.transformToTuple(record, projectedColumns); assertEquals(DataType.LONG, DataType.findType(t.get(2))); assertEquals(DataType.TUPLE, DataType.findType(t.get(4))); Tuple doubleArrayTuple = (Tuple)t.get(4); assertEquals(2,doubleArrayTuple.size()); field = new ResourceFieldSchema().setType(DataType.BIGDECIMAL); field1 = new ResourceFieldSchema().setType(DataType.BIGINTEGER); values.clear(); values.put("first", new BigDecimal(123123123.123213)); values.put("second", new BigInteger("1312313231312")); ResourceFieldSchema[] columns = { field, field1 }; t = TypeUtil.transformToTuple(record, columns); assertEquals(DataType.BIGDECIMAL, DataType.findType(t.get(0))); assertEquals(DataType.BIGINTEGER, DataType.findType(t.get(1))); }
CsvBulkImportUtil { @VisibleForTesting static Character getCharacter(Configuration conf, String confKey) { String strValue = conf.get(confKey); if (strValue == null) { return null; } return new String(Base64.decode(strValue)).charAt(0); } static void initCsvImportJob(Configuration conf, char fieldDelimiter, char quoteChar, char escapeChar, String arrayDelimiter, String binaryEncoding); static void configurePreUpsertProcessor(Configuration conf, Class<? extends ImportPreUpsertKeyValueProcessor> processorClass); static Path getOutputPath(Path outputdir, String tableName); }
@Test public void testGetChar_NotPresent() { Configuration conf = new Configuration(); assertNull(CsvBulkImportUtil.getCharacter(conf, "conf.key")); }
ScanRanges { public boolean intersectRegion(byte[] regionStartKey, byte[] regionEndKey, boolean isLocalIndex) { if (isEverything()) { return true; } if (isDegenerate()) { return false; } if (isLocalIndex) { return true; } boolean crossesSaltBoundary = isSalted && ScanUtil.crossesPrefixBoundary(regionEndKey, ScanUtil.getPrefix(regionStartKey, SaltingUtil.NUM_SALTING_BYTES), SaltingUtil.NUM_SALTING_BYTES); return intersectScan(null, regionStartKey, regionEndKey, 0, crossesSaltBoundary) == HAS_INTERSECTION; } private ScanRanges(RowKeySchema schema, int[] slotSpan, List<List<KeyRange>> ranges, KeyRange scanRange, KeyRange minMaxRange, boolean useSkipScanFilter, boolean isPointLookup, Integer bucketNum, TimeRange rowTimestampRange); static ScanRanges createPointLookup(List<KeyRange> keys); static ScanRanges createSingleSpan(RowKeySchema schema, List<List<KeyRange>> ranges); static ScanRanges createSingleSpan(RowKeySchema schema, List<List<KeyRange>> ranges, Integer nBuckets, boolean useSkipSan); static ScanRanges create(RowKeySchema schema, List<List<KeyRange>> ranges, int[] slotSpan, KeyRange minMaxRange, Integer nBuckets, boolean useSkipScan, int rowTimestampColIndex); KeyRange getMinMaxRange(); void initializeScan(Scan scan); static byte[] prefixKey(byte[] key, int keyOffset, byte[] prefixKey, int prefixKeyOffset); static byte[] stripPrefix(byte[] key, int keyOffset); Scan intersectScan(Scan scan, final byte[] originalStartKey, final byte[] originalStopKey, final int keyOffset, boolean crossesRegionBoundary); boolean intersectRegion(byte[] regionStartKey, byte[] regionEndKey, boolean isLocalIndex); SkipScanFilter getSkipScanFilter(); List<List<KeyRange>> getRanges(); List<List<KeyRange>> getBoundRanges(); RowKeySchema getSchema(); boolean isEverything(); boolean isDegenerate(); boolean useSkipScanFilter(); boolean isPointLookup(); int getPointLookupCount(); Iterator<KeyRange> getPointLookupKeyIterator(); int getBoundPkColumnCount(); int getBoundSlotCount(); @Override String toString(); int[] getSlotSpans(); boolean hasEqualityConstraint(int pkPosition); static TimeRange getDescTimeRange(KeyRange lowestKeyRange, KeyRange highestKeyRange, Field f); TimeRange getRowTimestampRange(); static final ScanRanges EVERYTHING; static final ScanRanges NOTHING; }
@Test public void test() { byte[] lowerInclusiveKey = keyRange.getLowerRange(); if (!keyRange.isLowerInclusive() && !Bytes.equals(lowerInclusiveKey, KeyRange.UNBOUND)) { lowerInclusiveKey = ByteUtil.nextKey(lowerInclusiveKey); } byte[] upperExclusiveKey = keyRange.getUpperRange(); if (keyRange.isUpperInclusive()) { upperExclusiveKey = ByteUtil.nextKey(upperExclusiveKey); } assertEquals(expectedResult, scanRanges.intersectRegion(lowerInclusiveKey,upperExclusiveKey,false)); }
ResourceList { Collection<String> getResourcesFromJarFile( final File file, final Pattern pattern) { final List<String> retVal = new ArrayList<>(); ZipFile zf; try { zf = new ZipFile(file); } catch (FileNotFoundException e) { return Collections.emptyList(); } catch (final ZipException e) { throw new Error(e); } catch (final IOException e) { throw new Error(e); } final Enumeration e = zf.entries(); while (e.hasMoreElements()) { final ZipEntry ze = (ZipEntry) e.nextElement(); final String fileName = ze.getName(); final boolean accept = pattern.matcher(fileName).matches(); logger.trace("fileName:" + fileName); logger.trace("File:" + file.toString()); logger.trace("Match:" + accept); if (accept) { logger.trace("Adding File from Jar: " + fileName); retVal.add("/" + fileName); } } try { zf.close(); } catch (final IOException e1) { throw new Error(e1); } return retVal; } ResourceList(String rootResourceDir); Collection<Path> getResourceList(final String pattern); }
@Test public void testMissingJarFileReturnsGracefully() { ResourceList rl = new ResourceList("foo"); File missingFile = new File("abracadabraphoenix.txt"); assertFalse("Did not expect a fake test file to actually exist", missingFile.exists()); assertEquals(Collections.emptyList(), rl.getResourcesFromJarFile(missingFile, Pattern.compile("pattern"))); }
PhoenixEmbeddedDriver implements Driver, SQLCloseable { @Override public boolean acceptsURL(String url) throws SQLException { if (url.startsWith(PhoenixRuntime.JDBC_PROTOCOL)) { if (url.length() == PhoenixRuntime.JDBC_PROTOCOL.length()) { return true; } if (PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR == url.charAt(PhoenixRuntime.JDBC_PROTOCOL.length())) { return true; } if (PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR == url.charAt(PhoenixRuntime.JDBC_PROTOCOL.length())) { int protoLength = PhoenixRuntime.JDBC_PROTOCOL.length() + 1; if (url.length() == protoLength) { return true; } if (url.startsWith(PhoenixRuntime.JDBC_THIN_PROTOCOL)) { return false; } if (!url.startsWith(DNC_JDBC_PROTOCOL_SUFFIX, protoLength)) { return true; } } } return false; } PhoenixEmbeddedDriver(); abstract QueryServices getQueryServices(); @Override boolean acceptsURL(String url); @Override Connection connect(String url, Properties info); @Override int getMajorVersion(); @Override int getMinorVersion(); @Override DriverPropertyInfo[] getPropertyInfo(String url, Properties info); @Override boolean jdbcCompliant(); @Override Logger getParentLogger(); @Override void close(); static boolean isTestUrl(String url); final static String MAJOR_VERSION_PROP; final static String MINOR_VERSION_PROP; final static String DRIVER_NAME_PROP; static final ReadOnlyProps DEFFAULT_PROPS; }
@Test public void testNotAccept() throws Exception { Driver driver = new PhoenixDriver(); assertFalse(driver.acceptsURL("jdbc:phoenix: assertFalse(driver.acceptsURL("jdbc:phoenix:localhost;test=true;bar=foo")); assertFalse(driver.acceptsURL("jdbc:phoenix:localhost;test=true")); assertTrue(driver.acceptsURL("jdbc:phoenix:localhost:123")); assertTrue(driver.acceptsURL("jdbc:phoenix:localhost:123;untest=true")); assertTrue(driver.acceptsURL("jdbc:phoenix:localhost:123;untest=true;foo=bar")); DriverManager.deregisterDriver(driver); }
Pherf { public static void main(String[] args) { try { new Pherf(args).run(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } Pherf(String[] args); static void main(String[] args); void run(); }
@Test public void testListArgument() { String[] args = {"-listFiles"}; Pherf.main(args); } @Test public void testUnknownOption() { String[] args = {"-drop", "all", "-q", "-m","-bsOption"}; exit.expectSystemExitWithStatus(1); Pherf.main(args); }
StatisticsScanner implements InternalScanner { @Override public void close() throws IOException { boolean async = getConfig().getBoolean(COMMIT_STATS_ASYNC, DEFAULT_COMMIT_STATS_ASYNC); StatisticsCollectionRunTracker collectionTracker = getStatsCollectionRunTracker(config); StatisticsScannerCallable callable = createCallable(); if (getRegionServerServices().isStopping() || getRegionServerServices().isStopped()) { LOG.debug("Not updating table statistics because the server is stopping/stopped"); return; } if (!async) { callable.call(); } else { collectionTracker.runTask(callable); } } StatisticsScanner(StatisticsCollector tracker, StatisticsWriter stats, RegionCoprocessorEnvironment env, InternalScanner delegate, ImmutableBytesPtr family); @Override boolean next(List<Cell> result); @Override boolean next(List<Cell> result, ScannerContext scannerContext); @Override void close(); }
@Test public void testCheckRegionServerStoppingOnClose() throws Exception { when(rsServices.isStopping()).thenReturn(true); when(rsServices.isStopped()).thenReturn(false); mockScanner.close(); verify(rsServices).isStopping(); verify(callable, never()).call(); verify(runTracker, never()).runTask(callable); } @Test public void testCheckRegionServerStoppedOnClose() throws Exception { when(rsServices.isStopping()).thenReturn(false); when(rsServices.isStopped()).thenReturn(true); mockScanner.close(); verify(rsServices).isStopping(); verify(rsServices).isStopped(); verify(callable, never()).call(); verify(runTracker, never()).runTask(callable); }
PhoenixQueryBuilder { public String buildQuery(JobConf jobConf, String tableName, List<String> readColumnList, String whereClause, Map<String, TypeInfo> columnTypeMap) throws IOException { String hints = getHint(jobConf, tableName); if (LOG.isDebugEnabled()) { LOG.debug("Building query with columns : " + readColumnList + " table name : " + tableName + " with where conditions : " + whereClause + " hints : " + hints); } return makeQueryString(jobConf, tableName, Lists.newArrayList(readColumnList), whereClause, QUERY_TEMPLATE, hints, columnTypeMap); } private PhoenixQueryBuilder(); static PhoenixQueryBuilder getInstance(); String buildQuery(JobConf jobConf, String tableName, List<String> readColumnList, String whereClause, Map<String, TypeInfo> columnTypeMap); String buildQuery(JobConf jobConf, String tableName, List<String> readColumnList, List<IndexSearchCondition> searchConditions); }
@Test public void testBuildQueryWithCharColumns() throws IOException { final String COLUMN_CHAR = "Column_Char"; final String COLUMN_VARCHAR = "Column_VChar"; final String expectedQueryPrefix = "select \"" + COLUMN_CHAR + "\",\"" + COLUMN_VARCHAR + "\" from TEST_TABLE where "; JobConf jobConf = new JobConf(); List<String> readColumnList = Lists.newArrayList(COLUMN_CHAR, COLUMN_VARCHAR); List<IndexSearchCondition> searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFOPEqual", "CHAR_VALUE", null, COLUMN_CHAR, "char(10)", false), mockedIndexSearchCondition("GenericUDFOPEqual", "CHAR_VALUE2", null, COLUMN_VARCHAR, "varchar(10)", false) ); assertEquals(expectedQueryPrefix + "\"Column_Char\" = 'CHAR_VALUE' and \"Column_VChar\" = 'CHAR_VALUE2'", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFIn", null, new Object[]{"CHAR1", "CHAR2", "CHAR3"}, COLUMN_CHAR, "char(10)", false) ); assertEquals(expectedQueryPrefix + "\"Column_Char\" in ('CHAR1', 'CHAR2', 'CHAR3')", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFIn", null, new Object[]{"CHAR1", "CHAR2", "CHAR3"}, COLUMN_CHAR, "char(10)", true) ); assertEquals(expectedQueryPrefix + "\"Column_Char\" not in ('CHAR1', 'CHAR2', 'CHAR3')", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFBetween", null, new Object[]{"CHAR1", "CHAR2"}, COLUMN_CHAR, "char(10)", false) ); assertEquals(expectedQueryPrefix + "\"Column_Char\" between 'CHAR1' and 'CHAR2'", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFBetween", null, new Object[]{"CHAR1", "CHAR2"}, COLUMN_CHAR, "char(10)", true) ); assertEquals(expectedQueryPrefix + "\"Column_Char\" not between 'CHAR1' and 'CHAR2'", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); } @Test public void testBuildBetweenQueryWithDateColumns() throws IOException { final String COLUMN_DATE = "Column_Date"; final String tableName = "TEST_TABLE"; final String expectedQueryPrefix = "select \"" + COLUMN_DATE + "\" from " + tableName + " where "; JobConf jobConf = new JobConf(); List<String> readColumnList = Lists.newArrayList(COLUMN_DATE); List<IndexSearchCondition> searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFBetween", null, new Object[]{"1992-01-02", "1992-02-02"}, COLUMN_DATE, "date", false) ); assertEquals(expectedQueryPrefix + "\"" + COLUMN_DATE + "\" between to_date('1992-01-02') and to_date('1992-02-02')", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFBetween", null, new Object[]{"1992-01-02", "1992-02-02"}, COLUMN_DATE, "date", true) ); assertEquals(expectedQueryPrefix + "\"" + COLUMN_DATE + "\" not between to_date('1992-01-02') and to_date('1992-02-02')", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); } @Test public void testBuildQueryWithNotNull() throws IOException { final String COLUMN_DATE = "Column_Date"; final String tableName = "TEST_TABLE"; final String expectedQueryPrefix = "select \"" + COLUMN_DATE + "\" from " + tableName + " where "; JobConf jobConf = new JobConf(); List<String> readColumnList = Lists.newArrayList(COLUMN_DATE); List<IndexSearchCondition> searchConditions = Lists.newArrayList( mockedIndexSearchCondition("GenericUDFOPNotNull", null, null, COLUMN_DATE, "date", true) ); assertEquals(expectedQueryPrefix + "\"" + COLUMN_DATE + "\" is not null ", BUILDER.buildQuery(jobConf, TABLE_NAME, readColumnList, searchConditions)); }
PhoenixRuntime { private static List<PColumn> getColumns(PTable table, List<Pair<String, String>> columns) throws SQLException { List<PColumn> pColumns = new ArrayList<PColumn>(columns.size()); for (Pair<String, String> column : columns) { pColumns.add(getColumn(table, column.getFirst(), column.getSecond())); } return pColumns; } private PhoenixRuntime(); static void main(String [] args); static int executeStatements(Connection conn, Reader reader, List<Object> binds); @Deprecated static List<KeyValue> getUncommittedData(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn, boolean includeMutableIndexes); static PTable getTableNoCache(Connection conn, String name); static PTable getTable(Connection conn, String name); static List<ColumnInfo> generateColumnInfo(Connection conn, String tableName, List<String> columns); static ColumnInfo getColumnInfo(PTable table, String columnName); static ColumnInfo getColumnInfo(PColumn pColumn); static QueryPlan getOptimizedQueryPlan(PreparedStatement stmt); static boolean hasOrderBy(QueryPlan plan); static int getLimit(QueryPlan plan); static List<Pair<String, String>> getPkColsForSql(Connection conn, QueryPlan plan); @Deprecated static void getPkColsForSql(List<Pair<String, String>> columns, QueryPlan plan, Connection conn, boolean forDataTable); @Deprecated static void getPkColsDataTypesForSql(List<Pair<String, String>> columns, List<String> dataTypes, QueryPlan plan, Connection conn, boolean forDataTable); static String getSqlTypeName(PColumn pCol); static String getSqlTypeName(PDataType dataType, Integer maxLength, Integer scale); static String getArraySqlTypeName(@Nullable Integer maxLength, @Nullable Integer scale, PDataType arrayType); @Deprecated static byte[] encodeValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); @Deprecated static Object[] decodeValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static byte[] encodeColumnValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); static Object[] decodeColumnValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static Expression getTenantIdExpression(Connection conn, String fullTableName); static Expression getFirstPKColumnExpression(Connection conn, String fullTableName); static Collection<GlobalMetric> getGlobalPhoenixClientMetrics(); static boolean areGlobalClientMetricsBeingCollected(); static Map<String, Map<String, Long>> getRequestReadMetrics(ResultSet rs); static Map<String, Long> getOverAllReadRequestMetrics(ResultSet rs); static Map<String, Map<String, Long>> getWriteMetricsForMutationsSinceLastReset(Connection conn); static Map<String, Map<String, Long>> getReadMetricsForMutationsSinceLastReset(Connection conn); static void resetMetrics(ResultSet rs); static void resetMetrics(Connection conn); static long getWallClockTimeFromCellTimeStamp(long tsOfCell); static long getCurrentScn(ReadOnlyProps props); final static String JDBC_PROTOCOL; final static String JDBC_THIN_PROTOCOL; final static char JDBC_PROTOCOL_TERMINATOR; final static char JDBC_PROTOCOL_SEPARATOR; @Deprecated final static String EMBEDDED_JDBC_PROTOCOL; static final String CURRENT_SCN_ATTRIB; static final String TENANT_ID_ATTRIB; static final String NO_UPGRADE_ATTRIB; final static String UPSERT_BATCH_SIZE_ATTRIB; final static String UPSERT_BATCH_SIZE_BYTES_ATTRIB; static final String AUTO_COMMIT_ATTRIB; static final String CONSISTENCY_ATTRIB; static final String REQUEST_METRIC_ATTRIB; final static String[] CONNECTION_PROPERTIES; final static String CONNECTIONLESS; static final String ANNOTATION_ATTRIB_PREFIX; static final String PHOENIX_TEST_DRIVER_URL_PARAM; static final String SCHEMA_ATTRIB; }
@Test public void testParseArguments_MinimalCase() { PhoenixRuntime.ExecutionCommand execCmd = PhoenixRuntime.ExecutionCommand.parseArgs( new String[] { "localhost", "test.csv" }); assertEquals( "localhost", execCmd.getConnectionString()); assertEquals( ImmutableList.of("test.csv"), execCmd.getInputFiles()); assertEquals(',', execCmd.getFieldDelimiter()); assertEquals('"', execCmd.getQuoteCharacter()); assertNull(execCmd.getEscapeCharacter()); assertNull(execCmd.getTableName()); assertNull(execCmd.getColumns()); assertFalse(execCmd.isStrict()); assertEquals( CSVCommonsLoader.DEFAULT_ARRAY_ELEMENT_SEPARATOR, execCmd.getArrayElementSeparator()); } @Test public void testParseArguments_FullOption() { PhoenixRuntime.ExecutionCommand execCmd = PhoenixRuntime.ExecutionCommand.parseArgs( new String[] { "-t", "mytable", "myzkhost:2181", "--strict", "file1.sql", "test.csv", "file2.sql", "--header", "one, two,three", "-a", "!", "-d", ":", "-q", "3", "-e", "4" }); assertEquals("myzkhost:2181", execCmd.getConnectionString()); assertEquals(ImmutableList.of("file1.sql", "test.csv", "file2.sql"), execCmd.getInputFiles()); assertEquals(':', execCmd.getFieldDelimiter()); assertEquals('3', execCmd.getQuoteCharacter()); assertEquals(Character.valueOf('4'), execCmd.getEscapeCharacter()); assertEquals("mytable", execCmd.getTableName()); assertEquals(ImmutableList.of("one", "two", "three"), execCmd.getColumns()); assertTrue(execCmd.isStrict()); assertEquals("!", execCmd.getArrayElementSeparator()); }
PhoenixRuntime { public static Expression getTenantIdExpression(Connection conn, String fullTableName) throws SQLException { PTable table = getTable(conn, fullTableName); if (!SchemaUtil.isMetaTable(table) && !SchemaUtil.isSequenceTable(table) && !table.isMultiTenant()) { return null; } return getFirstPKColumnExpression(table); } private PhoenixRuntime(); static void main(String [] args); static int executeStatements(Connection conn, Reader reader, List<Object> binds); @Deprecated static List<KeyValue> getUncommittedData(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn, boolean includeMutableIndexes); static PTable getTableNoCache(Connection conn, String name); static PTable getTable(Connection conn, String name); static List<ColumnInfo> generateColumnInfo(Connection conn, String tableName, List<String> columns); static ColumnInfo getColumnInfo(PTable table, String columnName); static ColumnInfo getColumnInfo(PColumn pColumn); static QueryPlan getOptimizedQueryPlan(PreparedStatement stmt); static boolean hasOrderBy(QueryPlan plan); static int getLimit(QueryPlan plan); static List<Pair<String, String>> getPkColsForSql(Connection conn, QueryPlan plan); @Deprecated static void getPkColsForSql(List<Pair<String, String>> columns, QueryPlan plan, Connection conn, boolean forDataTable); @Deprecated static void getPkColsDataTypesForSql(List<Pair<String, String>> columns, List<String> dataTypes, QueryPlan plan, Connection conn, boolean forDataTable); static String getSqlTypeName(PColumn pCol); static String getSqlTypeName(PDataType dataType, Integer maxLength, Integer scale); static String getArraySqlTypeName(@Nullable Integer maxLength, @Nullable Integer scale, PDataType arrayType); @Deprecated static byte[] encodeValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); @Deprecated static Object[] decodeValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static byte[] encodeColumnValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); static Object[] decodeColumnValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static Expression getTenantIdExpression(Connection conn, String fullTableName); static Expression getFirstPKColumnExpression(Connection conn, String fullTableName); static Collection<GlobalMetric> getGlobalPhoenixClientMetrics(); static boolean areGlobalClientMetricsBeingCollected(); static Map<String, Map<String, Long>> getRequestReadMetrics(ResultSet rs); static Map<String, Long> getOverAllReadRequestMetrics(ResultSet rs); static Map<String, Map<String, Long>> getWriteMetricsForMutationsSinceLastReset(Connection conn); static Map<String, Map<String, Long>> getReadMetricsForMutationsSinceLastReset(Connection conn); static void resetMetrics(ResultSet rs); static void resetMetrics(Connection conn); static long getWallClockTimeFromCellTimeStamp(long tsOfCell); static long getCurrentScn(ReadOnlyProps props); final static String JDBC_PROTOCOL; final static String JDBC_THIN_PROTOCOL; final static char JDBC_PROTOCOL_TERMINATOR; final static char JDBC_PROTOCOL_SEPARATOR; @Deprecated final static String EMBEDDED_JDBC_PROTOCOL; static final String CURRENT_SCN_ATTRIB; static final String TENANT_ID_ATTRIB; static final String NO_UPGRADE_ATTRIB; final static String UPSERT_BATCH_SIZE_ATTRIB; final static String UPSERT_BATCH_SIZE_BYTES_ATTRIB; static final String AUTO_COMMIT_ATTRIB; static final String CONSISTENCY_ATTRIB; static final String REQUEST_METRIC_ATTRIB; final static String[] CONNECTION_PROPERTIES; final static String CONNECTIONLESS; static final String ANNOTATION_ATTRIB_PREFIX; static final String PHOENIX_TEST_DRIVER_URL_PARAM; static final String SCHEMA_ATTRIB; }
@Test public void testGetTenantIdExpression() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); Expression e1 = PhoenixRuntime.getTenantIdExpression(conn, PhoenixDatabaseMetaData.SYSTEM_STATS_NAME); assertNull(e1); Expression e2 = PhoenixRuntime.getTenantIdExpression(conn, PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME); assertNotNull(e2); Expression e3 = PhoenixRuntime.getTenantIdExpression(conn, PhoenixDatabaseMetaData.SYSTEM_SEQUENCE_NAME); assertNotNull(e3); conn.createStatement().execute("CREATE TABLE FOO (k VARCHAR PRIMARY KEY)"); Expression e4 = PhoenixRuntime.getTenantIdExpression(conn, "FOO"); assertNull(e4); conn.createStatement().execute("CREATE TABLE A.BAR (k1 VARCHAR NOT NULL, k2 VARCHAR, CONSTRAINT PK PRIMARY KEY(K1,K2)) MULTI_TENANT=true"); Expression e5 = PhoenixRuntime.getTenantIdExpression(conn, "A.BAR"); assertNotNull(e5); conn.createStatement().execute("CREATE INDEX I1 ON A.BAR (K2)"); Expression e5A = PhoenixRuntime.getTenantIdExpression(conn, "A.I1"); assertNotNull(e5A); conn.createStatement().execute("CREATE TABLE BAS (k1 VARCHAR NOT NULL, k2 VARCHAR, CONSTRAINT PK PRIMARY KEY(K1,K2)) MULTI_TENANT=true, SALT_BUCKETS=3"); Expression e6 = PhoenixRuntime.getTenantIdExpression(conn, "BAS"); assertNotNull(e6); conn.createStatement().execute("CREATE INDEX I2 ON BAS (K2)"); Expression e6A = PhoenixRuntime.getTenantIdExpression(conn, "I2"); assertNotNull(e6A); try { PhoenixRuntime.getTenantIdExpression(conn, "NOT.ATABLE"); fail(); } catch (TableNotFoundException e) { } Properties props = PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES); props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, "t1"); Connection tsconn = DriverManager.getConnection(getUrl(), props); tsconn.createStatement().execute("CREATE VIEW V(V1 VARCHAR) AS SELECT * FROM BAS"); Expression e7 = PhoenixRuntime.getTenantIdExpression(tsconn, "V"); assertNotNull(e7); tsconn.createStatement().execute("CREATE LOCAL INDEX I3 ON V (V1)"); try { PhoenixRuntime.getTenantIdExpression(tsconn, "I3"); fail(); } catch (SQLFeatureNotSupportedException e) { } }
PhoenixRuntime { public static long getWallClockTimeFromCellTimeStamp(long tsOfCell) { return TxUtils.isPreExistingVersion(tsOfCell) ? tsOfCell : TransactionUtil.convertToMilliseconds(tsOfCell); } private PhoenixRuntime(); static void main(String [] args); static int executeStatements(Connection conn, Reader reader, List<Object> binds); @Deprecated static List<KeyValue> getUncommittedData(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn); static Iterator<Pair<byte[],List<KeyValue>>> getUncommittedDataIterator(Connection conn, boolean includeMutableIndexes); static PTable getTableNoCache(Connection conn, String name); static PTable getTable(Connection conn, String name); static List<ColumnInfo> generateColumnInfo(Connection conn, String tableName, List<String> columns); static ColumnInfo getColumnInfo(PTable table, String columnName); static ColumnInfo getColumnInfo(PColumn pColumn); static QueryPlan getOptimizedQueryPlan(PreparedStatement stmt); static boolean hasOrderBy(QueryPlan plan); static int getLimit(QueryPlan plan); static List<Pair<String, String>> getPkColsForSql(Connection conn, QueryPlan plan); @Deprecated static void getPkColsForSql(List<Pair<String, String>> columns, QueryPlan plan, Connection conn, boolean forDataTable); @Deprecated static void getPkColsDataTypesForSql(List<Pair<String, String>> columns, List<String> dataTypes, QueryPlan plan, Connection conn, boolean forDataTable); static String getSqlTypeName(PColumn pCol); static String getSqlTypeName(PDataType dataType, Integer maxLength, Integer scale); static String getArraySqlTypeName(@Nullable Integer maxLength, @Nullable Integer scale, PDataType arrayType); @Deprecated static byte[] encodeValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); @Deprecated static Object[] decodeValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static byte[] encodeColumnValues(Connection conn, String fullTableName, Object[] values, List<Pair<String, String>> columns); static Object[] decodeColumnValues(Connection conn, String fullTableName, byte[] value, List<Pair<String, String>> columns); static Expression getTenantIdExpression(Connection conn, String fullTableName); static Expression getFirstPKColumnExpression(Connection conn, String fullTableName); static Collection<GlobalMetric> getGlobalPhoenixClientMetrics(); static boolean areGlobalClientMetricsBeingCollected(); static Map<String, Map<String, Long>> getRequestReadMetrics(ResultSet rs); static Map<String, Long> getOverAllReadRequestMetrics(ResultSet rs); static Map<String, Map<String, Long>> getWriteMetricsForMutationsSinceLastReset(Connection conn); static Map<String, Map<String, Long>> getReadMetricsForMutationsSinceLastReset(Connection conn); static void resetMetrics(ResultSet rs); static void resetMetrics(Connection conn); static long getWallClockTimeFromCellTimeStamp(long tsOfCell); static long getCurrentScn(ReadOnlyProps props); final static String JDBC_PROTOCOL; final static String JDBC_THIN_PROTOCOL; final static char JDBC_PROTOCOL_TERMINATOR; final static char JDBC_PROTOCOL_SEPARATOR; @Deprecated final static String EMBEDDED_JDBC_PROTOCOL; static final String CURRENT_SCN_ATTRIB; static final String TENANT_ID_ATTRIB; static final String NO_UPGRADE_ATTRIB; final static String UPSERT_BATCH_SIZE_ATTRIB; final static String UPSERT_BATCH_SIZE_BYTES_ATTRIB; static final String AUTO_COMMIT_ATTRIB; static final String CONSISTENCY_ATTRIB; static final String REQUEST_METRIC_ATTRIB; final static String[] CONNECTION_PROPERTIES; final static String CONNECTIONLESS; static final String ANNOTATION_ATTRIB_PREFIX; static final String PHOENIX_TEST_DRIVER_URL_PARAM; static final String SCHEMA_ATTRIB; }
@Test public void testGetWallClockTimeFromCellTimeStamp() { long ts = System.currentTimeMillis(); assertEquals(ts, PhoenixRuntime.getWallClockTimeFromCellTimeStamp(ts)); long nanoTs = TransactionUtil.convertToNanoseconds(ts); assertEquals(ts, PhoenixRuntime.getWallClockTimeFromCellTimeStamp(nanoTs)); long skewedTs = ts + QueryConstants.MILLIS_IN_DAY; assertEquals(skewedTs, PhoenixRuntime.getWallClockTimeFromCellTimeStamp(skewedTs)); }
PropertiesUtil { public static Properties extractProperties(Properties props, final Configuration conf) { Iterator<Map.Entry<String, String>> iterator = conf.iterator(); if(iterator != null) { while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); props.setProperty(entry.getKey(), entry.getValue()); } } return props; } private PropertiesUtil(); static Properties deepCopy(Properties properties); static Properties extractProperties(Properties props, final Configuration conf); }
@Test public void testCopyFromConfiguration() throws Exception{ final Configuration conf = HBaseConfiguration.create(); final Properties props = new Properties(); conf.set(HConstants.ZOOKEEPER_QUORUM, HConstants.LOCALHOST); conf.set(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY, PropertiesUtilTest.SOME_OTHER_PROPERTY_VALUE); PropertiesUtil.extractProperties(props, conf); assertEquals(props.getProperty(HConstants.ZOOKEEPER_QUORUM), conf.get(HConstants.ZOOKEEPER_QUORUM)); assertEquals(props.getProperty(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY), conf.get(PropertiesUtilTest.SOME_OTHER_PROPERTY_KEY)); }
JDBCUtil { public static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info) { Preconditions.checkNotNull(url); Preconditions.checkNotNull(info); Map<String, String> combinedProperties = getCombinedConnectionProperties(url, info); Map<String, String> result = newHashMapWithExpectedSize(combinedProperties.size()); for (Map.Entry<String, String> prop : combinedProperties.entrySet()) { if (prop.getKey().startsWith(ANNOTATION_ATTRIB_PREFIX) && prop.getKey().length() > ANNOTATION_ATTRIB_PREFIX.length()) { result.put(prop.getKey().substring(ANNOTATION_ATTRIB_PREFIX.length()), prop.getValue()); } } return result; } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testGetCustomTracingAnnotationsWithNone() { String url = "localhost;TenantId=abc;"; Map<String, String> customAnnotations = JDBCUtil.getAnnotations(url, new Properties()); assertTrue(customAnnotations.isEmpty()); } @Test public void testGetCustomTracingAnnotationInBothPropertiesAndURL() { String annotKey1 = "key1"; String annotVal1 = "val1"; String annotKey2 = "key2"; String annotVal2 = "val2"; String annotKey3 = "key3"; String annotVal3 = "val3"; String url= "localhost;" + ANNOTATION_ATTRIB_PREFIX + annotKey1 + '=' + annotVal1; Properties prop = new Properties(); prop.put(ANNOTATION_ATTRIB_PREFIX + annotKey2, annotVal2); prop.put(ANNOTATION_ATTRIB_PREFIX + annotKey3, annotVal3); Map<String, String> customAnnotations = JDBCUtil.getAnnotations(url, prop); assertEquals(3, customAnnotations.size()); assertEquals(annotVal1, customAnnotations.get(annotKey1)); assertEquals(annotVal2, customAnnotations.get(annotKey2)); assertEquals(annotVal3, customAnnotations.get(annotKey3)); }
JDBCUtil { public static String removeProperty(String url, String propName) { String urlPropName = PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR + propName.toUpperCase() + "="; String upperCaseURL = url.toUpperCase(); int begIndex = upperCaseURL.indexOf(urlPropName); if (begIndex >= 0) { int endIndex = upperCaseURL.indexOf(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR, begIndex + urlPropName.length()); if (endIndex < 0) { endIndex = url.length(); } String prefix = url.substring(0, begIndex); String suffix = url.substring(endIndex, url.length()); return prefix + suffix; } else { return url; } } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testRemoveProperty() { assertEquals("localhost;", JDBCUtil.removeProperty("localhost;TenantId=abc;", TENANT_ID_ATTRIB)); assertEquals("localhost;foo=bar", JDBCUtil.removeProperty("localhost;TenantId=abc;foo=bar", TENANT_ID_ATTRIB)); assertEquals("localhost;TenantId=abc", JDBCUtil.removeProperty("localhost;TenantId=abc;foo=bar", "foo")); assertEquals("localhost;TenantId=abc;foo=bar", JDBCUtil.removeProperty("localhost;TenantId=abc;foo=bar", "bar")); }
JDBCUtil { public static boolean getAutoCommit(String url, Properties info, boolean defaultValue) { String autoCommit = findProperty(url, info, PhoenixRuntime.AUTO_COMMIT_ATTRIB); if (autoCommit == null) { return defaultValue; } return Boolean.valueOf(autoCommit); } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testGetAutoCommit_NotSpecified_DefaultTrue() { assertTrue(JDBCUtil.getAutoCommit("localhost", new Properties(), true)); } @Test public void testGetAutoCommit_NotSpecified_DefaultFalse() { assertFalse(JDBCUtil.getAutoCommit("localhost", new Properties(), false)); } @Test public void testGetAutoCommit_TrueInUrl() { assertTrue(JDBCUtil.getAutoCommit("localhost;AutoCommit=TrUe", new Properties(), false)); } @Test public void testGetAutoCommit_FalseInUrl() { assertFalse(JDBCUtil.getAutoCommit("localhost;AutoCommit=FaLse", new Properties(), false)); } @Test public void testGetAutoCommit_TrueInProperties() { Properties props = new Properties(); props.setProperty("AutoCommit", "true"); assertTrue(JDBCUtil.getAutoCommit("localhost", props, false)); } @Test public void testGetAutoCommit_FalseInProperties() { Properties props = new Properties(); props.setProperty("AutoCommit", "false"); assertFalse(JDBCUtil.getAutoCommit("localhost", props, false)); }
JDBCUtil { public static Consistency getConsistencyLevel(String url, Properties info, String defaultValue) { String consistency = findProperty(url, info, PhoenixRuntime.CONSISTENCY_ATTRIB); if(consistency != null && consistency.equalsIgnoreCase(Consistency.TIMELINE.toString())){ return Consistency.TIMELINE; } return Consistency.STRONG; } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testGetConsistency_TIMELINE_InUrl() { assertTrue(JDBCUtil.getConsistencyLevel("localhost;Consistency=TIMELINE", new Properties(), Consistency.STRONG.toString()) == Consistency.TIMELINE); } @Test public void testGetConsistency_TIMELINE_InProperties() { Properties props = new Properties(); props.setProperty(PhoenixRuntime.CONSISTENCY_ATTRIB, "TIMELINE"); assertTrue(JDBCUtil.getConsistencyLevel("localhost", props, Consistency.STRONG.toString()) == Consistency.TIMELINE); }
JDBCUtil { public static String getSchema(String url, Properties info, String defaultValue) { String schema = findProperty(url, info, PhoenixRuntime.SCHEMA_ATTRIB); return (schema == null || schema.equals("")) ? defaultValue : schema; } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testSchema() { assertTrue(JDBCUtil.getSchema("localhost;schema=TEST", new Properties(), null).equals("TEST")); assertNull(JDBCUtil.getSchema("localhost;schema=", new Properties(), null)); assertNull(JDBCUtil.getSchema("localhost;", new Properties(), null)); }
JDBCUtil { public static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props) throws SQLException { String batchSizeStr = findProperty(url, info, PhoenixRuntime.UPSERT_BATCH_SIZE_BYTES_ATTRIB); return (batchSizeStr == null ? props.getLong(QueryServices.MUTATE_BATCH_SIZE_BYTES_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES) : Long.parseLong(batchSizeStr)); } private JDBCUtil(); static String findProperty(String url, Properties info, String propName); static String removeProperty(String url, String propName); static Map<String, String> getAnnotations(@NotNull String url, @NotNull Properties info); static Long getCurrentSCN(String url, Properties info); @Deprecated // use getMutateBatchSizeBytes static int getMutateBatchSize(String url, Properties info, ReadOnlyProps props); static long getMutateBatchSizeBytes(String url, Properties info, ReadOnlyProps props); static @Nullable PName getTenantId(String url, Properties info); static boolean getAutoCommit(String url, Properties info, boolean defaultValue); static Consistency getConsistencyLevel(String url, Properties info, String defaultValue); static boolean isCollectingRequestLevelMetricsEnabled(String url, Properties overrideProps, ReadOnlyProps queryServicesProps); static String getSchema(String url, Properties info, String defaultValue); }
@Test public void testGetMaxMutateBytes() throws Exception { assertEquals(1000L, JDBCUtil.getMutateBatchSizeBytes("localhost;" + PhoenixRuntime.UPSERT_BATCH_SIZE_BYTES_ATTRIB + "=1000", new Properties(), ReadOnlyProps.EMPTY_PROPS)); Properties props = new Properties(); props.setProperty(PhoenixRuntime.UPSERT_BATCH_SIZE_BYTES_ATTRIB, "2000"); assertEquals(2000L, JDBCUtil.getMutateBatchSizeBytes("localhost", props, ReadOnlyProps.EMPTY_PROPS)); Map<String, String> propMap = Maps.newHashMap(); propMap.put(QueryServices.MUTATE_BATCH_SIZE_BYTES_ATTRIB, "3000"); ReadOnlyProps readOnlyProps = new ReadOnlyProps(propMap); assertEquals(3000L, JDBCUtil.getMutateBatchSizeBytes("localhost", new Properties(), readOnlyProps)); }
QueryUtil { public static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos) { if (columnInfos.isEmpty()) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } final List<String> columnNames = Lists.transform(columnInfos, new Function<ColumnInfo,String>() { @Override public String apply(ColumnInfo columnInfo) { return columnInfo.getColumnName(); } }); return constructUpsertStatement(tableName, columnNames, null); } private QueryUtil(); static String toSQL(CompareOp op); static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos); static String constructUpsertStatement(String tableName, List<String> columns, Hint hint); static String constructGenericUpsertStatement(String tableName, int numColumns); static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions); static String getUrl(String zkQuorum); static String getUrl(String zkQuorum, int clientPort); static String getUrl(String zkQuorum, String znodeParent); static String getUrl(String zkQuorum, int port, String znodeParent, String principal); static String getUrl(String zkQuorum, int port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent, String principal); static String getExplainPlan(ResultSet rs); static String getExplainPlan(ResultIterator iterator); static Connection getConnectionOnServer(Configuration conf); static Connection getConnectionOnServer(Properties props, Configuration conf); static Connection getConnection(Configuration conf); static String getConnectionUrl(Properties props, Configuration conf); static String getConnectionUrl(Properties props, Configuration conf, String principal); static String getViewStatement(String schemaName, String tableName, String where); static Integer getOffsetLimit(Integer limit, Integer offset); static Integer getRemainingOffset(Tuple offsetTuple); static String getViewPartitionClause(String partitionColumnName, long autoPartitionNum); static final int COLUMN_FAMILY_POSITION; static final int COLUMN_NAME_POSITION; static final int DATA_TYPE_POSITION; static final int DATA_TYPE_NAME_POSITION; }
@Test public void testConstructUpsertStatement_ColumnInfos() { assertEquals( "UPSERT INTO MYTAB (\"ID\", \"NAME\") VALUES (?, ?)", QueryUtil.constructUpsertStatement("MYTAB", ImmutableList.of(ID_COLUMN, NAME_COLUMN))); } @Test(expected=IllegalArgumentException.class) public void testConstructUpsertStatement_ColumnInfos_NoColumns() { QueryUtil.constructUpsertStatement("MYTAB", ImmutableList.<ColumnInfo>of()); }
QueryUtil { public static String constructGenericUpsertStatement(String tableName, int numColumns) { if (numColumns == 0) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } List<String> parameterList = Lists.newArrayListWithCapacity(numColumns); for (int i = 0; i < numColumns; i++) { parameterList.add("?"); } return String.format("UPSERT INTO %s VALUES (%s)", tableName, Joiner.on(", ").join(parameterList)); } private QueryUtil(); static String toSQL(CompareOp op); static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos); static String constructUpsertStatement(String tableName, List<String> columns, Hint hint); static String constructGenericUpsertStatement(String tableName, int numColumns); static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions); static String getUrl(String zkQuorum); static String getUrl(String zkQuorum, int clientPort); static String getUrl(String zkQuorum, String znodeParent); static String getUrl(String zkQuorum, int port, String znodeParent, String principal); static String getUrl(String zkQuorum, int port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent, String principal); static String getExplainPlan(ResultSet rs); static String getExplainPlan(ResultIterator iterator); static Connection getConnectionOnServer(Configuration conf); static Connection getConnectionOnServer(Properties props, Configuration conf); static Connection getConnection(Configuration conf); static String getConnectionUrl(Properties props, Configuration conf); static String getConnectionUrl(Properties props, Configuration conf, String principal); static String getViewStatement(String schemaName, String tableName, String where); static Integer getOffsetLimit(Integer limit, Integer offset); static Integer getRemainingOffset(Tuple offsetTuple); static String getViewPartitionClause(String partitionColumnName, long autoPartitionNum); static final int COLUMN_FAMILY_POSITION; static final int COLUMN_NAME_POSITION; static final int DATA_TYPE_POSITION; static final int DATA_TYPE_NAME_POSITION; }
@Test public void testConstructGenericUpsertStatement() { assertEquals( "UPSERT INTO MYTAB VALUES (?, ?)", QueryUtil.constructGenericUpsertStatement("MYTAB", 2)); } @Test(expected=IllegalArgumentException.class) public void testConstructGenericUpsertStatement_NoColumns() { QueryUtil.constructGenericUpsertStatement("MYTAB", 0); }
SqlQueryToColumnInfoFunction implements Function<String,List<ColumnInfo>> { @Override public List<ColumnInfo> apply(String sqlQuery) { Preconditions.checkNotNull(sqlQuery); Connection connection = null; List<ColumnInfo> columnInfos = null; try { connection = ConnectionUtil.getInputConnection(this.configuration); final Statement statement = connection.createStatement(); final PhoenixStatement pstmt = statement.unwrap(PhoenixStatement.class); final QueryPlan queryPlan = pstmt.compileQuery(sqlQuery); final List<? extends ColumnProjector> projectedColumns = queryPlan.getProjector().getColumnProjectors(); columnInfos = Lists.newArrayListWithCapacity(projectedColumns.size()); columnInfos = Lists.transform(projectedColumns, new Function<ColumnProjector,ColumnInfo>() { @Override public ColumnInfo apply(final ColumnProjector columnProjector) { return new ColumnInfo(columnProjector.getName(), columnProjector.getExpression().getDataType().getSqlType()); } }); } catch (SQLException e) { LOG.error(String.format(" Error [%s] parsing SELECT query [%s] ",e.getMessage(),sqlQuery)); throw new RuntimeException(e); } finally { if(connection != null) { try { connection.close(); } catch(SQLException sqle) { LOG.error("Error closing connection!!"); throw new RuntimeException(sqle); } } } return columnInfos; } SqlQueryToColumnInfoFunction(final Configuration configuration); @Override List<ColumnInfo> apply(String sqlQuery); }
@Test public void testValidSelectQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id integer not null, name varchar, age integer,location varchar " + " CONSTRAINT pk PRIMARY KEY (id))\n"; createTestTable(getUrl(), ddl); final String selectQuery = "SELECT name as a ,age AS b,UPPER(location) AS c FROM EMPLOYEE"; final ColumnInfo NAME_COLUMN = new ColumnInfo("A", Types.VARCHAR); final ColumnInfo AGE_COLUMN = new ColumnInfo("B", Types.INTEGER); final ColumnInfo LOCATION_COLUMN = new ColumnInfo("C", Types.VARCHAR); final List<ColumnInfo> expectedColumnInfos = ImmutableList.of(NAME_COLUMN, AGE_COLUMN,LOCATION_COLUMN); final List<ColumnInfo> actualColumnInfos = function.apply(selectQuery); Assert.assertEquals(expectedColumnInfos, actualColumnInfos); }
QueryUtil { public static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions) { Preconditions.checkNotNull(fullTableName,"Table name cannot be null"); if(columnInfos == null || columnInfos.isEmpty()) { throw new IllegalArgumentException("At least one column must be provided"); } StringBuilder query = new StringBuilder(); query.append("SELECT "); for (ColumnInfo cinfo : columnInfos) { if (cinfo != null) { String fullColumnName = getEscapedFullColumnName(cinfo.getColumnName()); query.append(fullColumnName); query.append(","); } } query.setLength(query.length() - 1); query.append(" FROM "); query.append(fullTableName); if(conditions != null && conditions.length() > 0) { query.append(" WHERE (").append(conditions).append(")"); } return query.toString(); } private QueryUtil(); static String toSQL(CompareOp op); static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos); static String constructUpsertStatement(String tableName, List<String> columns, Hint hint); static String constructGenericUpsertStatement(String tableName, int numColumns); static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions); static String getUrl(String zkQuorum); static String getUrl(String zkQuorum, int clientPort); static String getUrl(String zkQuorum, String znodeParent); static String getUrl(String zkQuorum, int port, String znodeParent, String principal); static String getUrl(String zkQuorum, int port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent, String principal); static String getExplainPlan(ResultSet rs); static String getExplainPlan(ResultIterator iterator); static Connection getConnectionOnServer(Configuration conf); static Connection getConnectionOnServer(Properties props, Configuration conf); static Connection getConnection(Configuration conf); static String getConnectionUrl(Properties props, Configuration conf); static String getConnectionUrl(Properties props, Configuration conf, String principal); static String getViewStatement(String schemaName, String tableName, String where); static Integer getOffsetLimit(Integer limit, Integer offset); static Integer getRemainingOffset(Tuple offsetTuple); static String getViewPartitionClause(String partitionColumnName, long autoPartitionNum); static final int COLUMN_FAMILY_POSITION; static final int COLUMN_NAME_POSITION; static final int DATA_TYPE_POSITION; static final int DATA_TYPE_NAME_POSITION; }
@Test public void testConstructSelectStatement() { assertEquals( "SELECT \"ID\",\"NAME\" FROM MYTAB", QueryUtil.constructSelectStatement("MYTAB", ImmutableList.of(ID_COLUMN,NAME_COLUMN),null)); } @Test public void testConstructSelectStatementWithSchema() { assertEquals( "SELECT \"ID\",\"NAME\" FROM A.MYTAB", QueryUtil.constructSelectStatement("A.MYTAB", ImmutableList.of(ID_COLUMN,NAME_COLUMN),null)); } @Test public void testConstructSelectStatementWithCaseSensitiveSchema() { final String tableName = "MYTAB"; final String schemaName = SchemaUtil.getEscapedArgument("a"); final String fullTableName = SchemaUtil.getTableName(schemaName, tableName); assertEquals( "SELECT \"ID\",\"NAME\" FROM \"a\".MYTAB", QueryUtil.constructSelectStatement(fullTableName, ImmutableList.of(ID_COLUMN,NAME_COLUMN),null)); } @Test public void testConstructSelectStatementWithCaseSensitiveTable() { final String tableName = SchemaUtil.getEscapedArgument("mytab"); final String schemaName = SchemaUtil.getEscapedArgument("a"); final String fullTableName = SchemaUtil.getTableName(schemaName, tableName); assertEquals( "SELECT \"ID\",\"NAME\" FROM \"a\".\"mytab\"", QueryUtil.constructSelectStatement(fullTableName, ImmutableList.of(ID_COLUMN,NAME_COLUMN),null)); }
QueryUtil { public static String getConnectionUrl(Properties props, Configuration conf) throws ClassNotFoundException, SQLException { return getConnectionUrl(props, conf, null); } private QueryUtil(); static String toSQL(CompareOp op); static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos); static String constructUpsertStatement(String tableName, List<String> columns, Hint hint); static String constructGenericUpsertStatement(String tableName, int numColumns); static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos,final String conditions); static String getUrl(String zkQuorum); static String getUrl(String zkQuorum, int clientPort); static String getUrl(String zkQuorum, String znodeParent); static String getUrl(String zkQuorum, int port, String znodeParent, String principal); static String getUrl(String zkQuorum, int port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent); static String getUrl(String zkQuorum, Integer port, String znodeParent, String principal); static String getExplainPlan(ResultSet rs); static String getExplainPlan(ResultIterator iterator); static Connection getConnectionOnServer(Configuration conf); static Connection getConnectionOnServer(Properties props, Configuration conf); static Connection getConnection(Configuration conf); static String getConnectionUrl(Properties props, Configuration conf); static String getConnectionUrl(Properties props, Configuration conf, String principal); static String getViewStatement(String schemaName, String tableName, String where); static Integer getOffsetLimit(Integer limit, Integer offset); static Integer getRemainingOffset(Tuple offsetTuple); static String getViewPartitionClause(String partitionColumnName, long autoPartitionNum); static final int COLUMN_FAMILY_POSITION; static final int COLUMN_NAME_POSITION; static final int DATA_TYPE_POSITION; static final int DATA_TYPE_NAME_POSITION; }
@Test public void testCreateConnectionFromConfiguration() throws Exception { Properties props = new Properties(); Configuration conf = new Configuration(false); conf.set(HConstants.ZOOKEEPER_QUORUM, "localhost"); conf.set(HConstants.ZOOKEEPER_CLIENT_PORT, "2181"); String conn = QueryUtil.getConnectionUrl(props, conf); validateUrl(conn); conf.set(HConstants.ZOOKEEPER_QUORUM, "host.at.some.domain.1,localhost," + "host.at.other.domain.3"); conn = QueryUtil.getConnectionUrl(props, conf); validateUrl(conn); conf.set("hbase.zookeeper.peerport", "3338"); conf.set("hbase.zookeeper.leaderport", "3339"); conn = QueryUtil.getConnectionUrl(props, conf); validateUrl(conn); }
ByteUtil { public static byte[] toBytes(byte[][] byteArrays) { int size = 0; for (byte[] b : byteArrays) { if (b == null) { size++; } else { size += b.length; size += WritableUtils.getVIntSize(b.length); } } TrustedByteArrayOutputStream bytesOut = new TrustedByteArrayOutputStream(size); DataOutputStream out = new DataOutputStream(bytesOut); try { for (byte[] b : byteArrays) { if (b == null) { WritableUtils.writeVInt(out, 0); } else { WritableUtils.writeVInt(out, b.length); out.write(b); } } } catch (IOException e) { throw new RuntimeException(e); } finally { try { out.close(); } catch (IOException e) { throw new RuntimeException(e); } } return bytesOut.getBuffer(); } static byte[] toBytes(byte[][] byteArrays); static byte[][] toByteArrays(byte[] b, int length); static byte[][] toByteArrays(byte[] b, int offset, int length); static byte[] serializeVIntArray(int[] intArray); static byte[] serializeVIntArray(int[] intArray, int encodedLength); static void serializeVIntArray(DataOutput output, int[] intArray); static void serializeVIntArray(DataOutput output, int[] intArray, int encodedLength); static long[] readFixedLengthLongArray(DataInput input, int length); static void writeFixedLengthLongArray(DataOutput output, long[] longArray); static int[] deserializeVIntArray(byte[] b); static int[] deserializeVIntArray(DataInput in); static int[] deserializeVIntArray(DataInput in, int length); static int[] deserializeVIntArray(byte[] b, int length); static byte[] concat(byte[] first, byte[]... rest); static T[] concat(T[] first, T[]... rest); static byte[] concat(SortOrder sortOrder, ImmutableBytesWritable... writables); static int vintFromBytes(byte[] buffer, int offset); static int vintFromBytes(ImmutableBytesWritable ptr); static long vlongFromBytes(ImmutableBytesWritable ptr); static int vintToBytes(byte[] result, int offset, final long vint); static byte[] nextKey(byte[] key); static boolean nextKey(byte[] key, int length); static boolean nextKey(byte[] key, int offset, int length); static byte[] previousKey(byte[] key); static boolean previousKey(byte[] key, int length); static boolean previousKey(byte[] key, int offset, int length); static byte[] fillKey(byte[] key, int length); static void nullPad(ImmutableBytesWritable ptr, int length); static int getSize(CharSequence sequence); static boolean isInclusive(CompareOp op); static boolean compare(CompareOp op, int compareResult); static byte[] copyKeyBytesIfNecessary(ImmutableBytesWritable ptr); static KeyRange getKeyRange(byte[] key, CompareOp op, PDataType type); static final byte[] EMPTY_BYTE_ARRAY; static final ImmutableBytesPtr EMPTY_BYTE_ARRAY_PTR; static final ImmutableBytesWritable EMPTY_IMMUTABLE_BYTE_ARRAY; static final Comparator<ImmutableBytesPtr> BYTES_PTR_COMPARATOR; }
@Test public void testSplitBytes() { byte[] startRow = Bytes.toBytes("EA"); byte[] stopRow = Bytes.toBytes("EZ"); byte[][] splitPoints = Bytes.split(startRow, stopRow, 10); for (byte[] splitPoint : splitPoints) { assertTrue(Bytes.toStringBinary(splitPoint), Bytes.compareTo(startRow, splitPoint) <= 0); assertTrue(Bytes.toStringBinary(splitPoint), Bytes.compareTo(stopRow, splitPoint) >= 0); } }
ByteUtil { public static int vintToBytes(byte[] result, int offset, final long vint) { long i = vint; if (i >= -112 && i <= 127) { result[offset] = (byte) i; return 1; } int len = -112; if (i < 0) { i ^= -1L; len = -120; } long tmp = i; while (tmp != 0) { tmp = tmp >> 8; len--; } result[offset++] = (byte) len; len = (len < -120) ? -(len + 120) : -(len + 112); for (int idx = len; idx != 0; idx--) { int shiftbits = (idx - 1) * 8; long mask = 0xFFL << shiftbits; result[offset++] = (byte)((i & mask) >> shiftbits); } return len + 1; } static byte[] toBytes(byte[][] byteArrays); static byte[][] toByteArrays(byte[] b, int length); static byte[][] toByteArrays(byte[] b, int offset, int length); static byte[] serializeVIntArray(int[] intArray); static byte[] serializeVIntArray(int[] intArray, int encodedLength); static void serializeVIntArray(DataOutput output, int[] intArray); static void serializeVIntArray(DataOutput output, int[] intArray, int encodedLength); static long[] readFixedLengthLongArray(DataInput input, int length); static void writeFixedLengthLongArray(DataOutput output, long[] longArray); static int[] deserializeVIntArray(byte[] b); static int[] deserializeVIntArray(DataInput in); static int[] deserializeVIntArray(DataInput in, int length); static int[] deserializeVIntArray(byte[] b, int length); static byte[] concat(byte[] first, byte[]... rest); static T[] concat(T[] first, T[]... rest); static byte[] concat(SortOrder sortOrder, ImmutableBytesWritable... writables); static int vintFromBytes(byte[] buffer, int offset); static int vintFromBytes(ImmutableBytesWritable ptr); static long vlongFromBytes(ImmutableBytesWritable ptr); static int vintToBytes(byte[] result, int offset, final long vint); static byte[] nextKey(byte[] key); static boolean nextKey(byte[] key, int length); static boolean nextKey(byte[] key, int offset, int length); static byte[] previousKey(byte[] key); static boolean previousKey(byte[] key, int length); static boolean previousKey(byte[] key, int offset, int length); static byte[] fillKey(byte[] key, int length); static void nullPad(ImmutableBytesWritable ptr, int length); static int getSize(CharSequence sequence); static boolean isInclusive(CompareOp op); static boolean compare(CompareOp op, int compareResult); static byte[] copyKeyBytesIfNecessary(ImmutableBytesWritable ptr); static KeyRange getKeyRange(byte[] key, CompareOp op, PDataType type); static final byte[] EMPTY_BYTE_ARRAY; static final ImmutableBytesPtr EMPTY_BYTE_ARRAY_PTR; static final ImmutableBytesWritable EMPTY_IMMUTABLE_BYTE_ARRAY; static final Comparator<ImmutableBytesPtr> BYTES_PTR_COMPARATOR; }
@Test public void testVIntToBytes() { for (int i = -10000; i <= 10000; i++) { byte[] vint = Bytes.vintToBytes(i); int vintSize = vint.length; byte[] vint2 = new byte[vint.length]; assertEquals(vintSize, ByteUtil.vintToBytes(vint2, 0, i)); assertTrue(Bytes.BYTES_COMPARATOR.compare(vint,vint2) == 0); } }
ByteUtil { public static byte[] nextKey(byte[] key) { byte[] nextStartRow = new byte[key.length]; System.arraycopy(key, 0, nextStartRow, 0, key.length); if (!nextKey(nextStartRow, nextStartRow.length)) { return null; } return nextStartRow; } static byte[] toBytes(byte[][] byteArrays); static byte[][] toByteArrays(byte[] b, int length); static byte[][] toByteArrays(byte[] b, int offset, int length); static byte[] serializeVIntArray(int[] intArray); static byte[] serializeVIntArray(int[] intArray, int encodedLength); static void serializeVIntArray(DataOutput output, int[] intArray); static void serializeVIntArray(DataOutput output, int[] intArray, int encodedLength); static long[] readFixedLengthLongArray(DataInput input, int length); static void writeFixedLengthLongArray(DataOutput output, long[] longArray); static int[] deserializeVIntArray(byte[] b); static int[] deserializeVIntArray(DataInput in); static int[] deserializeVIntArray(DataInput in, int length); static int[] deserializeVIntArray(byte[] b, int length); static byte[] concat(byte[] first, byte[]... rest); static T[] concat(T[] first, T[]... rest); static byte[] concat(SortOrder sortOrder, ImmutableBytesWritable... writables); static int vintFromBytes(byte[] buffer, int offset); static int vintFromBytes(ImmutableBytesWritable ptr); static long vlongFromBytes(ImmutableBytesWritable ptr); static int vintToBytes(byte[] result, int offset, final long vint); static byte[] nextKey(byte[] key); static boolean nextKey(byte[] key, int length); static boolean nextKey(byte[] key, int offset, int length); static byte[] previousKey(byte[] key); static boolean previousKey(byte[] key, int length); static boolean previousKey(byte[] key, int offset, int length); static byte[] fillKey(byte[] key, int length); static void nullPad(ImmutableBytesWritable ptr, int length); static int getSize(CharSequence sequence); static boolean isInclusive(CompareOp op); static boolean compare(CompareOp op, int compareResult); static byte[] copyKeyBytesIfNecessary(ImmutableBytesWritable ptr); static KeyRange getKeyRange(byte[] key, CompareOp op, PDataType type); static final byte[] EMPTY_BYTE_ARRAY; static final ImmutableBytesPtr EMPTY_BYTE_ARRAY_PTR; static final ImmutableBytesWritable EMPTY_IMMUTABLE_BYTE_ARRAY; static final Comparator<ImmutableBytesPtr> BYTES_PTR_COMPARATOR; }
@Test public void testNextKey() { byte[] key = new byte[] {1}; assertEquals((byte)2, ByteUtil.nextKey(key)[0]); key = new byte[] {1, (byte)255}; byte[] nextKey = ByteUtil.nextKey(key); byte[] expectedKey = new byte[] {2,(byte)0}; assertArrayEquals(expectedKey, nextKey); key = ByteUtil.concat(Bytes.toBytes("00D300000000XHP"), PInteger.INSTANCE.toBytes(Integer.MAX_VALUE)); nextKey = ByteUtil.nextKey(key); expectedKey = ByteUtil.concat(Bytes.toBytes("00D300000000XHQ"), PInteger.INSTANCE.toBytes(Integer.MIN_VALUE)); assertArrayEquals(expectedKey, nextKey); key = new byte[] {(byte)255}; assertNull(ByteUtil.nextKey(key)); }
QuerySchemaParserFunction implements Function<String,Pair<String,String>> { @Override public Pair<String, String> apply(final String selectStatement) { Preconditions.checkNotNull(selectStatement); Preconditions.checkArgument(!selectStatement.isEmpty(), "Select Query is empty!!"); Connection connection = null; try { connection = ConnectionUtil.getInputConnection(this.configuration); final Statement statement = connection.createStatement(); final PhoenixStatement pstmt = statement.unwrap(PhoenixStatement.class); final QueryPlan queryPlan = pstmt.compileQuery(selectStatement); isValidStatement(queryPlan); final String tableName = queryPlan.getTableRef().getTable().getName().getString(); final List<? extends ColumnProjector> projectedColumns = queryPlan.getProjector().getColumnProjectors(); final List<String> columns = Lists.transform(projectedColumns, new Function<ColumnProjector,String>() { @Override public String apply(ColumnProjector column) { return column.getName(); } }); final String columnsAsStr = Joiner.on(",").join(columns); return new Pair<String, String>(tableName, columnsAsStr); } catch (SQLException e) { LOG.error(String.format(" Error [%s] parsing SELECT query [%s] ",e.getMessage(),selectStatement)); throw new RuntimeException(e); } finally { if(connection != null) { try { connection.close(); } catch(SQLException sqle) { LOG.error(" Error closing connection "); throw new RuntimeException(sqle); } } } } QuerySchemaParserFunction(Configuration configuration); @Override Pair<String, String> apply(final String selectStatement); }
@Test(expected=RuntimeException.class) public void testSelectQuery() { final String selectQuery = "SELECT col1 FROM test"; function.apply(selectQuery); fail("Should fail as the table [test] doesn't exist"); } @Test public void testValidSelectQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id integer not null, name varchar, age integer,location varchar " + " CONSTRAINT pk PRIMARY KEY (id))\n"; createTestTable(getUrl(), ddl); final String selectQuery = "SELECT name,age,location FROM EMPLOYEE"; Pair<String,String> pair = function.apply(selectQuery); assertEquals(pair.getFirst(), "EMPLOYEE"); assertEquals(pair.getSecond(),Joiner.on(',').join("NAME","AGE","LOCATION")); } @Test(expected=RuntimeException.class) public void testUpsertQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id integer not null, name varchar, age integer,location varchar " + " CONSTRAINT pk PRIMARY KEY (id))\n"; createTestTable(getUrl(), ddl); final String upsertQuery = "UPSERT INTO EMPLOYEE (ID, NAME) VALUES (?, ?)"; function.apply(upsertQuery); fail(" Function call successful despite passing an UPSERT query"); } @Test(expected=IllegalArgumentException.class) public void testAggregationQuery() throws SQLException { String ddl = "CREATE TABLE EMPLOYEE " + " (id integer not null, name varchar, age integer,location varchar " + " CONSTRAINT pk PRIMARY KEY (id))\n"; createTestTable(getUrl(), ddl); final String selectQuery = "SELECT MAX(ID) FROM EMPLOYEE"; function.apply(selectQuery); fail(" Function call successful despite passing an aggreagate query"); }
DateUtil { public static Timestamp getTimestamp(long millis, int nanos) { if (nanos > MAX_ALLOWED_NANOS || nanos < 0) { throw new IllegalArgumentException("nanos > " + MAX_ALLOWED_NANOS + " or < 0"); } Timestamp ts = new Timestamp(millis); if (ts.getNanos() + nanos > MAX_ALLOWED_NANOS) { int millisToNanosConvertor = BigDecimal.valueOf(MILLIS_TO_NANOS_CONVERTOR).intValue(); int overFlowMs = (ts.getNanos() + nanos) / millisToNanosConvertor; int overFlowNanos = (ts.getNanos() + nanos) - (overFlowMs * millisToNanosConvertor); ts = new Timestamp(millis + overFlowMs); ts.setNanos(ts.getNanos() + overFlowNanos); } else { ts.setNanos(ts.getNanos() + nanos); } return ts; } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }
@Test public void testDemonstrateSetNanosOnTimestampLosingMillis() { Timestamp ts1 = new Timestamp(120055); ts1.setNanos(60); Timestamp ts2 = new Timestamp(120100); ts2.setNanos(60); assertTrue(ts1.equals(ts2)); ts1 = DateUtil.getTimestamp(120055, 60); ts2 = DateUtil.getTimestamp(120100, 60); assertFalse(ts1.equals(ts2)); assertTrue(ts2.after(ts1)); }
DateUtil { public static Date parseDate(String dateValue) { return new Date(parseDateTime(dateValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }
@Test public void testParseDate() { assertEquals(10000L, DateUtil.parseDate("1970-01-01 00:00:10").getTime()); } @Test public void testParseDate_PureDate() { assertEquals(0L, DateUtil.parseDate("1970-01-01").getTime()); } @Test(expected = IllegalDataException.class) public void testParseDate_InvalidDate() { DateUtil.parseDate("not-a-date"); } @Test(expected=IllegalDataException.class) public void testParseTime_InvalidTime() { DateUtil.parseDate("not-a-time"); }
DateUtil { public static Time parseTime(String timeValue) { return new Time(parseDateTime(timeValue)); } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }
@Test public void testParseTime() { assertEquals(10000L, DateUtil.parseTime("1970-01-01 00:00:10").getTime()); }
DateUtil { public static Timestamp parseTimestamp(String timestampValue) { Timestamp timestamp = new Timestamp(parseDateTime(timestampValue)); int period = timestampValue.indexOf('.'); if (period > 0) { String nanosStr = timestampValue.substring(period + 1); if (nanosStr.length() > 9) throw new IllegalDataException("nanos > 999999999 or < 0"); if(nanosStr.length() > 3 ) { int nanos = Integer.parseInt(nanosStr); for (int i = 0; i < 9 - nanosStr.length(); i++) { nanos *= 10; } timestamp.setNanos(nanos); } } return timestamp; } private DateUtil(); @NotNull static PDataCodec getCodecFor(PDataType type); static TimeZone getTimeZone(String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType, String timeZoneId); static DateTimeParser getDateTimeParser(String pattern, PDataType pDataType); static Format getDateFormatter(String pattern); static Format getTimeFormatter(String pattern); static Format getTimestampFormatter(String pattern); static Date parseDate(String dateValue); static Time parseTime(String timeValue); static Timestamp parseTimestamp(String timestampValue); static Timestamp getTimestamp(long millis, int nanos); static Timestamp getTimestamp(BigDecimal bd); static final String DEFAULT_TIME_ZONE_ID; static final String LOCAL_TIME_ZONE_ID; static final String DEFAULT_MS_DATE_FORMAT; static final Format DEFAULT_MS_DATE_FORMATTER; static final String DEFAULT_DATE_FORMAT; static final Format DEFAULT_DATE_FORMATTER; static final String DEFAULT_TIME_FORMAT; static final Format DEFAULT_TIME_FORMATTER; static final String DEFAULT_TIMESTAMP_FORMAT; static final Format DEFAULT_TIMESTAMP_FORMATTER; }
@Test public void testParseTimestamp() { assertEquals(10000L, DateUtil.parseTimestamp("1970-01-01 00:00:10").getTime()); } @Test public void testParseTimestamp_WithMillis() { assertEquals(10123L, DateUtil.parseTimestamp("1970-01-01 00:00:10.123").getTime()); } @Test public void testParseTimestamp_WithNanos() { assertEquals(123000000, DateUtil.parseTimestamp("1970-01-01 00:00:10.123").getNanos()); assertEquals(123456780, DateUtil.parseTimestamp("1970-01-01 00:00:10.12345678").getNanos ()); assertEquals(999999999, DateUtil.parseTimestamp("1970-01-01 00:00:10.999999999").getNanos ()); } @Test(expected=IllegalDataException.class) public void testParseTimestamp_tooLargeNanos() { DateUtil.parseTimestamp("1970-01-01 00:00:10.9999999999"); } @Test(expected=IllegalDataException.class) public void testParseTimestamp_missingNanos() { DateUtil.parseTimestamp("1970-01-01 00:00:10."); } @Test(expected=IllegalDataException.class) public void testParseTimestamp_negativeNanos() { DateUtil.parseTimestamp("1970-01-01 00:00:10.-1"); } @Test(expected=IllegalDataException.class) public void testParseTimestamp_InvalidTimestamp() { DateUtil.parseTimestamp("not-a-timestamp"); }
MetaDataUtil { public static long encodeVersion(String hbaseVersionStr, Configuration config) { long hbaseVersion = VersionUtil.encodeVersion(hbaseVersionStr); long isTableNamespaceMappingEnabled = SchemaUtil.isNamespaceMappingEnabled(PTableType.TABLE, new ReadOnlyProps(config.iterator())) ? 1 : 0; long phoenixVersion = VersionUtil.encodeVersion(MetaDataProtocol.PHOENIX_MAJOR_VERSION, MetaDataProtocol.PHOENIX_MINOR_VERSION, MetaDataProtocol.PHOENIX_PATCH_NUMBER); long walCodec = IndexManagementUtil.isWALEditCodecSet(config) ? 0 : 1; long version = (hbaseVersion << (Byte.SIZE * 5)) | (isTableNamespaceMappingEnabled << (Byte.SIZE * 4)) | (phoenixVersion << (Byte.SIZE * 1)) | walCodec; return version; } static boolean areClientAndServerCompatible(long serverHBaseAndPhoenixVersion); static int decodePhoenixVersion(long version); static long encodeHasIndexWALCodec(long version, boolean isValid); static boolean decodeHasIndexWALCodec(long version); static int decodeHBaseVersion(long version); static String decodeHBaseVersionAsString(int version); static boolean decodeTableNamespaceMappingEnabled(long version); static long encodeVersion(String hbaseVersionStr, Configuration config); static void getTenantIdAndSchemaAndTableName(List<Mutation> tableMetadata, byte[][] rowKeyMetaData); static void getTenantIdAndFunctionName(List<Mutation> functionMetadata, byte[][] rowKeyMetaData); static byte[] getParentTableName(List<Mutation> tableMetadata); static long getSequenceNumber(Mutation tableMutation); static long getSequenceNumber(List<Mutation> tableMetaData); static PTableType getTableType(List<Mutation> tableMetaData, KeyValueBuilder builder, ImmutableBytesWritable value); static long getParentSequenceNumber(List<Mutation> tableMetaData); static Mutation getTableHeaderRow(List<Mutation> tableMetaData); static boolean getMutationValue(Mutation headerRow, byte[] key, KeyValueBuilder builder, ImmutableBytesWritable ptr); static Put getPutOnlyTableHeaderRow(List<Mutation> tableMetaData); static Put getPutOnlyAutoPartitionColumn(PTable parentTable, List<Mutation> tableMetaData); static Mutation getParentTableHeaderRow(List<Mutation> tableMetaData); static long getClientTimeStamp(List<Mutation> tableMetadata); static long getClientTimeStamp(Mutation m); static byte[] getParentLinkKey(String tenantId, String schemaName, String tableName, String indexName); static byte[] getParentLinkKey(byte[] tenantId, byte[] schemaName, byte[] tableName, byte[] indexName); static boolean isMultiTenant(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static boolean isTransactional(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static boolean isSalted(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static byte[] getViewIndexPhysicalName(byte[] physicalTableName); static String getViewIndexTableName(String tableName); static String getViewIndexSchemaName(String schemaName); static String getViewIndexName(String schemaName, String tableName); static byte[] getIndexPhysicalName(byte[] physicalTableName, String indexPrefix); static String getIndexPhysicalName(String physicalTableName, String indexPrefix); static byte[] getLocalIndexPhysicalName(byte[] physicalTableName); static String getLocalIndexTableName(String tableName); static String getLocalIndexSchemaName(String schemaName); static String getLocalIndexUserTableName(String localIndexTableName); static String getViewIndexUserTableName(String viewIndexTableName); static String getViewIndexSequenceSchemaName(PName physicalName, boolean isNamespaceMapped); static String getViewIndexSequenceName(PName physicalName, PName tenantId, boolean isNamespaceMapped); static SequenceKey getViewIndexSequenceKey(String tenantId, PName physicalName, int nSaltBuckets, boolean isNamespaceMapped); static PDataType getViewIndexIdDataType(); static String getViewIndexIdColumnName(); static boolean hasViewIndexTable(PhoenixConnection connection, PName physicalName); static boolean hasViewIndexTable(PhoenixConnection connection, byte[] physicalTableName); static boolean hasLocalIndexTable(PhoenixConnection connection, PName physicalName); static boolean hasLocalIndexTable(PhoenixConnection connection, byte[] physicalTableName); static boolean hasLocalIndexColumnFamily(HTableDescriptor desc); static List<byte[]> getNonLocalIndexColumnFamilies(HTableDescriptor desc); static List<byte[]> getLocalIndexColumnFamilies(PhoenixConnection conn, byte[] physicalTableName); static void deleteViewIndexSequences(PhoenixConnection connection, PName name, boolean isNamespaceMapped); static boolean tableRegionsOnline(Configuration conf, PTable table); static Scan newTableRowsScan(byte[] key, long startTimeStamp, long stopTimeStamp); static Scan newTableRowsScan(byte[] startKey, byte[] stopKey, long startTimeStamp, long stopTimeStamp); static LinkType getLinkType(Mutation tableMutation); static boolean isLocalIndex(String physicalName); static boolean isViewIndex(String physicalName); static String getAutoPartitionColumnName(PTable parentTable); static int getAutoPartitionColIndex(PTable parentTable); static String getJdbcUrl(RegionCoprocessorEnvironment env); static boolean isHColumnProperty(String propName); static boolean isHTableProperty(String propName); static boolean isLocalIndexFamily(ImmutableBytesPtr cfPtr); static boolean isLocalIndexFamily(byte[] cf); static final byte[] getPhysicalTableRowForView(PTable view); static final String VIEW_INDEX_TABLE_PREFIX; static final String LOCAL_INDEX_TABLE_PREFIX; static final String VIEW_INDEX_SEQUENCE_PREFIX; static final String VIEW_INDEX_SEQUENCE_NAME_PREFIX; static final byte[] VIEW_INDEX_SEQUENCE_PREFIX_BYTES; static final String PARENT_TABLE_KEY; static final byte[] PARENT_TABLE_KEY_BYTES; static final String IS_VIEW_INDEX_TABLE_PROP_NAME; static final byte[] IS_VIEW_INDEX_TABLE_PROP_BYTES; static final String IS_LOCAL_INDEX_TABLE_PROP_NAME; static final byte[] IS_LOCAL_INDEX_TABLE_PROP_BYTES; static final String DATA_TABLE_NAME_PROP_NAME; static final byte[] DATA_TABLE_NAME_PROP_BYTES; }
@Test public void testEncode() { assertEquals(VersionUtil.encodeVersion("0.94.5"),VersionUtil.encodeVersion("0.94.5-mapR")); assertTrue(VersionUtil.encodeVersion("0.94.6")>VersionUtil.encodeVersion("0.94.5-mapR")); assertTrue(VersionUtil.encodeVersion("0.94.6")>VersionUtil.encodeVersion("0.94.5")); assertTrue(VersionUtil.encodeVersion("0.94.1-mapR")>VersionUtil.encodeVersion("0.94")); assertTrue(VersionUtil.encodeVersion("1", "1", "3")>VersionUtil.encodeVersion("1", "1", "1")); }
MetaDataUtil { public static boolean getMutationValue(Mutation headerRow, byte[] key, KeyValueBuilder builder, ImmutableBytesWritable ptr) { List<Cell> kvs = headerRow.getFamilyCellMap().get(PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES); if (kvs != null) { for (Cell cell : kvs) { KeyValue kv = org.apache.hadoop.hbase.KeyValueUtil.ensureKeyValue(cell); if (builder.compareQualifier(kv, key, 0, key.length) ==0) { builder.getValueAsPtr(kv, ptr); return true; } } } return false; } static boolean areClientAndServerCompatible(long serverHBaseAndPhoenixVersion); static int decodePhoenixVersion(long version); static long encodeHasIndexWALCodec(long version, boolean isValid); static boolean decodeHasIndexWALCodec(long version); static int decodeHBaseVersion(long version); static String decodeHBaseVersionAsString(int version); static boolean decodeTableNamespaceMappingEnabled(long version); static long encodeVersion(String hbaseVersionStr, Configuration config); static void getTenantIdAndSchemaAndTableName(List<Mutation> tableMetadata, byte[][] rowKeyMetaData); static void getTenantIdAndFunctionName(List<Mutation> functionMetadata, byte[][] rowKeyMetaData); static byte[] getParentTableName(List<Mutation> tableMetadata); static long getSequenceNumber(Mutation tableMutation); static long getSequenceNumber(List<Mutation> tableMetaData); static PTableType getTableType(List<Mutation> tableMetaData, KeyValueBuilder builder, ImmutableBytesWritable value); static long getParentSequenceNumber(List<Mutation> tableMetaData); static Mutation getTableHeaderRow(List<Mutation> tableMetaData); static boolean getMutationValue(Mutation headerRow, byte[] key, KeyValueBuilder builder, ImmutableBytesWritable ptr); static Put getPutOnlyTableHeaderRow(List<Mutation> tableMetaData); static Put getPutOnlyAutoPartitionColumn(PTable parentTable, List<Mutation> tableMetaData); static Mutation getParentTableHeaderRow(List<Mutation> tableMetaData); static long getClientTimeStamp(List<Mutation> tableMetadata); static long getClientTimeStamp(Mutation m); static byte[] getParentLinkKey(String tenantId, String schemaName, String tableName, String indexName); static byte[] getParentLinkKey(byte[] tenantId, byte[] schemaName, byte[] tableName, byte[] indexName); static boolean isMultiTenant(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static boolean isTransactional(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static boolean isSalted(Mutation m, KeyValueBuilder builder, ImmutableBytesWritable ptr); static byte[] getViewIndexPhysicalName(byte[] physicalTableName); static String getViewIndexTableName(String tableName); static String getViewIndexSchemaName(String schemaName); static String getViewIndexName(String schemaName, String tableName); static byte[] getIndexPhysicalName(byte[] physicalTableName, String indexPrefix); static String getIndexPhysicalName(String physicalTableName, String indexPrefix); static byte[] getLocalIndexPhysicalName(byte[] physicalTableName); static String getLocalIndexTableName(String tableName); static String getLocalIndexSchemaName(String schemaName); static String getLocalIndexUserTableName(String localIndexTableName); static String getViewIndexUserTableName(String viewIndexTableName); static String getViewIndexSequenceSchemaName(PName physicalName, boolean isNamespaceMapped); static String getViewIndexSequenceName(PName physicalName, PName tenantId, boolean isNamespaceMapped); static SequenceKey getViewIndexSequenceKey(String tenantId, PName physicalName, int nSaltBuckets, boolean isNamespaceMapped); static PDataType getViewIndexIdDataType(); static String getViewIndexIdColumnName(); static boolean hasViewIndexTable(PhoenixConnection connection, PName physicalName); static boolean hasViewIndexTable(PhoenixConnection connection, byte[] physicalTableName); static boolean hasLocalIndexTable(PhoenixConnection connection, PName physicalName); static boolean hasLocalIndexTable(PhoenixConnection connection, byte[] physicalTableName); static boolean hasLocalIndexColumnFamily(HTableDescriptor desc); static List<byte[]> getNonLocalIndexColumnFamilies(HTableDescriptor desc); static List<byte[]> getLocalIndexColumnFamilies(PhoenixConnection conn, byte[] physicalTableName); static void deleteViewIndexSequences(PhoenixConnection connection, PName name, boolean isNamespaceMapped); static boolean tableRegionsOnline(Configuration conf, PTable table); static Scan newTableRowsScan(byte[] key, long startTimeStamp, long stopTimeStamp); static Scan newTableRowsScan(byte[] startKey, byte[] stopKey, long startTimeStamp, long stopTimeStamp); static LinkType getLinkType(Mutation tableMutation); static boolean isLocalIndex(String physicalName); static boolean isViewIndex(String physicalName); static String getAutoPartitionColumnName(PTable parentTable); static int getAutoPartitionColIndex(PTable parentTable); static String getJdbcUrl(RegionCoprocessorEnvironment env); static boolean isHColumnProperty(String propName); static boolean isHTableProperty(String propName); static boolean isLocalIndexFamily(ImmutableBytesPtr cfPtr); static boolean isLocalIndexFamily(byte[] cf); static final byte[] getPhysicalTableRowForView(PTable view); static final String VIEW_INDEX_TABLE_PREFIX; static final String LOCAL_INDEX_TABLE_PREFIX; static final String VIEW_INDEX_SEQUENCE_PREFIX; static final String VIEW_INDEX_SEQUENCE_NAME_PREFIX; static final byte[] VIEW_INDEX_SEQUENCE_PREFIX_BYTES; static final String PARENT_TABLE_KEY; static final byte[] PARENT_TABLE_KEY_BYTES; static final String IS_VIEW_INDEX_TABLE_PROP_NAME; static final byte[] IS_VIEW_INDEX_TABLE_PROP_BYTES; static final String IS_LOCAL_INDEX_TABLE_PROP_NAME; static final byte[] IS_LOCAL_INDEX_TABLE_PROP_BYTES; static final String DATA_TABLE_NAME_PROP_NAME; static final byte[] DATA_TABLE_NAME_PROP_BYTES; }
@Test public void testGetMutationKeyValue() throws Exception { String version = VersionInfo.getVersion(); KeyValueBuilder builder = KeyValueBuilder.get(version); byte[] row = Bytes.toBytes("row"); byte[] family = PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES; byte[] qualifier = Bytes.toBytes("qual"); byte[] value = Bytes.toBytes("generic-value"); KeyValue kv = builder.buildPut(wrap(row), wrap(family), wrap(qualifier), wrap(value)); Put put = new Put(row); KeyValueBuilder.addQuietly(put, builder, kv); ImmutableBytesPtr ptr = new ImmutableBytesPtr(); assertTrue(MetaDataUtil.getMutationValue(put, qualifier, builder, ptr)); assertEquals("Value returned doesn't match stored value for " + builder.getClass().getName() + "!", 0, ByteUtil.BYTES_PTR_COMPARATOR.compare(ptr, wrap(value))); if (builder != GenericKeyValueBuilder.INSTANCE) { builder = GenericKeyValueBuilder.INSTANCE; value = Bytes.toBytes("client-value"); kv = builder.buildPut(wrap(row), wrap(family), wrap(qualifier), wrap(value)); put = new Put(row); KeyValueBuilder.addQuietly(put, builder, kv); assertTrue(MetaDataUtil.getMutationValue(put, qualifier, builder, ptr)); assertEquals("Value returned doesn't match stored value for " + builder.getClass().getName() + "!", 0, ByteUtil.BYTES_PTR_COMPARATOR.compare(ptr, wrap(value))); assertFalse(MetaDataUtil.getMutationValue(put, Bytes.toBytes("not a match"), builder, ptr)); } }
IndexManagementUtil { public static void ensureMutableIndexingCorrectlyConfigured(Configuration conf) throws IllegalStateException { if (isWALEditCodecSet(conf)) { return; } String codecClass = INDEX_WAL_EDIT_CODEC_CLASS_NAME; String indexLogReaderName = INDEX_HLOG_READER_CLASS_NAME; try { Class.forName(indexLogReaderName); } catch (ClassNotFoundException e) { throw new IllegalStateException(codecClass + " is not installed, but " + indexLogReaderName + " hasn't been installed in hbase-site.xml under " + HLOG_READER_IMPL_KEY); } if (indexLogReaderName.equals(conf.get(HLOG_READER_IMPL_KEY, indexLogReaderName))) { if (conf.getBoolean(HConstants.ENABLE_WAL_COMPRESSION, false)) { throw new IllegalStateException( "WAL Compression is only supported with " + codecClass + ". You can install in hbase-site.xml, under " + WALCellCodec.WAL_CELL_CODEC_CLASS_KEY); } } else { throw new IllegalStateException(codecClass + " is not installed, but " + indexLogReaderName + " hasn't been installed in hbase-site.xml under " + HLOG_READER_IMPL_KEY); } } private IndexManagementUtil(); static boolean isWALEditCodecSet(Configuration conf); static void ensureMutableIndexingCorrectlyConfigured(Configuration conf); static ValueGetter createGetterFromScanner(Scanner scanner, byte[] currentRow); static boolean updateMatchesColumns(Collection<KeyValue> update, List<ColumnReference> columns); static boolean columnMatchesUpdate(List<ColumnReference> columns, Collection<KeyValue> update); static Scan newLocalStateScan(List<? extends Iterable<? extends ColumnReference>> refsArray); static Scan newLocalStateScan(Scan scan, List<? extends Iterable<? extends ColumnReference>> refsArray); static void rethrowIndexingException(Throwable e); static void setIfNotSet(Configuration conf, String key, int value); static final String INDEX_WAL_EDIT_CODEC_CLASS_NAME; static final String HLOG_READER_IMPL_KEY; static final String WAL_EDIT_CODEC_CLASS_KEY; }
@Test public void testUncompressedWal() throws Exception { Configuration conf = new Configuration(false); conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, IndexedWALEditCodec.class.getName()); IndexManagementUtil.ensureMutableIndexingCorrectlyConfigured(conf); conf = new Configuration(false); conf.set(IndexManagementUtil.HLOG_READER_IMPL_KEY, IndexedHLogReader.class.getName()); IndexManagementUtil.ensureMutableIndexingCorrectlyConfigured(conf); } @Test public void testCompressedWALWithCodec() throws Exception { Configuration conf = new Configuration(false); conf.setBoolean(HConstants.ENABLE_WAL_COMPRESSION, true); conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, IndexedWALEditCodec.class.getName()); IndexManagementUtil.ensureMutableIndexingCorrectlyConfigured(conf); } @Test(expected = IllegalStateException.class) public void testCompressedWALWithHLogReader() throws Exception { Configuration conf = new Configuration(false); conf.setBoolean(HConstants.ENABLE_WAL_COMPRESSION, true); conf.set(IndexManagementUtil.HLOG_READER_IMPL_KEY, IndexedHLogReader.class.getName()); IndexManagementUtil.ensureMutableIndexingCorrectlyConfigured(conf); }
CoveredColumnIndexCodec extends BaseIndexCodec { public static boolean checkRowKeyForAllNulls(byte[] bytes) { int keyCount = CoveredColumnIndexCodec.getPreviousInteger(bytes, bytes.length); int pos = bytes.length - Bytes.SIZEOF_INT; for (int i = 0; i < keyCount; i++) { int next = CoveredColumnIndexCodec.getPreviousInteger(bytes, pos); if (next > 0) { return false; } pos -= Bytes.SIZEOF_INT; } return true; } static CoveredColumnIndexCodec getCodecForTesting(List<ColumnGroup> groups); @Override void initialize(RegionCoprocessorEnvironment env); @Override Iterable<IndexUpdate> getIndexUpserts(TableState state, IndexMetaData context); @Override Iterable<IndexUpdate> getIndexDeletes(TableState state, IndexMetaData context); static List<KeyValue> getIndexKeyValueForTesting(byte[] pk, long timestamp, List<Pair<byte[], CoveredColumn>> values); static List<byte[]> getValues(byte[] bytes); static boolean checkRowKeyForAllNulls(byte[] bytes); @Override boolean isEnabled(Mutation m); static final byte[] INDEX_ROW_COLUMN_FAMILY; }
@Test public void testCheckRowKeyForAllNulls() { byte[] pk = new byte[] { 'a', 'b', 'z' }; byte[] result = EMPTY_INDEX_KEY; assertTrue("Didn't correctly read single element as being null in row key", CoveredColumnIndexCodec.checkRowKeyForAllNulls(result)); result = CoveredColumnIndexCodec.composeRowKey(pk, 0, Lists.newArrayList(toColumnEntry(new byte[0]), toColumnEntry(new byte[0]))); assertTrue("Didn't correctly read two elements as being null in row key", CoveredColumnIndexCodec.checkRowKeyForAllNulls(result)); result = CoveredColumnIndexCodec.composeRowKey(pk, 2, Arrays.asList(toColumnEntry(new byte[] { 1, 2 }))); assertFalse("Found a null key, when it wasn't!", CoveredColumnIndexCodec.checkRowKeyForAllNulls(result)); result = CoveredColumnIndexCodec.composeRowKey(pk, 2, Arrays.asList(toColumnEntry(new byte[] { 1, 2 }), toColumnEntry(new byte[0]))); assertFalse("Found a null key, when it wasn't!", CoveredColumnIndexCodec.checkRowKeyForAllNulls(result)); }
EmailValidator { public static boolean isValidEmail(CharSequence email) { return email != null && EMAIL_PATTERN.matcher(email).matches(); } static boolean isValidEmail(CharSequence email); static final Pattern EMAIL_PATTERN; }
@Test public void isValidEmail() throws Exception { assertThat(EmailValidator.isValidEmail("[email protected]")).isTrue(); }
SampleService { public static boolean start() { return true; } static boolean start(); }
@Test public void onStartCommand() throws Exception { assertThat(SampleService.start()).isTrue(); }
Calculator { public static double add(int firstOperand, double secondOperand) { return firstOperand + secondOperand; } static double add(int firstOperand, double secondOperand); }
@Test public void add() throws Exception { assertThat(Calculator.add(1, 2)).isEqualTo(3); }
BridgeServiceImpl implements BridgeService { @Override public BridgeDTO create(BridgeCreateDTO bridge) throws InvalidIpException, BridgeAlreadyExistsException, UserDoesNotExistException { if (!isIPv4Address(bridge.getIp())) { throw new InvalidIpException(bridge.getIp()); } else if (bridgeRepository.findByIp(bridge.getIp()) != null) { throw new BridgeAlreadyExistsException(bridge.getIp()); } User user = userRepository.findOne(bridge.getUserId()); if (user == null) { throw new UserDoesNotExistException(bridge.getUserId()); } Bridge b = new Bridge(); b.setIp(bridge.getIp()); b.setUser(user); b = bridgeRepository.save(b); BridgeDTO dto = mapper.map(b, BridgeDTO.class); hueService.connectToBridgeIfNotAlreadyConnected(dto); return dto; } @Autowired BridgeServiceImpl(UserRepository userRepository, BridgeRepository bridgeRepository, HueService hueService, Mapper mapper); @Override List<BridgeDTO> findAll(); @Override List<BridgeDTO> findAll(int page, int size); @Override List<FoundBridgeDTO> findAvailable(); @Override long count(); @Override List<BridgeDTO> findBySearchItem(String searchItem); @Override List<BridgeDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override BridgeDTO create(BridgeCreateDTO bridge); @Override BridgeDTO findByIp(String ip); @Override void remove(long id); }
@Test(expected = InvalidIpException.class) public void testCreateWithInvalidIp() { bridgeService.create(new BridgeCreateDTO("invalid", -1)); fail(); } @Test(expected = UserDoesNotExistException.class) public void testCreateWithoutValidUserId() { bridgeService.create(new BridgeCreateDTO("127.0.0.1", -1)); fail(); }
LampServiceImpl implements LampService { @Override public LampDTO create(LampCreateDTO lamp) throws EmptyInputException, TeamDoesNotExistException, LampAlreadyExistsException { if (lamp.getName() == null || lamp.getName().trim().isEmpty() || lamp.getHueUniqueId() == null || lamp.getHueUniqueId().trim().isEmpty()) { throw new EmptyInputException(); } Team team = teamRepository.findOne(lamp.getTeamId()); if (team == null) { throw new TeamDoesNotExistException(lamp.getTeamId()); } if (lampRepository.findByHueUniqueId(lamp.getHueUniqueId()) != null) { throw new LampAlreadyExistsException(lamp.getHueUniqueId()); } Lamp l = mapper.map(lamp, Lamp.class); l.setTeam(team); l.setWorkingStart(defaultWorkingStart()); l.setWorkingEnd(defaultWorkingEnd()); l.setScenarioConfigs(new ScenarioUtil().generateDefaultScenarioConfigs()); l = lampRepository.save(l); l.getTeam().getScenarioPriority().size(); l.getScenarioConfigs().size(); l.setScenarioConfigs(l.getScenarioConfigs()); return mapper.map(l, LampDTO.class); } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test(expected = LampAlreadyExistsException.class) public void testCreateWithDuplicateHueUniqueId() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())); lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())); fail(); } @Test public void testCreate() { assertEquals(0, lampService.count()); TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); LampCreateDTO lampCreateDTO = new LampCreateDTO("hueId", "Name 1", team.getId()); assertEquals(0, lampService.count(team.getId())); LampDTO lampDTO = lampService.create(lampCreateDTO); assertNull(lampDTO.getJobs()); assertNull(lampDTO.getLastShownScenario()); assertEquals(4, lampDTO.getScenarioConfigs().size()); assertNotNull(lampDTO.getWorkingStart()); assertNotNull(lampDTO.getWorkingEnd()); assertEquals(1, lampService.count(team.getId())); assertEquals(1, lampService.count()); assertEquals(0, lampService.count(-1)); Lamp lamp = lampRepository.findOne(lampDTO.getId()); assertEquals(lamp.getHueUniqueId(), lampDTO.getHueUniqueId()); } @Test(expected = EmptyInputException.class) public void testCreateWithoutValidName() { try { lampService.create(new LampCreateDTO("unique id", null, 0)); } catch(EmptyInputException eie) { lampService.create(new LampCreateDTO("unique id", "", 0)); } fail(); } @Test(expected = EmptyInputException.class) public void testCreateWithoutValidHueUniqueId() { try { lampService.create(new LampCreateDTO(null, "Lamp 1", 0)); } catch(EmptyInputException eie) { lampService.create(new LampCreateDTO("", "Lamp 1", 0)); } fail(); } @Test(expected = TeamDoesNotExistException.class) public void testCreateWithoutValidTeamId() { lampService.create(new LampCreateDTO("unique id", "Lamp 1", -1)); fail(); }
LampServiceImpl implements LampService { @Override public LampDTO update(LampUpdateDTO lamp) throws InvalidWorkingPeriodException, LampDoesNotExistsException { if (lamp.getWorkingStart() == null) { lamp.setWorkingStart(defaultWorkingStart()); } if (lamp.getWorkingEnd() == null) { lamp.setWorkingEnd(defaultWorkingEnd()); } DateTime start = new DateTime(lamp.getWorkingStart()); DateTime end = new DateTime(lamp.getWorkingEnd()); if (!holidayService.isValidWorkingPeriod(start, end)) { throw new InvalidWorkingPeriodException(start, end); } Lamp lampInDB = lampRepository.findOne(lamp.getId()); if (lampInDB == null) { throw new LampDoesNotExistsException(lamp.getId()); } Lamp lampUpdate = new Lamp(lampInDB.getId(), lampInDB.getHueUniqueId(), lampInDB.getName(), lamp.getWorkingStart(), lamp.getWorkingEnd(), null, lampInDB.getLastShownScenario(), null, lampInDB.getTeam()); lampUpdate.setJobs(mapper.mapList(lamp.getJobs(), Job.class)); lampUpdate.setScenarioConfigs(new ArrayList<>()); lampUpdate.getScenarioConfigs().addAll(mapper.mapList(lamp.getBuildingConfigs(), ScenarioConfig.class)); lampUpdate.getScenarioConfigs().addAll(mapper.mapList(lamp.getFailureConfigs(), ScenarioConfig.class)); lampUpdate.getScenarioConfigs().addAll(mapper.mapList(lamp.getUnstableConfigs(), ScenarioConfig.class)); lampUpdate.getScenarioConfigs().addAll(mapper.mapList(lamp.getSuccessConfigs(), ScenarioConfig.class)); lampUpdate = lampRepository.save(lampUpdate); return mapper.map(lampUpdate, LampDTO.class); } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test public void testUpdate() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); LampDTO lamp = lampService.create(new LampCreateDTO("unique id", "Lamp 1", team.getId())); assertNotNull(lamp.getWorkingStart()); assertNotNull(lamp.getWorkingEnd()); assertNull(lamp.getLastShownScenario()); assertNull(lamp.getJobs()); assertTrue(lamp.getScenarioConfigs() != null && lamp.getScenarioConfigs().size() > 0); LampUpdateDTO lampUpdate = new LampUpdateDTO(lamp.getId(), null, null, Collections.singletonList(new JobDTO(0, "Job 1")), null, null, null, null); lamp = lampService.update(lampUpdate); assertNotNull(lamp.getWorkingStart()); assertNotNull(lamp.getWorkingEnd()); assertEquals(1, lamp.getJobs().size()); assertEquals(0, lamp.getScenarioConfigs().size()); } @Test(expected = InvalidWorkingPeriodException.class) public void testUpdateWithInvalidWorkingPeriod() { Date workingStart = DateTime.now().withMillisOfDay(0).withHourOfDay(16).toDate(); Date workingEnd = DateTime.now().withMillisOfDay(0).withHourOfDay(6).toDate(); lampService.update(new LampUpdateDTO(0, workingStart, workingEnd, null, null, null, null, null)); fail(); } @Test(expected = LampDoesNotExistsException.class) public void testUpdateWithoutValidLampId() { lampService.update(new LampUpdateDTO(-1, null, null, null, null, null, null, null)); fail(); }
LampServiceImpl implements LampService { @Override public LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp) throws LampDoesNotExistsException { Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setLastShownScenario(lamp.getLastShownScenario()); l = lampRepository.save(l); return mapper.map(l, LampDTO.class); } else { throw new LampDoesNotExistsException(lamp.getId()); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test(expected = LampDoesNotExistsException.class) public void testUpdateLastShownScenarioWithoutValidLampId() { lampService.updateLastShownScenario(new LampUpdateLastShownScenarioDTO(-1, Scenario.BUILDING)); fail(); }
LampServiceImpl implements LampService { @Override public LampDTO rename(LampRenameDTO lamp) throws EmptyInputException, LampDoesNotExistsException { if (lamp.getName() == null || lamp.getName().trim().isEmpty()) { throw new EmptyInputException(); } Lamp l = lampRepository.findOne(lamp.getId()); if (l != null) { l.setName(lamp.getName()); l = lampRepository.save(l); return mapper.map(l, LampDTO.class); } else { throw new LampDoesNotExistsException(lamp.getId()); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test(expected = EmptyInputException.class) public void testRenameWithEmptyInput() { try { lampService.rename(new LampRenameDTO(-1, null)); } catch (EmptyInputException eie) { lampService.rename(new LampRenameDTO(-1, "")); } fail(); } @Test(expected = LampDoesNotExistsException.class) public void testRenameWithInvalidLampId() { lampService.rename(new LampRenameDTO(-1, "Lamp 1")); fail(); }
LampServiceImpl implements LampService { @Override public List<LampDTO> findAll() { List<Lamp> lamps = lampRepository.findAll(); List<LampDTO> dtos = new ArrayList<>(lamps.size()); for (Lamp lamp : lamps) { LampDTO dto = mapper.map(lamp, LampDTO.class); dtos.add(dto); } return dtos; } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test public void testFindAll() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); assertEquals(0, lampService.count(team.getId())); LampCreateDTO lampCreateDTO1 = new LampCreateDTO("hueId 1", "Name 1", team.getId()); LampDTO lampDTO1 = lampService.create(lampCreateDTO1); assertEquals(1, lampService.count(team.getId())); assertEquals(lampCreateDTO1.getHueUniqueId(), lampService.findAll().get(0).getHueUniqueId()); LampCreateDTO lampCreateDTO2 = new LampCreateDTO("hueId 2", "Name 2", team.getId()); LampDTO lampDTO2 = lampService.create(lampCreateDTO2); assertEquals(2, lampService.count(team.getId())); List<LampDTO> lampDTOs = lampService.findAll(); String hueUniqueId2 = lampDTOs.get(1).getHueUniqueId(); if(!hueUniqueId2.equals(lampDTO1.getHueUniqueId()) && !hueUniqueId2.equals(lampDTO2.getHueUniqueId())) { fail(); } }
LampServiceImpl implements LampService { @Override public TeamLampsDTO findAllOfATeam(long teamId) throws TeamDoesNotExistException { Team team = teamRepository.findOne(teamId); if (team != null) { TeamLampsDTO dto = mapper.map(team, TeamLampsDTO.class); for (int i = 0; i < nullSafe(team.getLamps()).size(); i++) { TeamLampsDTO.TeamLampsDTO_LampDTO lampDTO = dto.getLamps().get(i); setGroupedScenarioConfigs(lampDTO, team.getLamps().get(i).getScenarioConfigs()); } return dto; } else { throw new TeamDoesNotExistException(teamId); } } @Autowired LampServiceImpl(LampRepository lampRepository, TeamRepository teamRepository, HueService hueService, HolidayService holidayService, Mapper mapper); @Override LampDTO create(LampCreateDTO lamp); @Override LampDTO update(LampUpdateDTO lamp); @Override LampDTO updateLastShownScenario(LampUpdateLastShownScenarioDTO lamp); @Override LampDTO rename(LampRenameDTO lamp); @Override void remove(long id); @Override List<LampDTO> findAll(); @Override LampGroupedScenariosDTO findOne(long id); @Override long count(); @Override long count(long teamId); @Override List<LampHueDTO> findAllAvailable(); @Override TeamLampsDTO findAllOfATeam(long teamId); @Override List<LampNameDTO> findAllLampNamesOfATeam(long teamId); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); }
@Test(expected = TeamDoesNotExistException.class) public void testFindAllOfATeamWithoutValidTeamId() { lampService.findAllOfATeam(-1); fail(); }
UserServiceImpl implements UserService { @Override public UserDTO create(UserCreateDTO user) throws EmptyInputException, TeamDoesNotExistException, UserAlreadyExistsException, InvalidLoginException { if (user.getLogin() == null || user.getLogin().trim().isEmpty()) { throw new EmptyInputException(); } user.setLogin(user.getLogin().trim().toLowerCase()); Team team = teamRepository.findOne(user.getTeamId()); if (team == null) { throw new TeamDoesNotExistException(user.getTeamId()); } if (userRepository.findByLogin(user.getLogin()) != null) { throw new UserAlreadyExistsException(user.getLogin()); } User u; if (ldapManager != null) { u = ldapManager.getUserForLoginName(user.getLogin()); if (u == null) { throw new InvalidLoginException(user.getLogin()); } } else { u = new User(); u.setLogin(user.getLogin()); } u.setTeam(team); u = userRepository.save(u); return mapper.map(u, UserDTO.class); } @Autowired UserServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<UserDTO> findAll(); @Override List<UserDTO> findAll(int page, int size); @Override long count(); @Override List<UserDTO> findBySearchItem(String searchItem); @Override List<UserDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override long count(long teamId); @Override UserDTO create(UserCreateDTO user); @Override UserDTO update(UserUpdateDTO user); @Override void remove(long id); @Override UserDTO findByLogin(String login); }
@Test public void testCreate() { assertEquals(0, userService.count()); TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); userService.create(new UserCreateDTO("wennier", team.getId())); assertEquals(1, userService.count()); UserDTO user = userService.findByLogin("wennier"); assertNotNull(user); } @Test(expected = EmptyInputException.class) public void testCreateWithEmptyInput() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); try { userService.create(new UserCreateDTO(null, team.getId())); } catch (EmptyInputException eie) { userService.create(new UserCreateDTO("", team.getId())); } fail(); } @Test(expected = TeamDoesNotExistException.class) public void testCreateWithoutExistingTeam() { userService.create(new UserCreateDTO("wennier", -1)); fail(); }
UserServiceImpl implements UserService { @Override public UserDTO update(UserUpdateDTO user) throws UserDoesNotExistException { User userInDB = userRepository.findOne(user.getId()); if (userInDB == null) { throw new UserDoesNotExistException(user.getId()); } userInDB.setRoles(user.getRoles()); userInDB = userRepository.save(userInDB); return mapper.map(userInDB, UserDTO.class); } @Autowired UserServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<UserDTO> findAll(); @Override List<UserDTO> findAll(int page, int size); @Override long count(); @Override List<UserDTO> findBySearchItem(String searchItem); @Override List<UserDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override long count(long teamId); @Override UserDTO create(UserCreateDTO user); @Override UserDTO update(UserUpdateDTO user); @Override void remove(long id); @Override UserDTO findByLogin(String login); }
@Test(expected = UserDoesNotExistException.class) public void testUpdateUserWithoutValidId() { userService.update(new UserUpdateDTO(-1, null)); fail(); }
JobServiceImpl implements JobService { @Override public long countNameDistinctly(long teamId) { return jobRepository.countNameDistinctly(teamId); } @Autowired JobServiceImpl(JobRepository jobRepository); @Override long countNameDistinctly(long teamId); @Override long countNameDistinctly(); }
@Test public void testCountNameDistinctly() { assertEquals(0, jobService.countNameDistinctly()); jobRepository.save(new Job(0, "A")); jobRepository.save(new Job(0, "A")); jobRepository.save(new Job(0, "B")); jobRepository.save(new Job(0, "B")); jobRepository.save(new Job(0, "C")); assertEquals(3, jobService.countNameDistinctly()); } @Test public void testCountNameDistinctlyWithTeamId() { assertEquals(0, jobService.countNameDistinctly()); TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); LampDTO lampDTO = lampService.create(new LampCreateDTO("hueId", "Lampe 1", team.getId())); assertEquals(0, jobService.countNameDistinctly(team.getId())); LampUpdateDTO lampUpdateDTO = new LampUpdateDTO(); lampUpdateDTO.setId(lampDTO.getId()); lampUpdateDTO.setBuildingConfigs(new ArrayList<>()); lampUpdateDTO.setFailureConfigs(new ArrayList<>()); lampUpdateDTO.setUnstableConfigs(new ArrayList<>()); lampUpdateDTO.setSuccessConfigs(new ArrayList<>()); List<ScenarioConfigDTO> scenarioConfigs2 = lampDTO.getScenarioConfigs(); for(ScenarioConfigDTO config : scenarioConfigs2) { String scenario = config.getScenario().toString(); if(scenario.startsWith(BuildState.BUILDING.toString())) { lampUpdateDTO.getBuildingConfigs().add(config); } else if(scenario.startsWith(BuildState.FAILURE.toString())) { lampUpdateDTO.getFailureConfigs().add(config); } else if(scenario.startsWith(BuildState.UNSTABLE.toString())) { lampUpdateDTO.getUnstableConfigs().add(config); } else if(scenario.startsWith(BuildState.SUCCESS.toString())) { lampUpdateDTO.getSuccessConfigs().add(config); } } List<String> jobNames = Arrays.asList("JobA", "JobB", "JobB", "JobB"); List<JobDTO> jobs = new ArrayList<>(); for(String name : jobNames) { jobs.add(new JobDTO(0, name)); } lampUpdateDTO.setJobs(jobs); lampUpdateDTO.setWorkingStart(lampDTO.getWorkingStart()); lampUpdateDTO.setWorkingEnd(lampDTO.getWorkingEnd()); lampService.update(lampUpdateDTO); assertEquals(2, jobService.countNameDistinctly(team.getId())); assertEquals(0, jobService.countNameDistinctly(654846215)); }
TeamServiceImpl implements TeamService { @Override public TeamLampsDTO create(TeamCreateDTO team) throws EmptyInputException, TeamAlreadyExistsException { if (team.getName() == null || team.getName().trim().isEmpty()) { throw new EmptyInputException(); } team.setName(team.getName().trim()); if(teamRepository.findByName(team.getName()) != null) { throw new TeamAlreadyExistsException(team.getName()); } Team t = new Team(); t.setName(team.getName()); t.setScenarioPriority(new ScenarioUtil().generateDefaultScenarioPriority()); t = teamRepository.save(t); t.getScenarioPriority().size(); TeamLampsDTO dto = new TeamLampsDTO(); dto.setId(t.getId()); dto.setName(t.getName()); dto.setScenarioPriority(t.getScenarioPriority()); return dto; } @Autowired TeamServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<TeamUsersDTO> findAll(); @Override List<TeamUsersDTO> findAll(int page, int size); @Override long count(); @Override List<TeamUsersDTO> findBySearchItem(String searchItem); @Override List<TeamUsersDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override TeamLampsDTO create(TeamCreateDTO team); @Override TeamUsersDTO update(TeamUpdateDTO team); @Override TeamUsersDTO rename(TeamRenameDTO team); @Override TeamUsersDTO findOne(long id); @Override void remove(long id); }
@Test public void testCreate() { assertEquals(0, teamService.count()); TeamCreateDTO teamCreateDTO1 = new TeamCreateDTO("Team 1"); TeamLampsDTO teamDTO1 = teamService.create(teamCreateDTO1); assertEquals(1, teamService.count()); assertEquals("Team 1", teamRepository.findOne(teamDTO1.getId()).getName()); TeamCreateDTO teamCreateDTO2 = new TeamCreateDTO("Team 2"); TeamLampsDTO teamDTO2 = teamService.create(teamCreateDTO2); assertEquals(2, teamService.count()); assertEquals("Team 2", teamRepository.findOne(teamDTO2.getId()).getName()); } @Test(expected = EmptyInputException.class) public void testCreateTeamWithoutName() { try { teamService.create(new TeamCreateDTO(null)); } catch (EmptyInputException eie) { teamService.create(new TeamCreateDTO("")); } fail(); }
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO update(TeamUpdateDTO team) throws TeamDoesNotExistException { Team teamInDB = teamRepository.findOne(team.getId()); if(teamInDB == null) { throw new TeamDoesNotExistException(team.getId()); } else { if(team.getScenarioPriority() != null && team.getScenarioPriority().size() == Scenario.getPriorityListLength()) { teamInDB.setScenarioPriority(team.getScenarioPriority()); teamInDB = teamRepository.save(teamInDB); return mapper.map(teamInDB, TeamUsersDTO.class); } else { throw new IllegalArgumentException("Die priorisierte Liste enthält nicht alle Szenarios!"); } } } @Autowired TeamServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<TeamUsersDTO> findAll(); @Override List<TeamUsersDTO> findAll(int page, int size); @Override long count(); @Override List<TeamUsersDTO> findBySearchItem(String searchItem); @Override List<TeamUsersDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override TeamLampsDTO create(TeamCreateDTO team); @Override TeamUsersDTO update(TeamUpdateDTO team); @Override TeamUsersDTO rename(TeamRenameDTO team); @Override TeamUsersDTO findOne(long id); @Override void remove(long id); }
@Test(expected = TeamDoesNotExistException.class) public void testUpdateTeamWithoutValidId() { teamService.update(new TeamUpdateDTO(-1, null)); fail(); }
TeamServiceImpl implements TeamService { @Override public TeamUsersDTO rename(TeamRenameDTO team) throws TeamDoesNotExistException, TeamAlreadyExistsException, EmptyInputException { Team t = teamRepository.findOne(team.getId()); if(t != null) { if(team.getName() == null || team.getName().trim().isEmpty()) { throw new EmptyInputException(); } else if(t.getName().equals(team.getName())) { return mapper.map(t, TeamUsersDTO.class); } Team teamWithSameName = teamRepository.findByName(team.getName()); if(teamWithSameName == null) { t.setName(team.getName()); teamRepository.save(t); return mapper.map(t, TeamUsersDTO.class); } else { throw new TeamAlreadyExistsException(team.getName()); } } else { throw new TeamDoesNotExistException(team.getId()); } } @Autowired TeamServiceImpl(TeamRepository teamRepository, UserRepository userRepository, BridgeRepository bridgeRepository, Mapper mapper); @Override List<TeamUsersDTO> findAll(); @Override List<TeamUsersDTO> findAll(int page, int size); @Override long count(); @Override List<TeamUsersDTO> findBySearchItem(String searchItem); @Override List<TeamUsersDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override TeamLampsDTO create(TeamCreateDTO team); @Override TeamUsersDTO update(TeamUpdateDTO team); @Override TeamUsersDTO rename(TeamRenameDTO team); @Override TeamUsersDTO findOne(long id); @Override void remove(long id); }
@Test(expected = TeamDoesNotExistException.class) public void testRenameTeamWithoutValidId() { teamService.rename(new TeamRenameDTO(-1, "Team 2")); fail(); }
HueServiceImpl implements HueService { @Override public boolean ipAreEqual(String ip1, String ip2) { return removePortAndToLowerCase(ip1).equals(removePortAndToLowerCase(ip2)); } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @Override void connectToBridgeIfNotAlreadyConnected(BridgeDTO bridge); @Override void disconnectFromBridge(BridgeDTO bridge); @Override void showRandomColorsOnAllLamps(); @Async @Override void updateLamp(LampWithHueUniqueId lamp, ScenarioConfigDTO config); @Override List<LampHueDTO> findAllLamps(); @Override List<FoundBridgeDTO> findAllBridges(); @Override void testScenario(LampTestDTO lamp); @Override void pulseOnce(String hueUniqueId); @Override void turnOff(LampTurnOffDTO lamp); @Override void updateBridgeState(List<BridgeDTO> bridgeDTOs); @Override boolean ipAreEqual(String ip1, String ip2); String removePortAndToLowerCase(String ip); }
@Test public void testIpAreEqual() { String ip1 = "10.10.10.10"; String ip2 = "10.10.10.10:80"; String ip3 = "10.10.10.20:80"; String ip4 = "10.10.10.20:45"; assertTrue(hueService.ipAreEqual(ip1, ip2)); assertFalse(hueService.ipAreEqual(ip2, ip3)); assertTrue(hueService.ipAreEqual(ip3, ip4)); }
BridgeServiceImpl implements BridgeService { boolean isIPv4Address(String ip) { if (ip == null) { return false; } else { String regex255 = "(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))"; String regexIPv4 = regex255 + "\\." + regex255 + "\\." + regex255 + "\\." + regex255; return ip.matches(regexIPv4); } } @Autowired BridgeServiceImpl(UserRepository userRepository, BridgeRepository bridgeRepository, HueService hueService, Mapper mapper); @Override List<BridgeDTO> findAll(); @Override List<BridgeDTO> findAll(int page, int size); @Override List<FoundBridgeDTO> findAvailable(); @Override long count(); @Override List<BridgeDTO> findBySearchItem(String searchItem); @Override List<BridgeDTO> findBySearchItem(String searchItem, int page, int size); @Override long count(String searchItem); @Override BridgeDTO create(BridgeCreateDTO bridge); @Override BridgeDTO findByIp(String ip); @Override void remove(long id); }
@Test public void testIsIPv4Address() { assertTrue(bridgeService.isIPv4Address("0.0.0.0")); assertTrue(bridgeService.isIPv4Address("48.51.37.15")); assertTrue(bridgeService.isIPv4Address("199.125.25.15")); assertTrue(bridgeService.isIPv4Address("245.255.2.245")); assertTrue(bridgeService.isIPv4Address("255.255.255.255")); assertFalse(bridgeService.isIPv4Address("")); assertFalse(bridgeService.isIPv4Address("fiidfj")); assertFalse(bridgeService.isIPv4Address("124")); assertFalse(bridgeService.isIPv4Address("10")); assertFalse(bridgeService.isIPv4Address("45.5")); assertFalse(bridgeService.isIPv4Address("45.87.125")); assertFalse(bridgeService.isIPv4Address("256.48.56.1")); assertFalse(bridgeService.isIPv4Address("00.00.45.6")); assertFalse(bridgeService.isIPv4Address("01.78.56.56")); assertFalse(bridgeService.isIPv4Address("001.2.5.2")); }