src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
StandbyTask extends AbstractTask { Map<TopicPartition, Long> checkpointedOffsets() { return checkpointedOffsets; } StandbyTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, final...
@Test public void testStorePartitions() throws Exception { StreamsConfig config = createConfig(baseDir); StandbyTask task = new StandbyTask(taskId, applicationId, topicPartitions, topology, consumer, changelogReader, config, null, stateDirectory); assertEquals(Utils.mkSet(partition2), new HashSet<>(task.checkpointedOff...
StandbyTask extends AbstractTask { public List<ConsumerRecord<byte[], byte[]>> update(final TopicPartition partition, final List<ConsumerRecord<byte[], byte[]>> records) { log.debug("{} Updating standby replicas of its state store for partition [{}]", logPrefix, partition); return stateMgr.updateStandbyStates(partition...
@SuppressWarnings("unchecked") @Test public void testUpdate() throws Exception { StreamsConfig config = createConfig(baseDir); StandbyTask task = new StandbyTask(taskId, applicationId, topicPartitions, topology, consumer, changelogReader, config, null, stateDirectory); restoreStateConsumer.assign(new ArrayList<>(task.c...
StateDirectory { File directoryForTask(final TaskId taskId) { final File taskDir = new File(stateDir, taskId.toString()); if (!taskDir.exists() && !taskDir.mkdir()) { throw new ProcessorStateException(String.format("task directory [%s] doesn't exist and couldn't be created", taskDir.getPath())); } return taskDir; } Sta...
@Test public void shouldCreateTaskStateDirectory() throws Exception { final TaskId taskId = new TaskId(0, 0); final File taskDirectory = directory.directoryForTask(taskId); assertTrue(taskDirectory.exists()); assertTrue(taskDirectory.isDirectory()); } @Test(expected = ProcessorStateException.class) public void shouldTh...
StateDirectory { boolean lock(final TaskId taskId, int retry) throws IOException { final File lockFile; if (locks.containsKey(taskId)) { log.trace("{} Found cached state dir lock for task {}", logPrefix, taskId); return true; } try { lockFile = new File(directoryForTask(taskId), LOCK_FILE_NAME); } catch (ProcessorState...
@Test public void shouldNotLockDeletedDirectory() throws Exception { final TaskId taskId = new TaskId(0, 0); Utils.delete(stateDir); assertFalse(directory.lock(taskId, 0)); }
StateDirectory { public void cleanRemovedTasks(final long cleanupDelayMs) { final File[] taskDirs = listTaskDirectories(); if (taskDirs == null || taskDirs.length == 0) { return; } for (File taskDir : taskDirs) { final String dirName = taskDir.getName(); TaskId id = TaskId.parse(dirName); if (!locks.containsKey(id)) { ...
@Test public void shouldNotRemoveNonTaskDirectoriesAndFiles() throws Exception { final File otherDir = TestUtils.tempDirectory(stateDir.toPath(), "foo"); directory.cleanRemovedTasks(0); assertTrue(otherDir.exists()); }
StreamThread extends Thread { String threadClientId() { return threadClientId; } StreamThread(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier, final String applicationId, f...
@Test public void testMetrics() throws Exception { final StreamThread thread = new StreamThread( builder, config, clientSupplier, applicationId, clientId, processId, metrics, mockTime, new StreamsMetadataState(builder, StreamsMetadataState.UNKNOWN_HOST), 0); final String defaultGroupName = "stream-metrics"; final Strin...
StreamThread extends Thread { protected void maybeClean(final long now) { if (now > lastCleanMs + cleanTimeMs) { stateDirectory.cleanRemovedTasks(cleanTimeMs); lastCleanMs = now; } } StreamThread(final TopologyBuilder builder, final StreamsConfig config, final KafkaClient...
@Test public void testMaybeClean() throws Exception { final File baseDir = Files.createTempDirectory("test").toFile(); try { final long cleanupDelay = 1000L; final Properties props = configProps(false); props.setProperty(StreamsConfig.STATE_CLEANUP_DELAY_MS_CONFIG, Long.toString(cleanupDelay)); props.setProperty(Stream...
StreamThread extends Thread { protected void maybeCommit(final long now) { if (commitTimeMs >= 0 && lastCommitMs + commitTimeMs < now) { log.debug("{} Committing all active tasks {} and standby tasks {} because the commit interval {}ms has elapsed by {}ms", logPrefix, activeTasks.keySet(), standbyTasks.keySet(), commit...
@Test public void testMaybeCommit() throws Exception { final File baseDir = Files.createTempDirectory("test").toFile(); try { final long commitInterval = 1000L; final Properties props = configProps(false); props.setProperty(StreamsConfig.STATE_DIR_CONFIG, baseDir.getCanonicalPath()); props.setProperty(StreamsConfig.COM...
StreamThread extends Thread { void setPartitionAssignor(final StreamPartitionAssignor partitionAssignor) { this.partitionAssignor = partitionAssignor; } StreamThread(final TopologyBuilder builder, final StreamsConfig config, final KafkaClientSupplier clientSupplier, ...
@Test public void shouldNotNullPointerWhenStandbyTasksAssignedAndNoStateStoresForTopology() throws Exception { builder.addSource("name", "topic").addSink("out", "output"); final StreamThread thread = new StreamThread( builder, config, clientSupplier, applicationId, clientId, processId, metrics, mockTime, new StreamsMet...
StreamsMetricsImpl implements StreamsMetrics { @Override public void removeSensor(Sensor sensor) { Sensor parent = null; Objects.requireNonNull(sensor, "Sensor is null"); metrics.removeSensor(sensor.name()); parent = parentSensors.get(sensor); if (parent != null) { metrics.removeSensor(parent.name()); } } StreamsMetric...
@Test(expected = NullPointerException.class) public void testRemoveNullSensor() { String groupName = "doesNotMatter"; Map<String, String> tags = new HashMap<>(); StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(new Metrics(), groupName, tags); streamsMetrics.removeSensor(null); } @Test public void testRemoveS...
GlobalStateManagerImpl implements GlobalStateManager { @Override public Set<String> initialize(final InternalProcessorContext processorContext) { try { if (!stateDirectory.lockGlobalState(MAX_LOCK_ATTEMPTS)) { throw new LockException(String.format("Failed to lock the global state directory: %s", baseDir)); } } catch (I...
@Test public void shouldLockGlobalStateDirectory() throws Exception { stateManager.initialize(context); assertTrue(new File(stateDirectory.globalStateDir(), ".lock").exists()); } @Test(expected = LockException.class) public void shouldThrowLockExceptionIfCantGetLock() throws Exception { final StateDirectory stateDir = ...
StreamTask extends AbstractTask implements Punctuator { boolean maybePunctuate() { final long timestamp = partitionGroup.timestamp(); if (timestamp == TimestampTracker.NOT_KNOWN) { return false; } else { return punctuationQueue.mayPunctuate(timestamp, this); } } StreamTask(final TaskId id, final S...
@SuppressWarnings("unchecked") @Test public void testMaybePunctuate() throws Exception { task.addRecords(partition1, records( new ConsumerRecord<>(partition1.topic(), partition1.partition(), 20, 0L, TimestampType.CREATE_TIME, 0L, 0, 0, recordKey, recordValue), new ConsumerRecord<>(partition1.topic(), partition1.partiti...
StreamTask extends AbstractTask implements Punctuator { @Override protected void flushState() { log.trace("{} Flushing state and producer", logPrefix); super.flushState(); recordCollector.flush(); } StreamTask(final TaskId id, final String applicationId, final Collection<Topi...
@Test public void shouldFlushRecordCollectorOnFlushState() throws Exception { final AtomicBoolean flushed = new AtomicBoolean(false); final StreamsMetrics streamsMetrics = new MockStreamsMetrics(new Metrics()); final StreamTask streamTask = new StreamTask(taskId00, "appId", partitions, topology, consumer, changelogRead...
StreamTask extends AbstractTask implements Punctuator { @Override public void commit() { commitImpl(true); } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, ...
@SuppressWarnings("unchecked") @Test public void shouldCheckpointOffsetsOnCommit() throws Exception { final String storeName = "test"; final String changelogTopic = ProcessorStateManager.storeChangelogTopic("appId", storeName); final InMemoryKeyValueStore inMemoryStore = new InMemoryKeyValueStore(storeName, null, null)...
ConnectorsResource { @GET @Path("/") public Collection<String> listConnectors(final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Collection<String>> cb = new FutureCallback<>(); herder.connectors(cb); return completeOrForwardRequest(cb, "/connectors", "GET", null, new TypeReference<Collecti...
@Test public void testListConnectors() throws Throwable { final Capture<Callback<Collection<String>>> cb = Capture.newInstance(); herder.connectors(EasyMock.capture(cb)); expectAndCallbackResult(cb, Arrays.asList(CONNECTOR2_NAME, CONNECTOR_NAME)); PowerMock.replayAll(); Collection<String> connectors = connectorsResourc...
StreamTask extends AbstractTask implements Punctuator { @Override public void punctuate(final ProcessorNode node, final long timestamp) { if (processorContext.currentNode() != null) { throw new IllegalStateException(String.format("%s Current node is not null", logPrefix)); } updateProcessorContext(new StampedRecord(DUM...
@Test public void shouldCallPunctuateOnPassedInProcessorNode() throws Exception { task.punctuate(processor, 5); assertThat(processor.punctuatedAt, equalTo(5L)); task.punctuate(processor, 10); assertThat(processor.punctuatedAt, equalTo(10L)); }
StreamTask extends AbstractTask implements Punctuator { public void schedule(final long interval) { if (processorContext.currentNode() == null) { throw new IllegalStateException(String.format("%s Current node is null", logPrefix)); } punctuationQueue.schedule(new PunctuationSchedule(processorContext.currentNode(), inte...
@Test(expected = IllegalStateException.class) public void shouldThrowIllegalStateExceptionOnScheduleIfCurrentNodeIsNull() throws Exception { task.schedule(1); }
StreamTask extends AbstractTask implements Punctuator { @Override public void close(boolean clean) { log.debug("{} Closing", logPrefix); RuntimeException firstException = null; try { suspend(clean); } catch (final RuntimeException e) { clean = false; firstException = e; log.error("{} Could not close task: ", logPrefix,...
@SuppressWarnings("unchecked") @Test public void shouldThrowExceptionIfAnyExceptionsRaisedDuringCloseButStillCloseAllProcessorNodesTopology() throws Exception { task.close(true); task = createTaskThatThrowsExceptionOnClose(); try { task.close(true); fail("should have thrown runtime exception"); } catch (final RuntimeEx...
StreamTask extends AbstractTask implements Punctuator { @Override public void suspend() { suspend(true); } StreamTask(final TaskId id, final String applicationId, final Collection<TopicPartition> partitions, final ProcessorTopology topology, ...
@Test public void shouldCommitTransactionOnSuspendEvenIfTransactionIsEmptyIfEosEnabled() throws Exception { final MockProducer producer = new MockProducer(); task = new StreamTask(taskId00, applicationId, partitions, topology, consumer, changelogReader, eosConfig, streamsMetrics, stateDirectory, null, time, producer); ...
StreamsMetadataState { public synchronized Collection<StreamsMetadata> getAllMetadataForStore(final String storeName) { Objects.requireNonNull(storeName, "storeName cannot be null"); if (!isInitialized()) { return Collections.emptyList(); } if (globalStores.contains(storeName)) { return allMetadata; } final List<String...
@Test public void shouldNotThrowNPEWhenOnChangeNotCalled() throws Exception { new StreamsMetadataState(builder, hostOne).getAllMetadataForStore("store"); } @Test public void shouldGetInstancesForStoreName() throws Exception { final StreamsMetadata one = new StreamsMetadata(hostOne, Utils.mkSet(globalTable, "table-one",...
StreamsMetadataState { public synchronized Collection<StreamsMetadata> getAllMetadata() { return allMetadata; } StreamsMetadataState(final TopologyBuilder builder, final HostInfo thisHost); synchronized Collection<StreamsMetadata> getAllMetadata(); synchronized Collection<StreamsMetadata> getAllMetadataForStore(final S...
@Test public void shouldGetAllStreamInstances() throws Exception { final StreamsMetadata one = new StreamsMetadata(hostOne, Utils.mkSet(globalTable, "table-one", "table-two", "merged-table"), Utils.mkSet(topic1P0, topic2P1, topic4P0)); final StreamsMetadata two = new StreamsMetadata(hostTwo, Utils.mkSet(globalTable, "t...
StreamsMetadataState { public synchronized <K> StreamsMetadata getMetadataWithKey(final String storeName, final K key, final Serializer<K> keySerializer) { Objects.requireNonNull(keySerializer, "keySerializer can't be null"); Objects.requireNonNull(storeName, "storeName can't be null"); Objects.requireNonNull(key, "key...
@Test public void shouldReturnNullOnGetWithKeyWhenStoreDoesntExist() throws Exception { final StreamsMetadata actual = discovery.getMetadataWithKey("not-a-store", "key", Serdes.String().serializer()); assertNull(actual); } @Test(expected = NullPointerException.class) public void shouldThrowWhenKeyIsNull() throws Except...
SinkNode extends ProcessorNode<K, V> { @Override public void process(final K key, final V value) { final RecordCollector collector = ((RecordCollector.Supplier) context).recordCollector(); final long timestamp = context.timestamp(); if (timestamp < 0) { throw new StreamsException("Invalid (negative) timestamp of " + ti...
@Test @SuppressWarnings("unchecked") public void shouldThrowStreamsExceptionOnInputRecordWithInvalidTimestamp() { final Bytes anyKey = new Bytes("any key".getBytes()); final Bytes anyValue = new Bytes("any value".getBytes()); context.setTime(-1); try { sink.process(anyKey, anyValue); fail("Should have thrown StreamsExc...
ProcessorTopology { public List<StateStore> globalStateStores() { return globalStateStores; } ProcessorTopology(final List<ProcessorNode> processorNodes, final Map<String, SourceNode> sourceByTopics, final Map<String, SinkNode> sinkByTopics, ...
@SuppressWarnings("unchecked") @Test public void shouldDriveGlobalStore() throws Exception { final StateStoreSupplier storeSupplier = Stores.create("my-store") .withStringKeys().withStringValues().inMemory().disableLogging().build(); final String global = "global"; final String topic = "topic"; final TopologyBuilder to...
ProcessorTopology { @Override public String toString() { return toString(""); } ProcessorTopology(final List<ProcessorNode> processorNodes, final Map<String, SourceNode> sourceByTopics, final Map<String, SinkNode> sinkByTopics, final...
@Test public void shouldCreateStringWithSourceAndTopics() throws Exception { builder.addSource("source", "topic1", "topic2"); final ProcessorTopology topology = builder.build(null); final String result = topology.toString(); assertThat(result, containsString("source:\n\t\ttopics:\t\t[topic1, topic2]\n")); } @Test publi...
ConnectorsResource { @POST @Path("/") public Response createConnector(final @QueryParam("forward") Boolean forward, final CreateConnectorRequest createRequest) throws Throwable { String name = createRequest.name(); if (name.contains("/")) { throw new BadRequestException("connector name should not contain '/'"); } Map<S...
@Test public void testCreateConnector() throws Throwable { CreateConnectorRequest body = new CreateConnectorRequest(CONNECTOR_NAME, Collections.singletonMap(ConnectorConfig.NAME_CONFIG, CONNECTOR_NAME)); final Capture<Callback<Herder.Created<ConnectorInfo>>> cb = Capture.newInstance(); herder.putConnectorConfig(EasyMoc...
InternalTopicConfig { public Properties toProperties(final long additionalRetentionMs) { final Properties result = new Properties(); for (Map.Entry<String, String> configEntry : logConfig.entrySet()) { result.put(configEntry.getKey(), configEntry.getValue()); } if (retentionMs != null && isCompactDelete()) { result.put...
@Test public void shouldHaveCompactionPropSetIfSupplied() throws Exception { final Properties properties = new InternalTopicConfig("name", Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), Collections.<String, String>emptyMap()).toProperties(0); assertEquals("compact", properties.getProperty(InternalTop...
InternalTopicConfig { boolean isCompacted() { return cleanupPolicies.contains(CleanupPolicy.compact); } InternalTopicConfig(final String name, final Set<CleanupPolicy> defaultCleanupPolicies, final Map<String, String> logConfig); Properties toProperties(final long additionalRetentionMs); String name(); void setRetentio...
@Test public void shouldBeCompactedIfCleanupPolicyCompactOrCompactAndDelete() throws Exception { assertTrue(new InternalTopicConfig("name", Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), Collections.<String, String>emptyMap()).isCompacted()); assertTrue(new InternalTopicConfig("name", Utils.mkSet(Int...
StreamPartitionAssignor implements PartitionAssignor, Configurable { @Override public Subscription subscription(Set<String> topics) { final Set<TaskId> previousActiveTasks = streamThread.prevActiveTasks(); Set<TaskId> standbyTasks = streamThread.cachedTasks(); standbyTasks.removeAll(previousActiveTasks); SubscriptionIn...
@SuppressWarnings("unchecked") @Test public void testSubscription() throws Exception { builder.addSource("source1", "topic1"); builder.addSource("source2", "topic2"); builder.addProcessor("processor", new MockProcessorSupplier(), "source1", "source2"); final Set<TaskId> prevTasks = Utils.mkSet( new TaskId(0, 1), new Ta...
StreamPartitionAssignor implements PartitionAssignor, Configurable { @Override public void onAssignment(Assignment assignment) { List<TopicPartition> partitions = new ArrayList<>(assignment.partitions()); Collections.sort(partitions, PARTITION_COMPARATOR); AssignmentInfo info = AssignmentInfo.decode(assignment.userData...
@Test public void testOnAssignment() throws Exception { TopicPartition t2p3 = new TopicPartition("topic2", 3); TopologyBuilder builder = new TopologyBuilder(); builder.addSource("source1", "topic1"); builder.addSource("source2", "topic2"); builder.addProcessor("processor", new MockProcessorSupplier(), "source1", "sourc...
StreamPartitionAssignor implements PartitionAssignor, Configurable { @Override public void configure(Map<String, ?> configs) { numStandbyReplicas = (Integer) configs.get(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG); Object o = configs.get(StreamsConfig.InternalConfig.STREAM_THREAD_INSTANCE); if (o == null) { KafkaExcepti...
@Test public void shouldThrowExceptionIfApplicationServerConfigPortIsNotAnInteger() throws Exception { final Properties properties = configProps(); final String myEndPoint = "localhost:j87yhk"; properties.put(StreamsConfig.APPLICATION_SERVER_CONFIG, myEndPoint); final StreamsConfig config = new StreamsConfig(properties...
StreamPartitionAssignor implements PartitionAssignor, Configurable { Cluster clusterMetadata() { if (metadataWithInternalTopics == null) { return Cluster.empty(); } return metadataWithInternalTopics; } @Override void configure(Map<String, ?> configs); @Override String name(); @Override Subscription subscription(Set<St...
@Test public void shouldReturnEmptyClusterMetadataIfItHasntBeenBuilt() throws Exception { final Cluster cluster = partitionAssignor.clusterMetadata(); assertNotNull(cluster); }
ConnectorsResource { @DELETE @Path("/{connector}") public void destroyConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<Herder.Created<ConnectorInfo>> cb = new FutureCallback<>(); herder.deleteConnectorConfig(connector, cb); complet...
@Test public void testDeleteConnector() throws Throwable { final Capture<Callback<Herder.Created<ConnectorInfo>>> cb = Capture.newInstance(); herder.deleteConnectorConfig(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackResult(cb, null); PowerMock.replayAll(); connectorsResource.destroyConnector(CON...
RecordQueue { public int addRawRecords(Iterable<ConsumerRecord<byte[], byte[]>> rawRecords) { for (ConsumerRecord<byte[], byte[]> rawRecord : rawRecords) { ConsumerRecord<Object, Object> record = recordDeserializer.deserialize(rawRecord); long timestamp = timestampExtractor.extract(record, timeTracker.get()); log.trace...
@Test(expected = StreamsException.class) public void shouldThrowStreamsExceptionWhenKeyDeserializationFails() throws Exception { final byte[] key = Serdes.Long().serializer().serialize("foo", 1L); final List<ConsumerRecord<byte[], byte[]>> records = Collections.singletonList( new ConsumerRecord<>("topic", 1, 1, 0L, Tim...
ProcessorNode { public void init(ProcessorContext context) { this.context = context; try { nodeMetrics = new NodeMetrics(context.metrics(), name, "task." + context.taskId()); nodeMetrics.metrics.measureLatencyNs(time, initDelegate, nodeMetrics.nodeCreationSensor); } catch (Exception e) { throw new StreamsException(Stri...
@SuppressWarnings("unchecked") @Test (expected = StreamsException.class) public void shouldThrowStreamsExceptionIfExceptionCaughtDuringInit() throws Exception { final ProcessorNode node = new ProcessorNode("name", new ExceptionalProcessor(), Collections.emptySet()); node.init(null); }
ProcessorNode { public void close() { try { nodeMetrics.metrics.measureLatencyNs(time, closeDelegate, nodeMetrics.nodeDestructionSensor); nodeMetrics.removeAllSensors(); } catch (Exception e) { throw new StreamsException(String.format("failed to close processor %s", name), e); } } ProcessorNode(String name); Processor...
@SuppressWarnings("unchecked") @Test (expected = StreamsException.class) public void shouldThrowStreamsExceptionIfExceptionCaughtDuringClose() throws Exception { final ProcessorNode node = new ProcessorNode("name", new ExceptionalProcessor(), Collections.emptySet()); node.close(); }
SourceNode extends ProcessorNode<K, V> { K deserializeKey(String topic, Headers headers, byte[] data) { return keyDeserializer.deserialize(topic, headers, data); } SourceNode(String name, List<String> topics, TimestampExtractor timestampExtractor, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); Sour...
@Test public void shouldProvideTopicHeadersAndDataToKeyDeserializer() { final SourceNode<String, String> sourceNode = new MockSourceNode<>(new String[]{""}, new TheExtendedDeserializer(), new TheExtendedDeserializer()); final RecordHeaders headers = new RecordHeaders(); final String deserializeKey = sourceNode.deserial...
SourceNode extends ProcessorNode<K, V> { V deserializeValue(String topic, Headers headers, byte[] data) { return valDeserializer.deserialize(topic, headers, data); } SourceNode(String name, List<String> topics, TimestampExtractor timestampExtractor, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer); So...
@Test public void shouldProvideTopicHeadersAndDataToValueDeserializer() { final SourceNode<String, String> sourceNode = new MockSourceNode<>(new String[]{""}, new TheExtendedDeserializer(), new TheExtendedDeserializer()); final RecordHeaders headers = new RecordHeaders(); final String deserializedValue = sourceNode.des...
ProcessorStateManager implements StateManager { @Override public StateStore getStore(final String name) { return stores.get(name); } ProcessorStateManager(final TaskId taskId, final Collection<TopicPartition> sources, final boolean isStandby, ...
@Test public void testGetStore() throws IOException { final MockStateStoreSupplier.MockStateStore mockStateStore = new MockStateStoreSupplier.MockStateStore(nonPersistentStoreName, false); final ProcessorStateManager stateMgr = new ProcessorStateManager( new TaskId(0, 1), noPartitions, false, stateDirectory, Collection...
ProcessorStateManager implements StateManager { @Override public void close(final Map<TopicPartition, Long> ackedOffsets) throws ProcessorStateException { RuntimeException firstException = null; try { if (!stores.isEmpty()) { log.debug("{} Closing its state manager and all the registered state stores", logPrefix); for ...
@Test public void shouldThrowLockExceptionIfFailedToLockStateDirectory() throws Exception { final File taskDirectory = stateDirectory.directoryForTask(taskId); final FileChannel channel = FileChannel.open(new File(taskDirectory, StateDirectory.LOCK_FILE_NAME).toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRIT...
ProcessorStateManager implements StateManager { @Override public void register(final StateStore store, final boolean loggingEnabled, final StateRestoreCallback stateRestoreCallback) { log.debug("{} Registering state store {} to its state manager", logPrefix, store.name()); if (store.name().equals(CHECKPOINT_FILE_NAME))...
@Test public void shouldThrowIllegalArgumentExceptionIfStoreNameIsSameAsCheckpointFileName() throws Exception { final ProcessorStateManager stateManager = new ProcessorStateManager( taskId, noPartitions, false, stateDirectory, Collections.<String, String>emptyMap(), changelogReader, false); try { stateManager.register(...
MinTimestampTracker implements TimestampTracker<E> { public long get() { Stamped<E> stamped = ascendingSubsequence.peekFirst(); if (stamped == null) return lastKnownTime; else return stamped.timestamp; } void addElement(final Stamped<E> elem); void removeElement(final Stamped<E> elem); int size(); long get(); }
@Test public void shouldReturnNotKnownTimestampWhenNoRecordsEverAdded() throws Exception { assertThat(tracker.get(), equalTo(TimestampTracker.NOT_KNOWN)); }
MinTimestampTracker implements TimestampTracker<E> { public void removeElement(final Stamped<E> elem) { if (elem == null) { return; } if (ascendingSubsequence.peekFirst() == elem) { ascendingSubsequence.removeFirst(); } if (ascendingSubsequence.isEmpty()) { lastKnownTime = elem.timestamp; } } void addElement(final Sta...
@Test public void shouldIgnoreNullRecordOnRemove() throws Exception { tracker.removeElement(null); }
MinTimestampTracker implements TimestampTracker<E> { public void addElement(final Stamped<E> elem) { if (elem == null) throw new NullPointerException(); Stamped<E> maxElem = ascendingSubsequence.peekLast(); while (maxElem != null && maxElem.timestamp >= elem.timestamp) { ascendingSubsequence.removeLast(); maxElem = asc...
@Test(expected = NullPointerException.class) public void shouldThrowNullPointerExceptionWhenTryingToAddNullElement() throws Exception { tracker.addElement(null); }
SourceNodeRecordDeserializer implements RecordDeserializer { @Override public ConsumerRecord<Object, Object> deserialize(final ConsumerRecord<byte[], byte[]> rawRecord) { final Object key; try { key = sourceNode.deserializeKey(rawRecord.topic(), rawRecord.headers(), rawRecord.key()); } catch (Exception e) { throw new S...
@Test(expected = StreamsException.class) public void shouldThrowStreamsExceptionIfKeyFailsToDeserialize() throws Exception { final SourceNodeRecordDeserializer recordDeserializer = new SourceNodeRecordDeserializer( new TheSourceNode(true, false)); recordDeserializer.deserialize(rawRecord); } @Test(expected = StreamsExc...
AssignmentInfo { public static AssignmentInfo decode(ByteBuffer data) { data.rewind(); DataInputStream in = new DataInputStream(new ByteBufferInputStream(data)); try { int version = in.readInt(); if (version < 0 || version > CURRENT_VERSION) { TaskAssignmentException ex = new TaskAssignmentException("Unknown assignment...
@Test public void shouldDecodePreviousVersion() throws Exception { List<TaskId> activeTasks = Arrays.asList(new TaskId(0, 0), new TaskId(0, 0), new TaskId(0, 1), new TaskId(1, 0)); Map<TaskId, Set<TopicPartition>> standbyTasks = new HashMap<>(); standbyTasks.put(new TaskId(1, 1), Utils.mkSet(new TopicPartition("t1", 1)...
ConnectorsResource { @GET @Path("/{connector}") public ConnectorInfo getConnector(final @PathParam("connector") String connector, final @QueryParam("forward") Boolean forward) throws Throwable { FutureCallback<ConnectorInfo> cb = new FutureCallback<>(); herder.connectorInfo(connector, cb); return completeOrForwardReque...
@Test public void testGetConnector() throws Throwable { final Capture<Callback<ConnectorInfo>> cb = Capture.newInstance(); herder.connectorInfo(EasyMock.eq(CONNECTOR_NAME), EasyMock.capture(cb)); expectAndCallbackResult(cb, new ConnectorInfo(CONNECTOR_NAME, CONNECTOR_CONFIG, CONNECTOR_TASK_NAMES)); PowerMock.replayAll(...
CarManufacturer { public Car manufactureCar(Specification spec) { Car car = carFactory.createCar(spec); entityManager.merge(car); return car; } Car manufactureCar(Specification spec); }
@Test public void test() { Specification spec = new Specification(); Car car = new Car(spec); when(entityManager.merge(any())).then(a -> a.getArgument(0)); when(carFactory.createCar(any())).thenReturn(car); assertThat(testObject.manufactureCar(spec)).isEqualTo(car); verify(carFactory).createCar(spec); verify(entityMana...
Types { public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) { if (lhsType.isAssignableFrom(rhsType)) { return true; } return lhsType.isPrimitive() ? lhsType.equals(Primitives.unwrap(rhsType)) : lhsType.isAssignableFrom(Primitives.wrap(rhsType)); } private Types(); static boolean isAssignable(Class<?...
@Test public void testIsAssignable() throws Exception { assertThat(Types.isAssignable(int.class, Integer.class), is(true)); assertThat(Types.isAssignable(Integer.class, Integer.class), is(true)); assertThat(Types.isAssignable(Integer.class, int.class), is(true)); assertThat(Types.isAssignable(int.class, int.class), is(...
MatchRatingApproachEncoder implements StringEncoder { public boolean isEncodeEquals(String name1, String name2) { if (name1 == null || EMPTY.equalsIgnoreCase(name1) || SPACE.equalsIgnoreCase(name1)) { return false; } else if (name2 == null || EMPTY.equalsIgnoreCase(name2) || SPACE.equalsIgnoreCase(name2)) { return fals...
@Test public final void testCompareNameNullSpace_ReturnsFalseSuccessfully() { assertFalse(getStringEncoder().isEncodeEquals(null, " ")); } @Test public final void testCompareNameSameNames_ReturnsFalseSuccessfully() { assertTrue(getStringEncoder().isEncodeEquals("John", "John")); } @Test public final void testCompare_SM...
Parser implements ParserTreeConstants, ParserConstants { final public ASTRootNode parse() throws ParseException { ASTRootNode jjtn000 = new ASTRootNode(JJTROOTNODE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { DML(); ASTBlock jjtn001 = new ASTBlock(JJTBLOCK); bool...
@Test public void testParse() throws Exception { String sql = "SELECT * from user where id in ( select id from user2 )"; ASTRootNode n = new Parser(sql).parse().init(); InvocationContext context = DefaultInvocationContext.create(); n.render(context); BoundSql boundSql = context.getBoundSql(); assertThat(boundSql.getSql...
Parser implements ParserTreeConstants, ParserConstants { final public void IntegerLiteral() throws ParseException { ASTIntegerLiteral jjtn000 = new ASTIntegerLiteral(JJTINTEGERLITERAL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));Token t; try { t = jj_consume_token(INTEG...
@Test public void testIntegerLiteral() throws Exception { String sql = "select #if (:1 > 9223372036854775800) ok #end"; ASTRootNode n = new Parser(sql).parse().init(); ParameterContext ctx = getParameterContext(Lists.newArrayList((Type) Integer.class)); n.checkAndBind(ctx); InvocationContext context = DefaultInvocation...
Soundex implements StringEncoder { @Override public Object encode(final Object obj) throws EncoderException { if (!(obj instanceof String)) { throw new EncoderException("Parameter supplied to Soundex encode is not of type java.lang.String"); } return soundex((String) obj); } Soundex(); Soundex(final char[] mapping); ...
@Test public void testBadCharacters() { Assert.assertEquals("H452", this.getStringEncoder().encode("HOL>MES")); } @Test public void testEncodeBasic() { Assert.assertEquals("T235", this.getStringEncoder().encode("testing")); Assert.assertEquals("T000", this.getStringEncoder().encode("The")); Assert.assertEquals("Q200", ...
Soundex implements StringEncoder { public int difference(final String s1, final String s2) throws EncoderException { return SoundexUtils.difference(this, s1, s2); } Soundex(); Soundex(final char[] mapping); Soundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final ...
@Test public void testDifference() throws EncoderException { Assert.assertEquals(0, this.getStringEncoder().difference(null, null)); Assert.assertEquals(0, this.getStringEncoder().difference("", "")); Assert.assertEquals(0, this.getStringEncoder().difference(" ", " ")); Assert.assertEquals(4, this.getStringEncoder().di...
Parser implements ParserTreeConstants, ParserConstants { final public void Replace() throws ParseException { ASTReplace jjtn000 = new ASTReplace(JJTREPLACE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));Token t; try { t = jj_consume_token(REPLACE); jjtree.closeNodeScope(j...
@Test public void testReplace() throws Exception { String sql = "replace xxx into replace xxx"; ASTRootNode n = new Parser(sql).parse().init(); List<Type> types = Lists.newArrayList(); ParameterContext ctx = getParameterContext(types); n.checkAndBind(ctx); InvocationContext context = DefaultInvocationContext.create(); ...
Soundex implements StringEncoder { public Soundex() { this.soundexMapping = US_ENGLISH_MAPPING; } Soundex(); Soundex(final char[] mapping); Soundex(final String mapping); int difference(final String s1, final String s2); @Override Object encode(final Object obj); @Override String encode(final String str); @Deprecated...
@Test public void testNewInstance() { Assert.assertEquals("W452", new Soundex().soundex("Williams")); } @Test public void testNewInstance2() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams")); } @Test public void testNewInstance3() { Assert.assertEquals("W452...
Parser implements ParserTreeConstants, ParserConstants { final public void Merge() throws ParseException { ASTMerge jjtn000 = new ASTMerge(JJTMERGE); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));Token t; try { t = jj_consume_token(MERGE); jjtree.closeNodeScope(jjtn000, tr...
@Test public void testMerge() throws Exception { String sql = "merge xxx into merge xxx"; ASTRootNode n = new Parser(sql).parse().init(); List<Type> types = Lists.newArrayList(); ParameterContext ctx = getParameterContext(types); n.checkAndBind(ctx); InvocationContext context = DefaultInvocationContext.create(); n.rend...
TransactionManager { public TransactionManager() { } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransaction(String tableName, final Callable<T> callable); static T callInTransaction(final ConnectionSource conn...
@Test public void testTransactionManager() throws Exception { ConnectionSource connectionSource = createMock(ConnectionSource.class); DatabaseConnection conn = createMock(DatabaseConnection.class); expect(conn.isAutoCommitSupported()).andReturn(false); Savepoint savePoint = createMock(Savepoint.class); expect(savePoint...
TransactionManager { public void initialize() { if (connectionSource == null) { throw new IllegalStateException("dataSource was not set on " + getClass().getSimpleName()); } } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable)...
@Test(expected = IllegalStateException.class) public void testTransactionManagerNoSet() { TransactionManager tm = new TransactionManager(); tm.initialize(); }
TransactionManager { private static void rollBack(DatabaseConnection connection, Savepoint savePoint) throws SQLException { String name = (savePoint == null ? null : savePoint.getSavepointName()); connection.rollback(savePoint); if (name == null) { logger.debug("rolled back savePoint transaction"); } else { logger.debu...
@Test public void testRollBack() throws Exception { if (connectionSource == null) { return; } TransactionManager mgr = new TransactionManager(connectionSource); final Dao<Foo, Integer> fooDao = createDao(Foo.class, true); testTransactionManager(mgr, new RuntimeException("What!! I protest!!"), fooDao); }
TransactionManager { public <T> T callInTransaction(final Callable<T> callable) throws SQLException { return callInTransaction(connectionSource, callable); } TransactionManager(); TransactionManager(ConnectionSource connectionSource); void initialize(); T callInTransaction(final Callable<T> callable); T callInTransact...
@Test public void testTransactionWithinTransaction() throws Exception { if (connectionSource == null) { return; } final TransactionManager mgr = new TransactionManager(connectionSource); final Dao<Foo, Integer> dao = createDao(Foo.class, true); mgr.callInTransaction(new Callable<Void>() { @Override public Void call() t...
SqlExceptionUtil { public static SQLException create(String message, Throwable cause) { SQLException sqlException; if (cause instanceof SQLException) { sqlException = new SQLException(message, ((SQLException) cause).getSQLState()); } else { sqlException = new SQLException(message); } sqlException.initCause(cause); retu...
@Test public void testException() { Throwable cause = new Throwable(); String msg = "hello"; SQLException e = SqlExceptionUtil.create(msg, cause); assertEquals(msg, e.getMessage()); assertEquals(cause, e.getCause()); } @Test public void testExceptionWithSQLException() { String sqlReason = "sql exception message"; Strin...
BaseDaoEnabled { public int create() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.create(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID...
@Test public void testCreate() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff = "fewpfjewfew"; one.stuff = stuff; one.setDao(dao); assertEquals(1, one.create()); } @Test(expected = SQLException.class) public void testCreateNoDao() throws Exception { One one = ne...
Parser implements ParserTreeConstants, ParserConstants { final public void StringLiteral() throws ParseException { ASTStringLiteral jjtn000 = new ASTStringLiteral(JJTSTRINGLITERAL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1));Token t; try { t = jj_consume_token(STRING_LI...
@Test public void testStringLiteral() throws Exception { String sql = "select #if (:1 == 'hello') ok #end"; ASTRootNode n = new Parser(sql).parse().init(); ParameterContext ctx = getParameterContext(Lists.newArrayList((Type) String.class)); n.checkAndBind(ctx); InvocationContext context = DefaultInvocationContext.creat...
BaseDaoEnabled { public int update() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.update(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID...
@Test public void testUpdate() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); String stuff2 = "fjpfejpwewpfjewfew"; one.stuff = stuff2; assertEquals(1, one.update()); One one2 = dao.queryFor...
BaseDaoEnabled { public int updateId(ID newId) throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.updateId(t, newId); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); vo...
@Test public void testUpdateId() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); int id = one.id; assertNotNull(dao.queryForId(id)); assertEquals(1, one.updateId(id + 1)); assertNull(dao.quer...
BaseDaoEnabled { public int delete() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.delete(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<T, ID...
@Test public void testDelete() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); assertNotNull(dao.queryForId(one.id)); assertEquals(1, one.delete()); assertNull(dao.queryForId(one.id)); }
BaseDaoEnabled { public String objectToString() { try { checkForDao(); } catch (SQLException e) { throw new IllegalArgumentException(e); } @SuppressWarnings("unchecked") T t = (T) this; return dao.objectToString(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToStrin...
@Test(expected = IllegalArgumentException.class) public void testObjectEqualsNoDao() { One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; one.objectToString(); }
BaseDaoEnabled { public ID extractId() throws SQLException { checkForDao(); @SuppressWarnings("unchecked") T t = (T) this; return dao.extractId(t); } int create(); int refresh(); int update(); int updateId(ID newId); int delete(); String objectToString(); ID extractId(); boolean objectsEqual(T other); void setDao(Dao<...
@Test public void testExtractId() throws Exception { Dao<One, Integer> dao = createDao(One.class, true); One one = new One(); String stuff1 = "fewpfjewfew"; one.stuff = stuff1; assertEquals(1, dao.create(one)); assertEquals(one.id, (int) one.extractId()); }
Logger { public boolean isLevelEnabled(Level level) { return log.isLevelEnabled(level); } Logger(Log log); boolean isLevelEnabled(Level level); void trace(String msg); void trace(String msg, Object arg0); void trace(String msg, Object arg0, Object arg1); void trace(String msg, Object arg0, Object arg1, Object arg2); vo...
@Test public void testIsEnabled() { for (Level level : Level.values()) { reset(mockLog); expect(mockLog.isLevelEnabled(level)).andReturn(true); expect(mockLog.isLevelEnabled(level)).andReturn(false); replay(mockLog); assertTrue(logger.isLevelEnabled(level)); assertFalse(logger.isLevelEnabled(level)); verify(mockLog); }...
LocalLog implements Log { @Override public boolean isLevelEnabled(Level level) { return this.level.isEnabled(level); } LocalLog(String className); static void openLogFile(String logPath); @Override boolean isLevelEnabled(Level level); @Override void log(Level level, String msg); @Override void log(Level level, String m...
@Test public void testLevelProperty() { Log log = new LocalLog("foo"); if (log.isLevelEnabled(Level.TRACE)) { return; } System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "TRACE"); try { log = new LocalLog("foo"); assertTrue(log.isLevelEnabled(Level.TRACE)); } finally { System.clearProperty(LocalLog.LOCAL_LOG_LEVEL_...
LocalLog implements Log { public static void openLogFile(String logPath) { if (logPath == null) { printStream = System.out; } else { try { printStream = new PrintStream(new File(logPath)); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Log file " + logPath + " was not found", e); } } } LocalLog...
@Test(expected = IllegalArgumentException.class) public void testInvalidFileProperty() { LocalLog.openLogFile("not-a-proper-directory-name-we-hope/foo.txt"); }
LocalLog implements Log { static List<PatternLevel> readLevelResourceFile(InputStream stream) { List<PatternLevel> levels = null; if (stream != null) { try { levels = configureClassLevels(stream); } catch (IOException e) { System.err.println( "IO exception reading the log properties file '" + LOCAL_LOG_PROPERTIES_FILE ...
@Test public void testInvalidLevelsFile() { StringWriter stringWriter = new StringWriter(); stringWriter.write("x\n"); stringWriter.write("com\\.j256\\.ormlite\\.stmt\\.StatementExecutor = INVALID_LEVEL\n"); LocalLog.readLevelResourceFile(new ByteArrayInputStream(stringWriter.toString().getBytes())); } @Test public voi...
LoggerFactory { public static Logger getLogger(Class<?> clazz) { return getLogger(clazz.getName()); } private LoggerFactory(); static Logger getLogger(Class<?> clazz); static Logger getLogger(String className); static String getSimpleClassName(String className); static final String LOG_TYPE_SYSTEM_PROPERTY; }
@Test public void testGetLoggerClass() { assertNotNull(LoggerFactory.getLogger(getClass())); } @Test public void testGetLoggerString() { assertNotNull(LoggerFactory.getLogger(getClass().getName())); }
LoggerFactory { public static String getSimpleClassName(String className) { String[] parts = className.split("\\."); if (parts.length <= 1) { return className; } else { return parts[parts.length - 1]; } } private LoggerFactory(); static Logger getLogger(Class<?> clazz); static Logger getLogger(String className); stati...
@Test public void testGetSimpleClassName() { String first = "foo"; String name = LoggerFactory.getSimpleClassName(first); assertEquals(first, name); String second = "bar"; String className = first + "." + second; name = LoggerFactory.getSimpleClassName(className); assertEquals(second, name); }
TableInfo { public TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass) throws SQLException { this(connectionSource.getDatabaseType(), baseDaoImpl, DatabaseTableConfig.fromClass(connectionSource, dataClass)); } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> b...
@Test(expected = IllegalArgumentException.class) public void testTableInfo() throws SQLException { new TableInfo<NoFieldAnnotations, Void>(connectionSource, null, NoFieldAnnotations.class); }
TableInfo { public String objectToString(T object) { StringBuilder sb = new StringBuilder(64); sb.append(object.getClass().getSimpleName()); for (FieldType fieldType : fieldTypes) { sb.append(' ').append(fieldType.getColumnName()).append('='); try { sb.append(fieldType.extractJavaFieldValue(object)); } catch (Exception...
@Test public void testObjectToString() throws Exception { String id = "f11232oo"; Foo foo = new Foo(); foo.id = id; assertEquals(id, foo.id); TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(connectionSource, null, Foo.class); assertTrue(tableInfo.objectToString(foo).contains(id)); }
TableInfo { public String getTableName() { return tableName; } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseType, BaseDaoImpl<T, ID> baseDaoImpl, DatabaseTableConfig<T> tableConfig); Class<T> getDataClass(); String getTableName(); Fiel...
@Test public void testNoTableNameInAnnotation() throws Exception { TableInfo<NoTableNameAnnotation, Void> tableInfo = new TableInfo<NoTableNameAnnotation, Void>(connectionSource, null, NoTableNameAnnotation.class); assertEquals(NoTableNameAnnotation.class.getSimpleName().toLowerCase(), tableInfo.getTableName()); }
TableInfo { public T createObject() throws SQLException { try { T instance; ObjectFactory<T> factory = null; if (baseDaoImpl != null) { factory = baseDaoImpl.getObjectFactory(); } if (factory == null) { instance = constructor.newInstance(); } else { instance = factory.createObject(constructor, baseDaoImpl.getDataClass(...
@Test public void testConstruct() throws Exception { TableInfo<Foo, String> tableInfo = new TableInfo<Foo, String>(connectionSource, null, Foo.class); Foo foo = tableInfo.createObject(); assertNotNull(foo); }
TableInfo { public FieldType getFieldTypeByColumnName(String columnName) { if (fieldNameMap == null) { Map<String, FieldType> map = new HashMap<String, FieldType>(); for (FieldType fieldType : fieldTypes) { map.put(fieldType.getColumnName().toLowerCase(), fieldType); } fieldNameMap = map; } FieldType fieldType = fieldN...
@Test public void testUnknownForeignField() throws Exception { TableInfo<Foreign, Void> tableInfo = new TableInfo<Foreign, Void>(connectionSource, null, Foreign.class); try { tableInfo.getFieldTypeByColumnName("foo"); fail("expected exception"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains(...
TableInfo { public boolean hasColumnName(String columnName) { for (FieldType fieldType : fieldTypes) { if (fieldType.getColumnName().equals(columnName)) { return true; } } return false; } TableInfo(ConnectionSource connectionSource, BaseDaoImpl<T, ID> baseDaoImpl, Class<T> dataClass); TableInfo(DatabaseType databaseTy...
@Test public void testHasColumnName() throws Exception { Dao<Foo, String> dao = createDao(Foo.class, true); TableInfo<Foo, String> tableInfo = ((BaseDaoImpl<Foo, String>) dao).getTableInfo(); assertTrue(tableInfo.hasColumnName(COLUMN_NAME)); assertFalse(tableInfo.hasColumnName("not this name")); }
DatabaseTableConfigLoader { public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException { try { writeConfig(writer, config); } catch (IOException e) { throw SqlExceptionUtil.create("Could not write config to writer", e); } } static List<DatabaseTableConfig<?>> loadDatabaseCon...
@Test public void testConfigFile() throws Exception { DatabaseTableConfig<NoFields> config = new DatabaseTableConfig<NoFields>(); StringBuilder body = new StringBuilder(); StringWriter writer = new StringWriter(); BufferedWriter buffer = new BufferedWriter(writer); Class<NoFields> clazz = NoFields.class; config.setData...
DatabaseTableConfigLoader { public static List<DatabaseTableConfig<?>> loadDatabaseConfigFromReader(BufferedReader reader) throws SQLException { List<DatabaseTableConfig<?>> list = new ArrayList<DatabaseTableConfig<?>>(); while (true) { DatabaseTableConfig<?> config = DatabaseTableConfigLoader.fromReader(reader); if (c...
@Test public void testConfigEntriesFromStream() throws Exception { StringBuilder value = new StringBuilder(); value.append(TABLE_START); value.append("# random comment").append(LINE_SEP); value.append(LINE_SEP); value.append("dataClass=").append(Foo.class.getName()).append(LINE_SEP); String tableName = "fprwojfgopwejfw...
DatabaseTableConfig { public DatabaseTableConfig() { } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig> fieldConfigs); DatabaseTableConfig(Class<T> dataClass, String tableName, List<DatabaseFieldConfig> fieldConfigs); private DatabaseTableConfig(Class<T> dataClass, String tabl...
@Test public void testDatabaseTableConfig() throws SQLException { DatabaseTableConfig<DatabaseTableAnno> dbTableConf = DatabaseTableConfig.fromClass(connectionSource, DatabaseTableAnno.class); assertEquals(DatabaseTableAnno.class, dbTableConf.getDataClass()); assertEquals(TABLE_NAME, dbTableConf.getTableName()); dbTabl...
DatabaseTableConfig { public void setFieldConfigs(List<DatabaseFieldConfig> fieldConfigs) { this.fieldConfigs = fieldConfigs; } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig> fieldConfigs); DatabaseTableConfig(Class<T> dataClass, String tableName, List<DatabaseFieldConfig> fi...
@Test public void testSetFieldConfigs() throws SQLException { DatabaseTableConfig<DatabaseTableAnno> dbTableConf = new DatabaseTableConfig<DatabaseTableAnno>(); dbTableConf.setDataClass(DatabaseTableAnno.class); dbTableConf.setTableName(TABLE_NAME); List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldCo...
DatabaseTableConfig { public void initialize() { if (dataClass == null) { throw new IllegalStateException("dataClass was never set on " + getClass().getSimpleName()); } if (tableName == null) { tableName = extractTableName(dataClass); } } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFiel...
@Test(expected = IllegalStateException.class) public void testBadSpringWiring() { DatabaseTableConfig<NoFields> dbTableConf = new DatabaseTableConfig<NoFields>(); dbTableConf.initialize(); }
ConsoleLogger extends AbstractInternalLogger { @Override public void trace(String msg) { println(msg); } protected ConsoleLogger(String name); @Override boolean isTraceEnabled(); @Override void trace(String msg); @Override void trace(String format, Object arg); @Override void trace(String format, Object argA, Object a...
@Test public void testMsg() throws Exception { ConsoleLogger logger = new ConsoleLogger("org"); logger.trace("ok"); }
DatabaseTableConfig { public FieldType[] getFieldTypes(DatabaseType databaseType) throws SQLException { if (fieldTypes == null) { throw new SQLException("Field types have not been extracted in table config"); } return fieldTypes; } DatabaseTableConfig(); DatabaseTableConfig(Class<T> dataClass, List<DatabaseFieldConfig...
@Test(expected = SQLException.class) public void testNoFields() throws SQLException { new DatabaseTableConfig<DatabaseTableAnno>().getFieldTypes(databaseType); }
TableUtils { public static <T, ID> List<String> getCreateTableStatements(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); if (dao instanceof BaseDaoImpl<?, ?>) { return addCreateTableStatements(connectionSource, ((BaseDaoImp...
@Test public void testCreateStatements() throws Exception { List<String> stmts = TableUtils.getCreateTableStatements(connectionSource, LocalFoo.class); assertEquals(1, stmts.size()); assertEquals(expectedCreateStatement(), stmts.get(0)); } @Test public void testCreateStatementsTableConfig() throws Exception { List<Stri...
TableUtils { public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass); return doCreateTable(dao, false); } private TableUtils(); static int createTable(ConnectionSource connectionSource, Class<T> dat...
@Test public void testCreateTableQueriesAfter() throws Exception { final String queryAfter = "SELECT * from foo"; DatabaseType databaseType = new H2DatabaseType() { @Override public void appendColumnArg(String tableName, StringBuilder sb, FieldType fieldType, List<String> additionalArgs, List<String> statementsBefore, ...
TableUtils { public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors) throws SQLException { Dao<T, ID> dao = DaoManager.createDao(connectionSource, dataClass); return dropTable(dao, ignoreErrors); } private TableUtils(); static int createTable(ConnectionSource co...
@Test public void testDropTable() throws Exception { final ConnectionSource connectionSource = createMock(ConnectionSource.class); testDrop("localfoo", connectionSource, 0, false, new Callable<Integer>() { @Override public Integer call() throws Exception { return (int) TableUtils.dropTable(connectionSource, LocalFoo.cl...
TableUtils { public static <T> int clearTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { String tableName = DatabaseTableConfig.extractTableName(dataClass); DatabaseType databaseType = connectionSource.getDatabaseType(); if (databaseType.isEntityNamesMustBeUpCase()) { tableName = datab...
@Test public void testClearTable() throws Exception { Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, true); assertEquals(0, fooDao.countOf()); LocalFoo foo = new LocalFoo(); assertEquals(1, fooDao.create(foo)); assertEquals(1, fooDao.countOf()); TableUtils.clearTable(connectionSource, LocalFoo.class); assert...
TableUtils { public static <T> int createTableIfNotExists(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException { Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass); return doCreateTable(dao, true); } private TableUtils(); static int createTable(ConnectionSource connectionSource, Cl...
@Test public void testCreateTableIfNotExists() throws Exception { dropTable(LocalFoo.class, true); Dao<LocalFoo, Integer> fooDao = createDao(LocalFoo.class, false); try { fooDao.countOf(); fail("Should have thrown an exception"); } catch (Exception e) { } TableUtils.createTableIfNotExists(connectionSource, LocalFoo.cla...
BaseDatabaseType implements DatabaseType { @Override public void loadDriver() throws SQLException { String className = getDriverClassName(); if (className != null) { try { Class.forName(className); } catch (ClassNotFoundException e) { throw SqlExceptionUtil.create("Driver class was not found for " + getDatabaseName() +...
@Test(expected = SQLException.class) public void testDriverNotFound() throws SQLException { new TestDatabaseType().loadDriver(); }
BaseDatabaseType implements DatabaseType { protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter, List<String> additionalArgs, List<String> queriesAfter) { throw new IllegalStateException( "GeneratedId is not supported by...
@Test(expected = IllegalStateException.class) public void testConfigureGeneratedId() { new TestDatabaseType().configureGeneratedId(null, new StringBuilder(), null, new ArrayList<String>(), null, new ArrayList<String>(), new ArrayList<String>()); }
BaseSqliteDatabaseType extends BaseDatabaseType { @Override protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, List<String> statementsBefore, List<String> statementsAfter, List<String> additionalArgs, List<String> queriesAfter) { if (fieldType.getSqlType() != SqlType.INTEGER &&...
@Test(expected = IllegalArgumentException.class) public void testConfigureGeneratedIdNotInteger() throws Exception { Field field = Foo.class.getField("stringField"); FieldType fieldType = FieldType.createFieldType(connectionSource, "foo", field, Foo.class); OurSqliteDatabaseType dbType = new OurSqliteDatabaseType(); St...
BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isVarcharFieldWidthSupported() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPe...
@Test public void testIsVarcharFieldWidthSupported() { assertFalse(new OurSqliteDatabaseType().isVarcharFieldWidthSupported()); }
BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isCreateTableReturnsZero() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersis...
@Test public void testIsCreateTableReturnsZero() { assertFalse(new OurSqliteDatabaseType().isCreateTableReturnsZero()); }
BaseSqliteDatabaseType extends BaseDatabaseType { @Override protected boolean generatedIdSqlAtEnd() { return false; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPersiste...
@Test public void testGeneratedIdSqlAtEnd() { assertFalse(new OurSqliteDatabaseType().generatedIdSqlAtEnd()); }
BaseSqliteDatabaseType extends BaseDatabaseType { @Override public boolean isCreateIfNotExistsSupported() { return true; } @Override boolean isVarcharFieldWidthSupported(); @Override boolean isCreateTableReturnsZero(); @Override boolean isCreateIfNotExistsSupported(); @Override FieldConverter getFieldConverter(DataPer...
@Test public void testIsCreateIfNotExistsSupported() { assertTrue(new OurSqliteDatabaseType().isCreateIfNotExistsSupported()); }