src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ExternalNegotiator implements SaslNegotiator { @Override public AuthenticationResult handleResponse(final byte[] response) { if (_isComplete) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException( "Multiple Authentications not permitted.")); } else { _isComplete = true; } return _result; } ExternalNegotiator(final ExternalAuthenticationManager externalAuthenticationManager,
final Principal externalPrincipal); @Override AuthenticationResult handleResponse(final byte[] response); @Override void dispose(); @Override String getAttemptedAuthenticationId(); }
|
@Test public void testHandleResponseUseFullDNValidExternalPrincipal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(true); X500Principal externalPrincipal = new X500Principal(VALID_USER_DN); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, externalPrincipal); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.SUCCESS, firstResult.getStatus()); String principalName = firstResult.getMainPrincipal().getName(); assertTrue(String.format("Unexpected first result principal '%s'", principalName), VALID_USER_DN.equalsIgnoreCase(principalName)); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected second result status", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
@Test public void testHandleResponseNotUseFullDNValidExternalPrincipal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(false); X500Principal externalPrincipal = new X500Principal(VALID_USER_DN); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, externalPrincipal); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.SUCCESS, firstResult.getStatus()); String principalName = firstResult.getMainPrincipal().getName(); assertEquals("Unexpected first result principal", VALID_USER_NAME, principalName); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected second result status", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
@Test public void testHandleResponseNotUseFullDN_No_CN_DC_In_ExternalPrincipal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(false); X500Principal externalPrincipal = new X500Principal(USERNAME_NO_CN_DC); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, externalPrincipal); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.ERROR, firstResult.getStatus()); assertNull("Unexpected first result principal", firstResult.getMainPrincipal()); }
@Test public void testHandleResponseUseFullDN_No_CN_DC_In_ExternalPrincipal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(true); X500Principal externalPrincipal = new X500Principal(USERNAME_NO_CN_DC); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, externalPrincipal); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.SUCCESS, firstResult.getStatus()); String principalName = firstResult.getMainPrincipal().getName(); assertTrue(String.format("Unexpected first result principal '%s'", principalName), USERNAME_NO_CN_DC.equalsIgnoreCase(principalName)); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected second result status", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
@Test public void testHandleResponseFailsWithoutExternalPrincipal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(true); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, null); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.ERROR, firstResult.getStatus()); assertNull("Unexpected first result principal", firstResult.getMainPrincipal()); }
@Test public void testHandleResponseSucceedsForNonX500Principal() throws Exception { ExternalAuthenticationManager<?> externalAuthenticationManager = mock(ExternalAuthenticationManager.class); when(externalAuthenticationManager.getUseFullDN()).thenReturn(true); Principal principal = mock(Principal.class); ExternalNegotiator negotiator = new ExternalNegotiator(externalAuthenticationManager, principal); AuthenticationResult firstResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first result status", AuthenticationResult.AuthenticationStatus.SUCCESS, firstResult.getStatus()); assertEquals("Unexpected first result principal", principal, firstResult.getMainPrincipal()); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected second result status", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
|
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { public ZippedContent getFilesAsZippedContent(Set<String> fileNames) { if (fileNames == null) { throw new IllegalArgumentException("File name cannot be null"); } Map<String, Path> paths = new TreeMap<>(); for (String name: fileNames) { Path filePath = getPath(name); if (filePath != null) { paths.put(name, filePath); } } return new ZippedContent(paths); } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }
|
@Test public void testGetFilesAsZippedContentWithNonLogFile() throws Exception { String[] fileNames = createTestRolledFilesAndNotifyWatcher(); String nonLogFileName = "nonLogFile.txt"; TestFileUtils.saveTextContentInFile(nonLogFileName, new File(_baseFolder, nonLogFileName)); String[] requestedFiles = new String[]{ fileNames[0], fileNames[2], nonLogFileName }; String[] expectedFiles = new String[]{ fileNames[0], fileNames[2] }; ZippedContent content = _rolloverWatcher.getFilesAsZippedContent(new HashSet<>(Arrays.asList(requestedFiles))); assertZippedContent(expectedFiles, content); }
@Test public void testGetFilesAsZippedContent() throws Exception { String[] fileNames = createTestRolledFilesAndNotifyWatcher(); String[] requestedFiles = new String[]{ fileNames[0], fileNames[2] }; ZippedContent content = _rolloverWatcher.getFilesAsZippedContent(new HashSet<>(Arrays.asList(requestedFiles))); assertZippedContent(requestedFiles, content); }
@Test public void testGetFilesAsZippedContentWithNonExistingFile() throws Exception { String[] fileNames = createTestRolledFilesAndNotifyWatcher(); new File(_baseFolder, fileNames[2]).delete(); String[] requestedFiles = new String[]{ fileNames[0], fileNames[2] }; String[] expectedFiles = new String[]{ fileNames[0] }; ZippedContent content = _rolloverWatcher.getFilesAsZippedContent(new HashSet<>(Arrays.asList(requestedFiles))); assertZippedContent(expectedFiles, content); }
|
PlainNegotiator implements SaslNegotiator { @Override public AuthenticationResult handleResponse(final byte[] response) { if (_state == State.COMPLETE) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException("Multiple Authentications not permitted.")); } else if (_state == State.INITIAL && (response == null || response.length == 0)) { _state = State.CHALLENGE_SENT; return new AuthenticationResult(new byte[0], AuthenticationResult.AuthenticationStatus.CONTINUE); } _state = State.COMPLETE; if (response == null || response.length == 0) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException( "Invalid PLAIN encoding, authzid null terminator not found")); } int authzidNullPosition = findNullPosition(response, 0); if (authzidNullPosition < 0) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException( "Invalid PLAIN encoding, authzid null terminator not found")); } int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); if (authcidNullPosition < 0) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalArgumentException( "Invalid PLAIN encoding, authcid null terminator not found")); } String password; _username = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, UTF8); int passwordLen = response.length - authcidNullPosition - 1; password = new String(response, authcidNullPosition + 1, passwordLen, UTF8); return _usernamePasswordAuthenticationProvider.authenticate(_username, password); } PlainNegotiator(final UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider); @Override AuthenticationResult handleResponse(final byte[] response); @Override void dispose(); @Override String getAttemptedAuthenticationId(); static final String MECHANISM; }
|
@Test public void testHandleResponse() throws Exception { final AuthenticationResult result = _negotiator.handleResponse(VALID_RESPONSE.getBytes(US_ASCII)); verify(_authenticationProvider).authenticate(eq(VALID_USERNAME), eq(VALID_PASSWORD)); assertEquals("Unexpected authentication result", _successfulResult, result); }
@Test public void testMultipleAuthenticationAttempts() throws Exception { final AuthenticationResult firstResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes(US_ASCII)); assertEquals("Unexpected first authentication result", _successfulResult, firstResult); final AuthenticationResult secondResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes(US_ASCII)); assertEquals("Unexpected second authentication result", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
@Test public void testHandleInvalidUser() throws Exception { final AuthenticationResult result = _negotiator.handleResponse(String.format(RESPONSE_FORMAT_STRING, "invalidUser", VALID_PASSWORD).getBytes(US_ASCII)); assertEquals("Unexpected authentication result", _errorResult, result); }
@Test public void testHandleInvalidPassword() throws Exception { final AuthenticationResult result = _negotiator.handleResponse(String.format(RESPONSE_FORMAT_STRING, VALID_USERNAME, "invalidPassword").getBytes(US_ASCII)); assertEquals("Unexpected authentication result", _errorResult, result); }
@Test public void testHandleNeverSendAResponse() throws Exception { final AuthenticationResult firstResult = _negotiator.handleResponse(new byte[0]); assertEquals("Unexpected authentication status", AuthenticationResult.AuthenticationStatus.CONTINUE, firstResult.getStatus()); assertArrayEquals("Unexpected authentication challenge", new byte[0], firstResult.getChallenge()); final AuthenticationResult secondResult = _negotiator.handleResponse(new byte[0]); assertEquals("Unexpected first authentication result", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
@Test public void testHandleNoInitialResponse() throws Exception { final AuthenticationResult result = _negotiator.handleResponse(new byte[0]); assertEquals("Unexpected authentication status", AuthenticationResult.AuthenticationStatus.CONTINUE, result.getStatus()); assertArrayEquals("Unexpected authentication challenge", new byte[0], result.getChallenge()); final AuthenticationResult firstResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes()); assertEquals("Unexpected first authentication result", _successfulResult, firstResult); }
@Test public void testHandleNoInitialResponseNull() throws Exception { final AuthenticationResult result = _negotiator.handleResponse(null); assertEquals("Unexpected authentication status", AuthenticationResult.AuthenticationStatus.CONTINUE, result.getStatus()); assertArrayEquals("Unexpected authentication challenge", new byte[0], result.getChallenge()); final AuthenticationResult firstResult = _negotiator.handleResponse(VALID_RESPONSE.getBytes()); assertEquals("Unexpected first authentication result", _successfulResult, firstResult); }
|
AnonymousNegotiator implements SaslNegotiator { @Override public AuthenticationResult handleResponse(final byte[] response) { if (_isComplete) { return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, new IllegalStateException( "Multiple Authentications not permitted.")); } else { _isComplete = true; } return _anonymousAuthenticationResult; } AnonymousNegotiator(final AuthenticationResult anonymousAuthenticationResult); @Override AuthenticationResult handleResponse(final byte[] response); @Override void dispose(); @Override String getAttemptedAuthenticationId(); }
|
@Test public void testHandleResponse() throws Exception { final AuthenticationResult result = mock(AuthenticationResult.class); AnonymousNegotiator negotiator = new AnonymousNegotiator(result); final Object actual = negotiator.handleResponse(new byte[0]); assertEquals("Unexpected result", result, actual); AuthenticationResult secondResult = negotiator.handleResponse(new byte[0]); assertEquals("Only first call to handleResponse should be successful", AuthenticationResult.AuthenticationStatus.ERROR, secondResult.getStatus()); }
|
SubjectCreator { public SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response) { AuthenticationResult authenticationResult = saslNegotiator.handleResponse(response); if(authenticationResult.getStatus() == AuthenticationStatus.SUCCESS) { return createResultWithGroups(authenticationResult); } else { if (authenticationResult.getStatus() == AuthenticationStatus.ERROR) { String authenticationId = saslNegotiator.getAttemptedAuthenticationId(); _authenticationProvider.getEventLogger().message(AUTHENTICATION_FAILED(authenticationId, authenticationId != null)); } return new SubjectAuthenticationResult(authenticationResult); } } SubjectCreator(AuthenticationProvider<?> authenticationProvider,
Collection<GroupProvider<?>> groupProviders,
NamedAddressSpace addressSpace); AuthenticationProvider<?> getAuthenticationProvider(); SaslNegotiator createSaslNegotiator(String mechanism, final SaslSettings saslSettings); SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response); SubjectAuthenticationResult createResultWithGroups(final AuthenticationResult authenticationResult); Subject createSubjectWithGroups(Principal userPrincipal); }
|
@Test public void testSaslAuthenticationSuccessReturnsSubjectWithUserAndGroupPrincipals() throws Exception { when(_testSaslNegotiator.handleResponse(_saslResponseBytes)).thenReturn(_authenticationResult); SubjectAuthenticationResult result = _subjectCreator.authenticate(_testSaslNegotiator, _saslResponseBytes); final Subject actualSubject = result.getSubject(); assertEquals("Should contain one user principal and two groups ", (long) 3, (long) actualSubject.getPrincipals().size()); assertTrue(actualSubject.getPrincipals().contains(new AuthenticatedPrincipal(USERNAME_PRINCIPAL))); assertTrue(actualSubject.getPrincipals().contains(_group1)); assertTrue(actualSubject.getPrincipals().contains(_group2)); assertTrue(actualSubject.isReadOnly()); }
|
SubjectCreator { Set<Principal> getGroupPrincipals(Principal userPrincipal) { Set<Principal> principals = new HashSet<Principal>(); for (GroupProvider groupProvider : _groupProviders) { Set<Principal> groups = groupProvider.getGroupPrincipalsForUser(userPrincipal); if (groups != null) { principals.addAll(groups); } } return Collections.unmodifiableSet(principals); } SubjectCreator(AuthenticationProvider<?> authenticationProvider,
Collection<GroupProvider<?>> groupProviders,
NamedAddressSpace addressSpace); AuthenticationProvider<?> getAuthenticationProvider(); SaslNegotiator createSaslNegotiator(String mechanism, final SaslSettings saslSettings); SubjectAuthenticationResult authenticate(SaslNegotiator saslNegotiator, byte[] response); SubjectAuthenticationResult createResultWithGroups(final AuthenticationResult authenticationResult); Subject createSubjectWithGroups(Principal userPrincipal); }
|
@Test public void testGetGroupPrincipals() { getAndAssertGroupPrincipals(_group1, _group2); }
|
CompositeInputStream extends InputStream { @Override public int read() throws IOException { int count = -1; if (_current != null) { count = _current.read(); } if (count == -1 && _inputStreams.size() > 0) { if (_current != null) { _current.close(); } _current = _inputStreams.removeFirst(); count = read(); } return count; } CompositeInputStream(Collection<InputStream> streams); @Override int read(); @Override int read(byte[] b, int off, int len); @Override int read(byte[] b); @Override int available(); @Override boolean markSupported(); @Override void mark(final int readlimit); @Override void reset(); @Override void close(); }
|
@Test public void testReadByteByByte_MultipleStreams() throws Exception { InputStream bis1 = new ByteArrayInputStream("ab".getBytes()); InputStream bis2 = new ByteArrayInputStream("cd".getBytes()); CompositeInputStream cis = new CompositeInputStream(Arrays.asList(bis1, bis2)); assertEquals("1st read byte unexpected", 'a', cis.read()); assertEquals("2nd read byte unexpected", 'b', cis.read()); assertEquals("3rd read byte unexpected", 'c', cis.read()); assertEquals("4th read byte unexpected", 'd', cis.read()); assertEquals("Expecting EOF", -1, cis.read()); }
@Test public void testReadByteArray_MultipleStreams() throws Exception { InputStream bis1 = new ByteArrayInputStream("ab".getBytes()); InputStream bis2 = new ByteArrayInputStream("cd".getBytes()); CompositeInputStream cis = new CompositeInputStream(Arrays.asList(bis1, bis2)); byte[] buf = new byte[3]; int read1 = cis.read(buf); assertEquals("Unexpected return value from 1st array read", 3, read1); assertArrayEquals("Unexpected bytes from 1st array read", "abc".getBytes(), buf); int read2 = cis.read(buf); assertEquals("Unexpected return value from 2nd array read", 1, read2); assertArrayEquals("Unexpected bytes from 1st array read", "d".getBytes(), Arrays.copyOf(buf, 1)); int read3 = cis.read(buf); assertEquals("Expecting EOF", -1, read3); }
@Test public void testReadsMixed_SingleStream() throws Exception { InputStream bis = new ByteArrayInputStream("abcd".getBytes()); CompositeInputStream cis = new CompositeInputStream(Arrays.asList(bis)); byte[] buf = new byte[3]; int read1 = cis.read(buf); assertEquals("Unexpected return value from 1st array read", 3, read1); assertArrayEquals("Unexpected bytes from 1st array read", "abc".getBytes(), buf); assertEquals("1st read byte unexpected", 'd', cis.read()); assertEquals("Expecting EOF", -1, cis.read(buf)); }
|
CompositeInputStream extends InputStream { @Override public void close() throws IOException { IOException ioException = null; try { if (_current != null) { try { _current.close(); _current = null; } catch (IOException e) { ioException = e; } } for (InputStream is : _inputStreams) { try { is.close(); } catch (IOException e) { if (ioException != null) { ioException = e; } } } } finally { if (ioException != null) { throw ioException; } } } CompositeInputStream(Collection<InputStream> streams); @Override int read(); @Override int read(byte[] b, int off, int len); @Override int read(byte[] b); @Override int available(); @Override boolean markSupported(); @Override void mark(final int readlimit); @Override void reset(); @Override void close(); }
|
@Test public void testClose() throws Exception { InputStream bis1 = mock(InputStream.class); InputStream bis2 = mock(InputStream.class); CompositeInputStream cis = new CompositeInputStream(Arrays.asList(bis1, bis2)); cis.close(); verify(bis1).close(); verify(bis1).close(); when(bis1.read()).thenThrow(new IOException("mocked stream closed")); try { cis.read(); fail("Excetion not thrown"); } catch(IOException ioe) { } }
|
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int getConnectionCount() { return _connectionCount; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }
|
@Test public void getOpenConnectionCount() { final ConnectionPrincipalStatistics stats = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(System.currentTimeMillis())); assertEquals(1, stats.getConnectionCount()); }
|
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int getConnectionFrequency() { return _latestConnectionCreatedTimes.size(); } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }
|
@Test public void getOpenConnectionFrequency() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats = new ConnectionPrincipalStatisticsImpl(1, Arrays.asList(connectionCreatedTime - 1000, connectionCreatedTime)); assertEquals(2, stats.getConnectionFrequency()); }
|
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { List<Long> getLatestConnectionCreatedTimes() { return _latestConnectionCreatedTimes; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }
|
@Test public void getLatestConnectionCreatedTimes() { final long connectionCreatedTime = System.currentTimeMillis(); final List<Long> connectionCreatedTimes = Arrays.asList(connectionCreatedTime - 1000, connectionCreatedTime); final ConnectionPrincipalStatisticsImpl stats = new ConnectionPrincipalStatisticsImpl(1, connectionCreatedTimes); assertEquals(connectionCreatedTimes, stats.getLatestConnectionCreatedTimes()); }
|
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ConnectionPrincipalStatisticsImpl that = (ConnectionPrincipalStatisticsImpl) o; if (_connectionCount != that._connectionCount) { return false; } return _latestConnectionCreatedTimes.equals(that._latestConnectionCreatedTimes); } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }
|
@Test public void equals() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats1 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); final ConnectionPrincipalStatistics stats2 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); assertEquals(stats1, stats2); final long connectionCreatedTime2 = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats3 = new ConnectionPrincipalStatisticsImpl(2, Arrays.asList(connectionCreatedTime, connectionCreatedTime2)); assertNotEquals(stats2, stats3); assertNotEquals(stats1, stats3); }
|
ConnectionPrincipalStatisticsImpl implements ConnectionPrincipalStatistics { @Override public int hashCode() { int result = _connectionCount; result = 31 * result + _latestConnectionCreatedTimes.hashCode(); return result; } ConnectionPrincipalStatisticsImpl(final int connectionCount, final List<Long> latestConnectionCreatedTimes); @Override int getConnectionCount(); @Override int getConnectionFrequency(); @Override boolean equals(final Object o); @Override int hashCode(); }
|
@Test public void testHashCode() { final long connectionCreatedTime = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats1 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); final ConnectionPrincipalStatistics stats2 = new ConnectionPrincipalStatisticsImpl(1, Collections.singletonList(connectionCreatedTime)); assertEquals(stats1.hashCode(), stats2.hashCode()); final long connectionCreatedTime2 = System.currentTimeMillis(); final ConnectionPrincipalStatistics stats3 = new ConnectionPrincipalStatisticsImpl(2, Arrays.asList(connectionCreatedTime, connectionCreatedTime2)); assertNotEquals(stats2.hashCode(), stats3.hashCode()); assertNotEquals(stats1.hashCode(), stats3.hashCode()); }
|
ConnectionPrincipalStatisticsCheckingTask extends HouseKeepingTask { @Override public void execute() { _connectionPrincipalStatisticsRegistry.reevaluateConnectionStatistics(); } ConnectionPrincipalStatisticsCheckingTask(final QueueManagingVirtualHost virtualHost,
final AccessControlContext controlContext,
final ConnectionPrincipalStatisticsRegistry connectionPrincipalStatisticsRegistry); @Override void execute(); }
|
@Test public void execute() { final QueueManagingVirtualHost vh = mock(QueueManagingVirtualHost.class); when(vh.getName()).thenReturn(getTestName()); final ConnectionPrincipalStatisticsRegistry registry = mock(ConnectionPrincipalStatisticsRegistry.class); ConnectionPrincipalStatisticsCheckingTask task = new ConnectionPrincipalStatisticsCheckingTask(vh, AccessController.getContext(), registry); task.execute(); verify(registry).reevaluateConnectionStatistics(); }
|
CacheFactory { public static <K, V> Cache<K, V> getCache(final String cacheName, final Cache<K, V> defaultCache) { Cache<K, V> cache = defaultCache; Subject subject = Subject.getSubject(AccessController.getContext()); if (subject != null) { VirtualHostPrincipal principal = QpidPrincipal.getSingletonPrincipal(subject, true, VirtualHostPrincipal.class); if (principal != null && principal.getVirtualHost() instanceof CacheProvider) { CacheProvider cacheProvider = (CacheProvider) principal.getVirtualHost(); cache = cacheProvider.getNamedCache(cacheName); } } return cache; } static Cache<K, V> getCache(final String cacheName, final Cache<K, V> defaultCache); }
|
@Test public void getCache() { String cacheName = "test"; final Cache<Object, Object> cache = new NullCache<>(); final CacheProvider virtualHost = mock(CacheProvider.class, withSettings().extraInterfaces(VirtualHost.class)); when(virtualHost.getNamedCache(cacheName)).thenReturn(cache); final Subject subject = new Subject(); subject.getPrincipals().add(new VirtualHostPrincipal((VirtualHost<?>) virtualHost)); subject.setReadOnly(); Cache<String, String> actualCache = Subject.doAs(subject, (PrivilegedAction<Cache<String, String>>) () -> CacheFactory.getCache(cacheName, null)); assertSame(actualCache, cache); verify(virtualHost).getNamedCache(cacheName); }
|
AsynchronousMessageStoreRecoverer implements MessageStoreRecoverer { @Override public ListenableFuture<Void> recover(final QueueManagingVirtualHost<?> virtualHost) { _asynchronousRecoverer = new AsynchronousRecoverer(virtualHost); return _asynchronousRecoverer.recover(); } @Override ListenableFuture<Void> recover(final QueueManagingVirtualHost<?> virtualHost); @Override void cancel(); }
|
@Test public void testExceptionOnRecovery() throws Exception { ServerScopedRuntimeException exception = new ServerScopedRuntimeException("test"); doThrow(exception).when(_storeReader).visitMessageInstances(any(TransactionLogResource.class), any(MessageInstanceHandler.class)); Queue<?> queue = mock(Queue.class); when(_virtualHost.getChildren(eq(Queue.class))).thenReturn(Collections.singleton(queue)); AsynchronousMessageStoreRecoverer recoverer = new AsynchronousMessageStoreRecoverer(); ListenableFuture<Void> result = recoverer.recover(_virtualHost); try { result.get(); fail("ServerScopedRuntimeException should be rethrown"); } catch(ExecutionException e) { assertEquals("Unexpected cause", exception, e.getCause()); } }
@Test public void testRecoveryEmptyQueue() throws Exception { Queue<?> queue = mock(Queue.class); when(_virtualHost.getChildren(eq(Queue.class))).thenReturn(Collections.singleton(queue)); AsynchronousMessageStoreRecoverer recoverer = new AsynchronousMessageStoreRecoverer(); ListenableFuture<Void> result = recoverer.recover(_virtualHost); assertNull(result.get()); }
@Test public void testRecoveryWhenLastRecoveryMessageIsConsumedBeforeRecoveryCompleted() throws Exception { Queue<?> queue = mock(Queue.class); when(queue.getId()).thenReturn(UUID.randomUUID()); when(_virtualHost.getChildren(eq(Queue.class))).thenReturn(Collections.singleton(queue)); when(_store.getNextMessageId()).thenReturn(3L); when(_store.newTransaction()).thenReturn(mock(Transaction.class)); final List<StoredMessage<?>> testMessages = new ArrayList<>(); StoredMessage<?> storedMessage = createTestMessage(1L); testMessages.add(storedMessage); StoredMessage<?> orphanedMessage = createTestMessage(2L); testMessages.add(orphanedMessage); StoredMessage newMessage = createTestMessage(4L); testMessages.add(newMessage); final MessageEnqueueRecord messageEnqueueRecord = mock(MessageEnqueueRecord.class); UUID id = queue.getId(); when(messageEnqueueRecord.getQueueId()).thenReturn(id); when(messageEnqueueRecord.getMessageNumber()).thenReturn(1L); MockStoreReader storeReader = new MockStoreReader(Collections.singletonList(messageEnqueueRecord), testMessages); when(_store.newMessageStoreReader()).thenReturn(storeReader); AsynchronousMessageStoreRecoverer recoverer = new AsynchronousMessageStoreRecoverer(); ListenableFuture<Void> result = recoverer.recover(_virtualHost); assertNull(result.get()); verify(orphanedMessage, times(1)).remove(); verify(newMessage, times(0)).remove(); verify(queue).recover(argThat((ArgumentMatcher<ServerMessage>) serverMessage -> serverMessage.getMessageNumber() == storedMessage.getMessageNumber()), same(messageEnqueueRecord)); }
|
AbstractVirtualHost extends AbstractConfiguredObject<X> implements QueueManagingVirtualHost<X> { protected void validateMessageStoreCreation() { MessageStore store = createMessageStore(); if (store != null) { try { store.openMessageStore(this); } catch (Exception e) { throw new IllegalConfigurationException("Cannot open virtual host message store:" + e.getMessage(), e); } finally { try { store.closeMessageStore(); } catch(Exception e) { LOGGER.warn("Failed to close database", e); } } } } AbstractVirtualHost(final Map<String, Object> attributes, VirtualHostNode<?> virtualHostNode); @Override void setFirstOpening(boolean firstOpening); @Override void onValidate(); @Override MessageStore getMessageStore(); @Override boolean isActive(); @Override Collection<? extends Connection<?>> getConnections(); @Override Connection<?> getConnection(String name); @Override int publishMessage(@Param(name = "message") final ManageableMessage message); @Override EventLogger getEventLogger(); @Override Map<String, Object> extractConfig(final boolean includeSecureAttributes); @Override Content exportMessageStore(); @Override void importMessageStore(final String source); @Override boolean authoriseCreateConnection(final AMQPConnection<?> connection); @Override void scheduleHouseKeepingTask(long period, HouseKeepingTask task); @Override ScheduledFuture<?> scheduleTask(long delay, Runnable task); @Override void executeTask(final String name, final Runnable task, AccessControlContext context); @Override List<String> getEnabledConnectionValidators(); @Override List<String> getDisabledConnectionValidators(); @Override List<String> getGlobalAddressDomains(); @Override List<NodeAutoCreationPolicy> getNodeAutoCreationPolicies(); @Override MessageSource getAttainedMessageSource(final String name); @Override Queue<?> getAttainedQueue(UUID id); @Override Queue<?> getAttainedQueue(final String name); @Override Broker<?> getBroker(); @Override MessageDestination getAttainedMessageDestination(final String name, final boolean mayCreate); @Override MessageDestination getSystemDestination(final String name); @Override ListenableFuture<Void> reallocateMessages(); @Override long getTotalDepthOfQueuesBytes(); @Override long getTotalDepthOfQueuesMessages(); @Override long getInMemoryMessageSize(); @Override long getBytesEvacuatedFromMemory(); @Override T getAttainedChildFromAddress(final Class<T> childClass,
final String address); @Override long getInboundMessageSizeHighWatermark(); @Override MessageDestination getDefaultDestination(); @Override String getLocalAddress(final String routingAddress); @Override void registerMessageDelivered(long messageSize); @Override void registerMessageReceived(long messageSize); @Override void registerTransactedMessageReceived(); @Override void registerTransactedMessageDelivered(); @Override long getMessagesIn(); @Override long getBytesIn(); @Override long getMessagesOut(); @Override long getBytesOut(); @Override long getTransactedMessagesIn(); @Override long getTransactedMessagesOut(); @Override T getSendingLink( String remoteContainerId, String linkName); @Override T getReceivingLink(String remoteContainerId, String linkName); @Override Collection<T> findSendingLinks(final Pattern containerIdPattern,
final Pattern linkNamePattern); @Override void visitSendingLinks(final LinkRegistryModel.LinkVisitor<T> visitor); @Override DtxRegistry getDtxRegistry(); @Override void event(final Event event); @Override String getRedirectHost(final AmqpPort<?> port); @Override boolean isOverTargetSize(); @Override void executeTransaction(TransactionalOperation op); @Override long getHousekeepingCheckPeriod(); @Override long getFlowToDiskCheckPeriod(); @Override boolean isDiscardGlobalSharedSubscriptionLinksOnDetach(); @Override long getStoreTransactionIdleTimeoutClose(); @Override long getStoreTransactionIdleTimeoutWarn(); @Override long getStoreTransactionOpenTimeoutClose(); @Override long getStoreTransactionOpenTimeoutWarn(); @Override long getQueueCount(); @Override long getExchangeCount(); @Override long getConnectionCount(); @Override long getTotalConnectionCount(); @Override int getHousekeepingThreadCount(); @Override int getStatisticsReportingPeriod(); @Override int getConnectionThreadPoolSize(); @Override int getNumberOfSelectors(); @Override UserPreferences createUserPreferences(ConfiguredObject<?> object); @Override String getModelVersion(); @Override String getProductVersion(); @Override DurableConfigurationStore getDurableConfigurationStore(); @Override void setTargetSize(final long targetSize); @Override long getTargetSize(); @Override Principal getPrincipal(); @Override boolean registerConnection(final AMQPConnection<?> connection,
final ConnectionEstablishmentPolicy connectionEstablishmentPolicy); ListenableFuture<Boolean> registerConnectionAsync(final AMQPConnection<?> connection,
final ConnectionEstablishmentPolicy connectionEstablishmentPolicy); @Override void deregisterConnection(final AMQPConnection<?> connection); ListenableFuture<Void> deregisterConnectionAsync(final AMQPConnection<?> connection); @Override SocketConnectionMetaData getConnectionMetaData(); @Override T createMessageSource(final Class<T> clazz, final Map<String, Object> attributes); @Override T createMessageDestination(final Class<T> clazz,
final Map<String, Object> attributes); @Override boolean hasMessageSources(); @Override @DoOnConfigThread Queue<?> getSubscriptionQueue(@Param(name = "exchangeName", mandatory = true) final String exchangeName,
@Param(name = "attributes", mandatory = true) final Map<String, Object> attributes,
@Param(name = "bindings", mandatory = true) final Map<String, Map<String, Object>> bindings); @Override @DoOnConfigThread void removeSubscriptionQueue(@Param(name = "queueName", mandatory = true) final String queueName); @Override Object dumpLinkRegistry(); @Override void purgeLinkRegistry(final String containerIdPatternString, final String role, final String linkNamePatternString); @Override Cache<K, V> getNamedCache(final String cacheName); }
|
@Test public void testValidateMessageStoreCreationFails() { Map<String,Object> attributes = Collections.<String, Object>singletonMap(AbstractVirtualHost.NAME, getTestName()); AbstractVirtualHost host = new AbstractVirtualHost(attributes, _node) { @Override protected MessageStore createMessageStore() { return _failingStore; } }; try { host.validateMessageStoreCreation(); fail("Validation on creation should fail"); } catch(IllegalConfigurationException e) { assertTrue("Unexpected exception " + e.getMessage(), e.getMessage().startsWith("Cannot open virtual host message store")); } finally { host.close(); } }
|
SynchronousMessageStoreRecoverer implements MessageStoreRecoverer { @Override public ListenableFuture<Void> recover(QueueManagingVirtualHost<?> virtualHost) { EventLogger eventLogger = virtualHost.getEventLogger(); MessageStore store = virtualHost.getMessageStore(); MessageStore.MessageStoreReader storeReader = store.newMessageStoreReader(); MessageStoreLogSubject logSubject = new MessageStoreLogSubject(virtualHost.getName(), store.getClass().getSimpleName()); Map<Queue<?>, Integer> queueRecoveries = new TreeMap<>(); Map<Long, ServerMessage<?>> recoveredMessages = new HashMap<>(); Map<Long, StoredMessage<?>> unusedMessages = new TreeMap<>(); Map<UUID, Integer> unknownQueuesWithMessages = new HashMap<>(); Map<Queue<?>, Integer> queuesWithUnknownMessages = new HashMap<>(); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_START()); storeReader.visitMessages(new MessageVisitor(recoveredMessages, unusedMessages)); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_START(null, false)); try { storeReader.visitMessageInstances(new MessageInstanceVisitor(virtualHost, store, queueRecoveries, recoveredMessages, unusedMessages, unknownQueuesWithMessages, queuesWithUnknownMessages)); } finally { if (!unknownQueuesWithMessages.isEmpty()) { unknownQueuesWithMessages.forEach((queueId, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue id '{}' as a queue with this " + "id does not appear in the configuration.", count, queueId); }); } if (!queuesWithUnknownMessages.isEmpty()) { queuesWithUnknownMessages.forEach((queue, count) -> { LOGGER.info("Discarded {} entry(s) associated with queue '{}' as the referenced message " + "does not exist.", count, queue.getName()); }); } } for(Map.Entry<Queue<?>, Integer> entry : queueRecoveries.entrySet()) { Queue<?> queue = entry.getKey(); Integer deliveredCount = entry.getValue(); eventLogger.message(logSubject, TransactionLogMessages.RECOVERED(deliveredCount, queue.getName())); eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(queue.getName(), true)); queue.completeRecovery(); } for (Queue<?> q : virtualHost.getChildren(Queue.class)) { if (!queueRecoveries.containsKey(q)) { q.completeRecovery(); } } storeReader.visitDistributedTransactions(new DistributedTransactionVisitor(virtualHost, eventLogger, logSubject, recoveredMessages, unusedMessages)); for(StoredMessage<?> m : unusedMessages.values()) { LOGGER.debug("Message id '{}' is orphaned, removing", m.getMessageNumber()); m.remove(); } if (unusedMessages.size() > 0) { LOGGER.info("Discarded {} orphaned message(s).", unusedMessages.size()); } eventLogger.message(logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); eventLogger.message(logSubject, MessageStoreMessages.RECOVERED(recoveredMessages.size() - unusedMessages.size())); eventLogger.message(logSubject, MessageStoreMessages.RECOVERY_COMPLETE()); return Futures.immediateFuture(null); } @Override ListenableFuture<Void> recover(QueueManagingVirtualHost<?> virtualHost); @Override void cancel(); }
|
@SuppressWarnings("unchecked") @Test public void testRecoveryOfSingleMessageOnSingleQueue() { final Queue<?> queue = createRegisteredMockQueue(); final long messageId = 1; final StoredMessage<StorableMessageMetaData> storedMessage = createMockStoredMessage(messageId); MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { handler.handle(storedMessage); } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { handler.handle(new TestMessageEnqueueRecord(queue.getId(), messageId)); } }; when(_virtualHost.getMessageStore()).thenReturn(store); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); ServerMessage<?> message = storedMessage.getMetaData().getType().createMessage(storedMessage); verify(queue, times(1)).recover(eq(message), any(MessageEnqueueRecord.class)); }
@SuppressWarnings("unchecked") @Test public void testRecoveryOfMessageInstanceForNonExistingMessage() { final Queue<?> queue = createRegisteredMockQueue(); final long messageId = 1; final Transaction transaction = mock(Transaction.class); MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { handler.handle(new TestMessageEnqueueRecord(queue.getId(), messageId)); } @Override public Transaction newTransaction() { return transaction; } }; when(_virtualHost.getMessageStore()).thenReturn(store); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); verify(queue, never()).enqueue(any(ServerMessage.class), any(Action.class), any(MessageEnqueueRecord.class)); verify(transaction).dequeueMessage(argThat(new MessageEnqueueRecordMatcher(queue.getId(), messageId))); verify(transaction, times(1)).commitTranAsync((Void) null); }
@Test public void testRecoveryOfMessageInstanceForNonExistingQueue() { final UUID queueId = UUID.randomUUID(); final Transaction transaction = mock(Transaction.class); final long messageId = 1; final StoredMessage<StorableMessageMetaData> storedMessage = createMockStoredMessage(messageId); MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { handler.handle(storedMessage); } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { handler.handle(new TestMessageEnqueueRecord(queueId, messageId)); } @Override public Transaction newTransaction() { return transaction; } }; when(_virtualHost.getMessageStore()).thenReturn(store); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); verify(transaction).dequeueMessage(argThat(new MessageEnqueueRecordMatcher(queueId,messageId))); verify(transaction, times(1)).commitTranAsync((Void) null); }
@Test public void testRecoveryDeletesOrphanMessages() { final long messageId = 1; final StoredMessage<StorableMessageMetaData> storedMessage = createMockStoredMessage(messageId); MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { handler.handle(storedMessage); } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { } }; when(_virtualHost.getMessageStore()).thenReturn(store); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); verify(storedMessage, times(1)).remove(); }
@SuppressWarnings("unchecked") @Test public void testRecoveryOfSingleEnqueueWithDistributedTransaction() { Queue<?> queue = createRegisteredMockQueue(); final Transaction transaction = mock(Transaction.class); final StoredMessage<StorableMessageMetaData> storedMessage = createMockStoredMessage(1); long messageId = storedMessage.getMessageNumber(); EnqueueableMessage enqueueableMessage = createMockEnqueueableMessage(messageId, storedMessage); EnqueueRecord enqueueRecord = createMockRecord(queue, enqueueableMessage); final long format = 1; final byte[] globalId = new byte[] {0}; final byte[] branchId = new byte[] {0}; final EnqueueRecord[] enqueues = { enqueueRecord }; final Transaction.DequeueRecord[] dequeues = {}; MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { handler.handle(storedMessage); } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { } @Override public void visitDistributedTransactions(DistributedTransactionHandler handler) throws StoreException { handler.handle(new Transaction.StoredXidRecord() { @Override public long getFormat() { return format; } @Override public byte[] getGlobalId() { return globalId; } @Override public byte[] getBranchId() { return branchId; } }, enqueues, dequeues); } @Override public Transaction newTransaction() { return transaction; } }; DtxRegistry dtxRegistry = new DtxRegistry(_virtualHost); when(_virtualHost.getMessageStore()).thenReturn(store); when(_virtualHost.getDtxRegistry()).thenReturn(dtxRegistry); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); DtxBranch branch = dtxRegistry.getBranch(new Xid(format, globalId, branchId)); assertNotNull("Expected dtx branch to be created", branch); branch.commit(); ServerMessage<?> message = storedMessage.getMetaData().getType().createMessage(storedMessage); verify(queue, times(1)).enqueue(eq(message), isNull(), isNull()); verify(transaction).commitTran(); }
@Test public void testRecoveryOfSingleDequeueWithDistributedTransaction() { final UUID queueId = UUID.randomUUID(); final Queue<?> queue = createRegisteredMockQueue(queueId); final Transaction transaction = mock(Transaction.class); final StoredMessage<StorableMessageMetaData> storedMessage = createMockStoredMessage(1); final long messageId = storedMessage.getMessageNumber(); Transaction.DequeueRecord dequeueRecord = createMockDequeueRecord(queueId, messageId); QueueEntry queueEntry = mock(QueueEntry.class); when(queueEntry.acquire()).thenReturn(true); when(queue.getMessageOnTheQueue(messageId)).thenReturn(queueEntry); final long format = 1; final byte[] globalId = new byte[] {0}; final byte[] branchId = new byte[] {0}; final EnqueueRecord[] enqueues = {}; final Transaction.DequeueRecord[] dequeues = { dequeueRecord }; MessageStore store = new NullMessageStore() { @Override public void visitMessages(MessageHandler handler) throws StoreException { handler.handle(storedMessage); } @Override public void visitMessageInstances(MessageInstanceHandler handler) throws StoreException { handler.handle(new TestMessageEnqueueRecord(queue.getId(), messageId)); } @Override public void visitDistributedTransactions(DistributedTransactionHandler handler) throws StoreException { handler.handle(new Transaction.StoredXidRecord() { @Override public long getFormat() { return format; } @Override public byte[] getGlobalId() { return globalId; } @Override public byte[] getBranchId() { return branchId; } }, enqueues, dequeues); } @Override public Transaction newTransaction() { return transaction; } }; DtxRegistry dtxRegistry = new DtxRegistry(_virtualHost); when(_virtualHost.getMessageStore()).thenReturn(store); when(_virtualHost.getDtxRegistry()).thenReturn(dtxRegistry); SynchronousMessageStoreRecoverer recoverer = new SynchronousMessageStoreRecoverer(); recoverer.recover(_virtualHost); DtxBranch branch = dtxRegistry.getBranch(new Xid(format, globalId, branchId)); assertNotNull("Expected dtx branch to be created", branch); branch.commit(); verify(queueEntry, times(1)).delete(); verify(transaction).commitTran(); }
|
RolloverWatcher implements RollingPolicyDecorator.RolloverListener { public ZippedContent getAllFilesAsZippedContent() { Set<String> fileNames = new HashSet<>(_rolledFiles); fileNames.add(getDisplayName(_activeFilePath)); return getFilesAsZippedContent(fileNames); } RolloverWatcher(final String activeFileName); @Override void onRollover(Path baseFolder, String[] relativeFileNames); @Override void onNoRolloverDetected(final Path baseFolder, final String[] relativeFileNames); PathContent getFileContent(String fileName); Collection<String> getRolledFiles(); List<LogFileDetails> getLogFileDetails(); String getContentType(String fileName); ZippedContent getFilesAsZippedContent(Set<String> fileNames); ZippedContent getAllFilesAsZippedContent(); }
|
@Test public void testGetAllFilesAsZippedContent() throws Exception { String[] fileNames = createTestRolledFilesAndNotifyWatcher(); ZippedContent content = _rolloverWatcher.getAllFilesAsZippedContent(); assertZippedContent(fileNames, content); }
|
HouseKeepingTask implements Runnable { @Override final public void run() { String originalThreadName = Thread.currentThread().getName(); Thread.currentThread().setName(_name); try { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { try { execute(); } catch (ConnectionScopedRuntimeException e) { LOGGER.warn("Execution of housekeeping task failed", e); } return null; } }, _accessControlContext); } finally { Thread.currentThread().setName(originalThreadName); } } HouseKeepingTask(String name, VirtualHost vhost, AccessControlContext context); @Override final void run(); abstract void execute(); synchronized void cancel(); }
|
@Test public void runExecuteThrowsConnectionScopeRuntimeException() { final VirtualHost virualHost = mock(VirtualHost.class); final AccessControlContext context = AccessController.getContext(); final HouseKeepingTask task = new HouseKeepingTask(getTestName(), virualHost, context) { @Override public void execute() { throw new ConnectionScopedRuntimeException("Test"); } }; task.run(); }
|
VirtualHostPropertiesNode extends AbstractSystemMessageSource { @Override public <T extends ConsumerTarget<T>> Consumer<T> addConsumer(final T target, final FilterManager filters, final Class<? extends ServerMessage> messageClass, final String consumerName, final EnumSet<ConsumerOption> options, final Integer priority) throws ExistingExclusiveConsumer, ExistingConsumerPreventsExclusive, ConsumerAccessRefused, QueueDeleted { final Consumer<T> consumer = super.addConsumer(target, filters, messageClass, consumerName, options, priority); consumer.send(createMessage()); target.noMessagesAvailable(); return consumer; } VirtualHostPropertiesNode(final NamedAddressSpace virtualHost); VirtualHostPropertiesNode(final NamedAddressSpace virtualHost, String name); @Override Consumer<T> addConsumer(final T target,
final FilterManager filters,
final Class<? extends ServerMessage> messageClass,
final String consumerName,
final EnumSet<ConsumerOption> options, final Integer priority); @Override void close(); }
|
@Test public void testAddConsumer() throws Exception { final EnumSet<ConsumerOption> options = EnumSet.noneOf(ConsumerOption.class); final ConsumerTarget target = mock(ConsumerTarget.class); when(target.allocateCredit(any(ServerMessage.class))).thenReturn(true); MessageInstanceConsumer consumer = _virtualHostPropertiesNode.addConsumer(target, null, ServerMessage.class, getTestName(), options, 0); final MessageContainer messageContainer = consumer.pullMessage(); assertNotNull("Could not pull message from VirtualHostPropertyNode", messageContainer); if (messageContainer.getMessageReference() != null) { messageContainer.getMessageReference().release(); } }
|
BrokerStoreUpgraderAndRecoverer extends AbstractConfigurationStoreUpgraderAndRecoverer implements ContainerStoreUpgraderAndRecoverer<Broker> { public List<ConfiguredObjectRecord> upgrade(final DurableConfigurationStore dcs, final List<ConfiguredObjectRecord> records) { return upgrade(dcs, records, Broker.class.getSimpleName(), Broker.MODEL_VERSION); } BrokerStoreUpgraderAndRecoverer(SystemConfig<?> systemConfig); @Override Broker<?> upgradeAndRecover(List<ConfiguredObjectRecord> records); List<ConfiguredObjectRecord> upgrade(final DurableConfigurationStore dcs,
final List<ConfiguredObjectRecord> records); static final String VIRTUALHOSTS; }
|
@Test public void testUpgradeVirtualHostWithJDBCStoreAndBoneCPPool() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("connectionPool", "BONECP"); hostAttributes.put("connectionURL", "jdbc:derby: hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("maxConnectionsPerPartition", 7); hostAttributes.put("minConnectionsPerPartition", 6); hostAttributes.put("partitionCount", 2); hostAttributes.put("storeType", "jdbc"); hostAttributes.put("type", "STANDARD"); hostAttributes.put("jdbcBigIntType", "mybigint"); hostAttributes.put("jdbcBlobType", "myblob"); hostAttributes.put("jdbcVarbinaryType", "myvarbinary"); hostAttributes.put("jdbcBytesForBlob", true); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("connectionPoolType", "BONECP"); expectedAttributes.put("connectionUrl", "jdbc:derby: expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("name", VIRTUALHOST_NAME); expectedAttributes.put("type", "JDBC"); expectedAttributes.put("defaultVirtualHostNode", "true"); final Map<String, Object> context = new HashMap<>(); context.put("qpid.jdbcstore.bigIntType", "mybigint"); context.put("qpid.jdbcstore.varBinaryType", "myvarbinary"); context.put("qpid.jdbcstore.blobType", "myblob"); context.put("qpid.jdbcstore.useBytesForBlob", true); context.put("qpid.jdbcstore.bonecp.maxConnectionsPerPartition", 7); context.put("qpid.jdbcstore.bonecp.minConnectionsPerPartition", 6); context.put("qpid.jdbcstore.bonecp.partitionCount", 2); expectedAttributes.put("context", context); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeVirtualHostWithJDBCStoreAndDefaultPool() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("connectionPool", "DEFAULT"); hostAttributes.put("connectionURL", "jdbc:derby: hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("storeType", "jdbc"); hostAttributes.put("type", "STANDARD"); hostAttributes.put("jdbcBigIntType", "mybigint"); hostAttributes.put("jdbcBlobType", "myblob"); hostAttributes.put("jdbcVarbinaryType", "myvarbinary"); hostAttributes.put("jdbcBytesForBlob", true); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("connectionPoolType", "NONE"); expectedAttributes.put("connectionUrl", "jdbc:derby: expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("name", VIRTUALHOST_NAME); expectedAttributes.put("type", "JDBC"); expectedAttributes.put("defaultVirtualHostNode", "true"); final Map<String, Object> context = new HashMap<>(); context.put("qpid.jdbcstore.bigIntType", "mybigint"); context.put("qpid.jdbcstore.varBinaryType", "myvarbinary"); context.put("qpid.jdbcstore.blobType", "myblob"); context.put("qpid.jdbcstore.useBytesForBlob", true); expectedAttributes.put("context", context); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeVirtualHostWithDerbyStore() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("storePath", "/tmp/vh/derby"); hostAttributes.put("storeType", "derby"); hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("type", "STANDARD"); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("storePath", "/tmp/vh/derby"); expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("name", VIRTUALHOST_NAME); expectedAttributes.put("type", "DERBY"); expectedAttributes.put("defaultVirtualHostNode", "true"); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeVirtualHostWithBDBStore() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("storePath", "/tmp/vh/bdb"); hostAttributes.put("storeType", "bdb"); hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("type", "STANDARD"); hostAttributes.put("bdbEnvironmentConfig", Collections.singletonMap("je.stats.collect", "false")); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("storePath", "/tmp/vh/bdb"); expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("name", VIRTUALHOST_NAME); expectedAttributes.put("type", "BDB"); expectedAttributes.put("defaultVirtualHostNode", "true"); expectedAttributes.put("context", Collections.singletonMap("je.stats.collect", "false")); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeVirtualHostWithBDBHAStore() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("type", "BDB_HA"); hostAttributes.put("storePath", "/tmp/vh/bdbha"); hostAttributes.put("haCoalescingSync", "true"); hostAttributes.put("haDesignatedPrimary", "true"); hostAttributes.put("haGroupName", "ha"); hostAttributes.put("haHelperAddress", "localhost:7000"); hostAttributes.put("haNodeAddress", "localhost:7000"); hostAttributes.put("haNodeName", "n1"); hostAttributes.put("haReplicationConfig", Collections.singletonMap("je.stats.collect", "false")); hostAttributes.put("bdbEnvironmentConfig", Collections.singletonMap("je.rep.feederTimeout", "1 m")); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedContext = new HashMap<>(); expectedContext.put("je.stats.collect", "false"); expectedContext.put("je.rep.feederTimeout", "1 m"); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("type", "BDB_HA"); expectedAttributes.put("storePath", "/tmp/vh/bdbha"); expectedAttributes.put("designatedPrimary", "true"); expectedAttributes.put("groupName", "ha"); expectedAttributes.put("address", "localhost:7000"); expectedAttributes.put("helperAddress", "localhost:7000"); expectedAttributes.put("name", "n1"); expectedAttributes.put("context", expectedContext); expectedAttributes.put("defaultVirtualHostNode", "true"); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeVirtualHostWithMemoryStore() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", VIRTUALHOST_NAME); hostAttributes.put("modelVersion", "0.4"); hostAttributes.put("storeType", "memory"); hostAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); hostAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); hostAttributes.put("type", "STANDARD"); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); assertEquals("Unexpected type", "VirtualHostNode", upgradedVirtualHostNodeRecord.getType()); Map<String,Object> expectedAttributes = new HashMap<>(); expectedAttributes.put("createdBy", VIRTUALHOST_CREATED_BY); expectedAttributes.put("createdTime", VIRTUALHOST_CREATE_TIME); expectedAttributes.put("name", VIRTUALHOST_NAME); expectedAttributes.put("type", "Memory"); expectedAttributes.put("defaultVirtualHostNode", "true"); assertEquals("Unexpected attributes", expectedAttributes, upgradedVirtualHostNodeRecord.getAttributes()); assertBrokerRecord(records); }
@Test public void testUpgradeNonAMQPPort() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", "nonAMQPPort"); hostAttributes.put("type", "HTTP"); _brokerRecord.getAttributes().put("modelVersion", "2.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); assertTrue("No virtualhostalias rescords should be returned", findRecordByType("VirtualHostAlias", records).isEmpty()); }
@Test public void testUpgradeImpliedAMQPPort() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", "impliedPort"); _brokerRecord.getAttributes().put("modelVersion", "2.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); assertFalse("VirtualHostAlias rescords should be returned", findRecordByType("VirtualHostAlias", records).isEmpty()); }
@Test public void testUpgradeImpliedNonAMQPPort() { Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put("name", "nonAMQPPort"); hostAttributes.put("protocols", "HTTP"); _brokerRecord.getAttributes().put("modelVersion", "2.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); assertTrue("No virtualhostalias rescords should be returned", findRecordByType("VirtualHostAlias", records).isEmpty()); }
@Test public void testUpgradeBrokerType() { _brokerRecord.getAttributes().put("modelVersion", "3.0"); _brokerRecord.getAttributes().put("type", "broker"); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> brokerRecords = findRecordByType("Broker", records); assertEquals("Unexpected number of broker records", (long) 1, (long) brokerRecords.size()); assertFalse("Unexpected type", brokerRecords.get(0).getAttributes().containsKey("type")); }
@Test public void testUpgradeAMQPPortWithNetworkBuffers() { Map<String, Object> portAttributes = new HashMap<>(); portAttributes.put("name", getTestName()); portAttributes.put("type", "AMQP"); portAttributes.put("receiveBufferSize", "1"); portAttributes.put("sendBufferSize", "2"); _brokerRecord.getAttributes().put("modelVersion", "3.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", portAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> ports = findRecordByType("Port", records); assertEquals("Unexpected port size", (long) 1, (long) ports.size()); ConfiguredObjectRecord upgradedRecord = ports.get(0); Map<String, Object> attributes = upgradedRecord.getAttributes(); assertFalse("receiveBufferSize is found " + attributes.get("receiveBufferSize"), attributes.containsKey("receiveBufferSize")); assertFalse("sendBufferSize is found " + attributes.get("sendBufferSize"), attributes.containsKey("sendBufferSize")); assertEquals("Unexpected name", getTestName(), attributes.get("name")); }
@Test public void testUpgradeRemoveJmxPlugin() { Map<String, Object> jmxPlugin = new HashMap<>(); jmxPlugin.put("name", getTestName()); jmxPlugin.put("type", "MANAGEMENT-JMX"); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Plugin", jmxPlugin, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> plugins = findRecordByType("Plugin", records); assertTrue("JMX Plugin was not removed", plugins.isEmpty()); }
@Test public void testUpgradeRemoveJmxPortByType() { Map<String, Object> jmxPort = new HashMap<>(); jmxPort.put("name", "jmx1"); jmxPort.put("type", "JMX"); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", jmxPort, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> ports = findRecordByType("Port", records); assertTrue("Port was not removed", ports.isEmpty()); }
@Test public void testUpgradeRemoveRmiPortByType() { Map<String, Object> rmiPort = new HashMap<>(); rmiPort.put("name", "rmi1"); rmiPort.put("type", "RMI"); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", rmiPort, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> ports = findRecordByType("Port", records); assertTrue("Port was not removed", ports.isEmpty()); }
@Test public void testUpgradeRemoveJmxPortByProtocol() { Map<String, Object> jmxPort = new HashMap<>(); jmxPort.put("name", "jmx2"); jmxPort.put("protocols", Collections.singleton("JMX_RMI")); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", jmxPort, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> ports = findRecordByType("Port", records); assertTrue("Port was not removed", ports.isEmpty()); }
@Test public void testUpgradeRemoveRmiPortByProtocol() { Map<String, Object> rmiPort2 = new HashMap<>(); rmiPort2.put("name", "rmi2"); rmiPort2.put("protocols", Collections.singleton("RMI")); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord portRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", rmiPort2, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, portRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> ports = findRecordByType("Port", records); assertTrue("Port was not removed", ports.isEmpty()); }
@Test public void testUpgradeRemovePreferencesProviderNonJsonLikeStore() { _brokerRecord.getAttributes().put("modelVersion", "6.0"); Map<String, Object> authenticationProvider = new HashMap<>(); authenticationProvider.put("name", "anonymous"); authenticationProvider.put("type", "Anonymous"); ConfiguredObjectRecord authenticationProviderRecord = new ConfiguredObjectRecordImpl( UUID.randomUUID(), "AuthenticationProvider", authenticationProvider, Collections.singletonMap("Broker", _brokerRecord.getId())); ConfiguredObjectRecord preferencesProviderRecord = new ConfiguredObjectRecordImpl( UUID.randomUUID(), "PreferencesProvider", Collections.<String, Object>emptyMap(), Collections.singletonMap("AuthenticationProvider", authenticationProviderRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, authenticationProviderRecord, preferencesProviderRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> preferencesProviders = findRecordByType("PreferencesProvider", records); assertTrue("PreferencesProvider was not removed", preferencesProviders.isEmpty()); List<ConfiguredObjectRecord> authenticationProviders = findRecordByType("AuthenticationProvider", records); assertEquals("AuthenticationProvider was removed", (long) 1, (long) authenticationProviders.size()); }
@Test public void testUpgradeRemovePreferencesProviderJsonLikeStore() { _brokerRecord.getAttributes().put("modelVersion", "6.0"); Map<String, Object> authenticationProvider = new HashMap<>(); authenticationProvider.put("name", "anonymous"); authenticationProvider.put("type", "Anonymous"); authenticationProvider.put("preferencesproviders", Collections.emptyMap()); ConfiguredObjectRecord authenticationProviderRecord = new ConfiguredObjectRecordImpl( UUID.randomUUID(), "AuthenticationProvider", authenticationProvider, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, authenticationProviderRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); List<ConfiguredObjectRecord> authenticationProviders = findRecordByType("AuthenticationProvider", records); assertEquals("AuthenticationProviders was removed", (long) 1, (long) authenticationProviders.size()); assertFalse("PreferencesProvider was not removed", authenticationProviders.get(0).getAttributes().containsKey("preferencesproviders")); }
@Test public void testUpgradeTrustStoreRecordsFrom_6_0() throws Exception { _brokerRecord.getAttributes().put("modelVersion", "6.0"); Map<String, UUID> parents = Collections.singletonMap("Broker", _brokerRecord.getId()); Map<String, Object> trustStoreAttributes1 = new HashMap<>(); trustStoreAttributes1.put("name", "truststore1"); trustStoreAttributes1.put("type", "FileTrustStore"); trustStoreAttributes1.put("path", "${json:test.ssl.resources}/java_broker_truststore1.jks"); trustStoreAttributes1.put("password", "password"); ConfiguredObjectRecord trustStore1 = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "TrustStore", trustStoreAttributes1, parents); Map<String, Object> trustStoreAttributes2 = new HashMap<>(); trustStoreAttributes2.put("name", "truststore2"); trustStoreAttributes2.put("type", "FileTrustStore"); trustStoreAttributes2.put("path", "${json:test.ssl.resources}/java_broker_truststore2.jks"); trustStoreAttributes2.put("password", "password"); trustStoreAttributes2.put("includedVirtualHostMessageSources", "true"); ConfiguredObjectRecord trustStore2 = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "TrustStore", trustStoreAttributes2, parents); Map<String, Object> trustStoreAttributes3 = new HashMap<>(); trustStoreAttributes3.put("name", "truststore3"); trustStoreAttributes3.put("type", "FileTrustStore"); trustStoreAttributes3.put("path", "${json:test.ssl.resources}/java_broker_truststore3.jks"); trustStoreAttributes3.put("password", "password"); trustStoreAttributes3.put("excludedVirtualHostMessageSources", "true"); ConfiguredObjectRecord trustStore3 = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "TrustStore", trustStoreAttributes3, parents); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, trustStore1, trustStore2, trustStore3); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord trustStore1Upgraded = findRecordById(trustStore1.getId(), records); ConfiguredObjectRecord trustStore2Upgraded = findRecordById(trustStore2.getId(), records); ConfiguredObjectRecord trustStore3Upgraded = findRecordById(trustStore3.getId(), records); assertNotNull("Trust store 1 is not found after upgrade", trustStore1Upgraded); assertNotNull("Trust store 2 is not found after upgrade", trustStore2Upgraded); assertNotNull("Trust store 3 is not found after upgrade", trustStore3Upgraded); assertEquals("Unexpected attributes after upgrade for Trust store 1", trustStoreAttributes1, new HashMap<>(trustStore1Upgraded.getAttributes())); assertEquals("includedVirtualHostNodeMessageSources is not found", "true", trustStore2Upgraded.getAttributes().get("includedVirtualHostNodeMessageSources")); assertNull("includedVirtualHostMessageSources is found", trustStore2Upgraded.getAttributes().get("includedVirtualHostMessageSources")); assertEquals("includedVirtualHostNodeMessageSources is not found", "true", trustStore3Upgraded.getAttributes().get("excludedVirtualHostNodeMessageSources")); assertNull("includedVirtualHostMessageSources is found", trustStore3Upgraded.getAttributes().get("excludedVirtualHostMessageSources")); assertModelVersionUpgraded(records); }
@Test public void testUpgradeJmxRecordsFrom_3_0() throws Exception { _brokerRecord.getAttributes().put("modelVersion", "3.0"); Map<String, UUID> parents = Collections.singletonMap("Broker", _brokerRecord.getId()); Map<String, Object> jmxPortAttributes = new HashMap<>(); jmxPortAttributes.put("name", "jmx1"); jmxPortAttributes.put("type", "JMX"); ConfiguredObjectRecord jmxPort = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", jmxPortAttributes, parents); Map<String, Object> rmiPortAttributes = new HashMap<>(); rmiPortAttributes.put("name", "rmi1"); rmiPortAttributes.put("type", "RMI"); ConfiguredObjectRecord rmiPort = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", rmiPortAttributes, parents); Map<String, Object> jmxPluginAttributes = new HashMap<>(); jmxPluginAttributes.put("name", getTestName()); jmxPluginAttributes.put("type", "MANAGEMENT-JMX"); _brokerRecord.getAttributes().put("modelVersion", "6.0"); ConfiguredObjectRecord jmxManagement = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Plugin", jmxPluginAttributes, parents); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, jmxPort, rmiPort, jmxManagement); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); assertNull("Jmx port is not removed", findRecordById(jmxPort.getId(), records)); assertNull("Rmi port is not removed", findRecordById(rmiPort.getId(), records)); assertNull("Jmx plugin is not removed", findRecordById(jmxManagement.getId(), records)); assertModelVersionUpgraded(records); }
@Test public void testUpgradeHttpPortFrom_6_0() throws Exception { _brokerRecord.getAttributes().put("modelVersion", "6.0"); Map<String, UUID> parents = Collections.singletonMap("Broker", _brokerRecord.getId()); Map<String, Object> httpPortAttributes = new HashMap<>(); httpPortAttributes.put("name", "http"); httpPortAttributes.put("protocols", Collections.singletonList("HTTP")); final Map<String, String > context = new HashMap<>(); httpPortAttributes.put("context", context); context.put("port.http.additionalInternalThreads", "6"); context.put("port.http.maximumQueuedRequests", "1000"); ConfiguredObjectRecord httpPort = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Port", httpPortAttributes, parents); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, httpPort); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedPort = findRecordById(httpPort.getId(), records); assertNotNull("Http port is not found", upgradedPort); Map<String, Object> upgradedAttributes = upgradedPort.getAttributes(); Map<String, String> upgradedContext = (Map<String, String>) upgradedAttributes.get("context"); assertFalse("Context variable \"port.http.additionalInternalThreads\" is not removed", upgradedContext.containsKey("port.http.additionalInternalThreads")); assertFalse("Context variable \"port.http.maximumQueuedRequests\" is not removed", upgradedContext.containsKey("port.http.maximumQueuedRequests")); assertEquals("Context variable \"port.http.maximumQueuedRequests\" is not renamed", "1000", upgradedContext.get("qpid.port.http.acceptBacklog")); }
@Test public void testBrokerConnectionAttributesRemoval() throws Exception { _brokerRecord.getAttributes().put("modelVersion", "6.1"); _brokerRecord.getAttributes().put("connection.sessionCountLimit", "512"); _brokerRecord.getAttributes().put("connection.heartBeatDelay", "300"); _brokerRecord.getAttributes().put("connection.closeWhenNoRoute", "false"); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord); BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); ConfiguredObjectRecord upgradedBroker = findRecordById(_brokerRecord.getId(), records); assertNotNull("Upgraded broker record is not found", upgradedBroker); Map<String, Object> upgradedAttributes = upgradedBroker.getAttributes(); final Map<String, String> expectedContext = new HashMap<>(); expectedContext.put("qpid.port.sessionCountLimit", "512"); expectedContext.put("qpid.port.heartbeatDelay", "300"); expectedContext.put("qpid.port.closeWhenNoRoute", "false"); Object upgradedContext = upgradedAttributes.get("context"); final boolean condition = upgradedContext instanceof Map; assertTrue("Unpexcted context", condition); assertEquals("Unexpected context", expectedContext, new HashMap<>(((Map<String, String>) upgradedContext))); assertFalse("Session count limit is not removed", upgradedAttributes.containsKey("connection.sessionCountLimit")); assertFalse("Heart beat delay is not removed", upgradedAttributes.containsKey("connection.heartBeatDelay")); assertFalse("Close when no route is not removed", upgradedAttributes.containsKey("conection.closeWhenNoRoute")); }
@Test public void testContextVariableUpgradeForTLSProtocolsSetOnBroker() { final Map<String, String> context = new HashMap<>(); context.put("qpid.security.tls.protocolWhiteList", ".*"); context.put("qpid.security.tls.protocolBlackList", "Ssl.*"); _brokerRecord.getAttributes().put("modelVersion", "8.0"); _brokerRecord.getAttributes().put("context", context); final DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord); final BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); final List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); final Map<String, String> contextMap = findCategoryRecordAndGetContext("Broker", records); assertEquals(".*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_PROTOCOL_ALLOW_LIST)); assertEquals("Ssl.*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_PROTOCOL_DENY_LIST)); }
@Test public void testContextVariableUpgradeForTLSCipherSuitesSetOnBroker() { final Map<String, String> context = new HashMap<>(); context.put("qpid.security.tls.cipherSuiteWhiteList", ".*"); context.put("qpid.security.tls.cipherSuiteBlackList", "Ssl.*"); _brokerRecord.getAttributes().put("modelVersion", "8.0"); _brokerRecord.getAttributes().put("context", context); final DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord); final BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); final List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); final Map<String, String> contextMap = findCategoryRecordAndGetContext("Broker", records); assertEquals(".*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_ALLOW_LIST)); assertEquals("Ssl.*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_DENY_LIST)); }
@Test public void testContextVariableUpgradeForTLSProtocolsSetOnPort() { _brokerRecord.getAttributes().put("modelVersion", "8.0"); final Map<String, String> context = new HashMap<>(); context.put("qpid.security.tls.protocolWhiteList", ".*"); context.put("qpid.security.tls.protocolBlackList", "Ssl.*"); final ConfiguredObjectRecord portRecord = createMockRecordForGivenCategoryTypeAndContext("Port", "AMQP", context); final DurableConfigurationStore dcs = new DurableConfigurationStoreStub(portRecord, _brokerRecord); final BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); final List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); final Map<String, String> contextMap = findCategoryRecordAndGetContext("Port", records); assertEquals(".*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_PROTOCOL_ALLOW_LIST)); assertEquals("Ssl.*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_PROTOCOL_DENY_LIST)); }
@Test public void testContextVariableUpgradeForTLSCipherSuitesSetOnAuthenticationProvider() { _brokerRecord.getAttributes().put("modelVersion", "8.0"); final Map<String, String> context = new HashMap<>(); context.put("qpid.security.tls.cipherSuiteWhiteList", ".*"); context.put("qpid.security.tls.cipherSuiteBlackList", "Ssl.*"); final ConfiguredObjectRecord authenticationProviderRecord = createMockRecordForGivenCategoryTypeAndContext("AuthenticationProvider", "OAuth2", context); final DurableConfigurationStore dcs = new DurableConfigurationStoreStub(authenticationProviderRecord, _brokerRecord); final BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); final List<ConfiguredObjectRecord> records = upgrade(dcs, recoverer); final Map<String, String> contextMap = findCategoryRecordAndGetContext("AuthenticationProvider", records); assertEquals(".*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_ALLOW_LIST)); assertEquals("Ssl.*", contextMap.get(CommonProperties.QPID_SECURITY_TLS_CIPHER_SUITE_DENY_LIST)); }
|
PrincipalLogEventFilter extends Filter<ILoggingEvent> implements LogBackLogInclusionRule { @Override public FilterReply decide(ILoggingEvent event) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject != null && subject.getPrincipals().contains(_principal)) { return FilterReply.NEUTRAL; } return FilterReply.DENY; } PrincipalLogEventFilter(final Principal principal); @Override FilterReply decide(ILoggingEvent event); @Override Filter<ILoggingEvent> asFilter(); @Override String getName(); }
|
@Test public void testNoSubject() { _subject.getPrincipals().add(mock(Principal.class)); assertEquals(FilterReply.DENY, _principalLogEventFilter.decide(_event)); }
|
BrokerLoggerStatusListener implements StatusListener { @Override public void addStatusEvent(Status status) { Throwable throwable = status.getThrowable(); if (status.getEffectiveLevel() == Status.ERROR && _errorClasses.stream().anyMatch(c -> c.isInstance(throwable))) { LOGGER.error("Unexpected error whilst trying to store log entry. Log messages could be lost.", throwable); if (_brokerLogger.getContextValue(Boolean.class, _contextFlag)) { try { _brokerLogger.stopLogging(); _systemConfig.getEventLogger().message(BrokerMessages.FATAL_ERROR( String.format( "Shutting down the broker because context variable '%s' is set and unexpected logging issue occurred: %s", _contextFlag, throwable.getMessage()))); } finally { _systemConfig.closeAsync(); } } } } BrokerLoggerStatusListener(final BrokerLogger<?> brokerLogger,
final SystemConfig<?> systemConfig,
final String contextFlag,
final Class<?>... errorClass); @Override void addStatusEvent(Status status); }
|
@Test public void testAddStatusEventForIOError() { Status event = createEvent(new IOError(new IOException("Mocked: No disk space left")), Status.ERROR); _statusListener.addStatusEvent(event); verify(_systemConfig).closeAsync(); }
@Test public void testAddStatusEventForIOErrorWithFailOnLoggerIOErrorDisabled() { Status event = createEvent(new IOError(new IOException("Mocked: No disk space left")), Status.ERROR); when(_fileLogger.getContextValue(Boolean.class, BrokerFileLogger.BROKER_FAIL_ON_LOGGER_IO_ERROR)).thenReturn(false); _statusListener.addStatusEvent(event); verify(_systemConfig, never()).closeAsync(); }
@Test public void testAddStatusEventForIOException() { Status event = createEvent(new IOException("Mocked: No disk space left"), Status.ERROR); _statusListener.addStatusEvent(event); verify(_systemConfig).closeAsync(); }
@Test public void testAddStatusEventForIOExceptionReportedAsWarning() { Status event = createEvent(new IOException("Mocked: No disk space left"), Status.WARN); _statusListener.addStatusEvent(event); verify(_systemConfig, never()).closeAsync(); }
@Test public void testAddStatusEventForNonIOException() { Status event = createEvent(new RuntimeException("Mocked: No disk space left"), Status.ERROR); _statusListener.addStatusEvent(event); verify(_systemConfig, never()).closeAsync(); }
|
AbstractConfigurationStoreUpgraderAndRecoverer { void register(StoreUpgraderPhase upgrader) { final String fromVersion = upgrader.getFromVersion(); final String toVersion = upgrader.getToVersion(); if (_upgraders.containsKey(fromVersion)) { throw new IllegalStateException(String.format( "Error in store upgrader chain. More than on upgrader from version %s", fromVersion)); } if (fromVersion.equals(toVersion)) { throw new IllegalStateException(String.format( "Error in store upgrader chain. From version %s cannot be equal to toVersion %s", fromVersion, toVersion)); } if (!fromVersion.equals(_initialVersion)) { boolean found = false; for (StoreUpgraderPhase storeUpgraderPhase : _upgraders.values()) { if (storeUpgraderPhase.getToVersion().equals(fromVersion)) { found = true; break; } } if (!found) { throw new IllegalStateException(String.format( "Error in store upgrader chain." + "No previously defined upgrader to version %s found when registering upgrader from %s to %s", fromVersion, fromVersion, toVersion)); } } _upgraders.put(fromVersion, upgrader); } AbstractConfigurationStoreUpgraderAndRecoverer(final String initialVersion); }
|
@Test public void testRegister() { _recoverer.register(new TestStoreUpgraderPhase("0.0", "1.0")); _recoverer.register(new TestStoreUpgraderPhase("1.0", "1.1")); _recoverer.register(new TestStoreUpgraderPhase("1.1", "2.0")); }
@Test public void testRegisterFailsOnUnknownFromVersion() { _recoverer.register(new TestStoreUpgraderPhase("0.0", "1.0")); try { _recoverer.register(new TestStoreUpgraderPhase("1.1", "2.0")); fail("should fail"); } catch (IllegalStateException e) { } }
@Test public void testRegisterFailsOnNoVersionNumberChange() { _recoverer.register(new TestStoreUpgraderPhase("0.0", "1.0")); try { _recoverer.register(new TestStoreUpgraderPhase("1.0", "1.0")); fail("should fail"); } catch (IllegalStateException e) { } }
@Test public void testRegisterFailsOnDuplicateFromVersion() { _recoverer.register(new TestStoreUpgraderPhase("0.0", "1.0")); try { _recoverer.register(new TestStoreUpgraderPhase("0.0", "2.0")); fail("should fail"); } catch (IllegalStateException e) { } }
@Test public void testRegisterFailsOnUnexpectedFromVersionInFirstUpgrader() { try { _recoverer.register(new TestStoreUpgraderPhase("0.1", "1.0")); fail("should fail"); } catch (IllegalStateException e) { } }
|
JsonFileConfigStore extends AbstractJsonFileStore implements DurableConfigurationStore { @Override public void init(ConfiguredObject<?> parent) { assertState(State.CLOSED); _parent = parent; _classNameMapping = generateClassNameMap(_parent.getModel(), _rootClass); FileBasedSettings fileBasedSettings = (FileBasedSettings) _parent; setup(parent.getName(), fileBasedSettings.getStorePath(), parent.getContextValue(String.class, SystemConfig.POSIX_FILE_PERMISSIONS), Collections.emptyMap()); changeState(State.CLOSED, State.CONFIGURED); } JsonFileConfigStore(Class<? extends ConfiguredObject> rootClass); @Override void upgradeStoreStructure(); @Override void init(ConfiguredObject<?> parent); @Override boolean openConfigurationStore(ConfiguredObjectRecordHandler handler,
final ConfiguredObjectRecord... initialRecords); @Override void reload(ConfiguredObjectRecordHandler handler); @Override synchronized void create(ConfiguredObjectRecord record); @Override synchronized UUID[] remove(final ConfiguredObjectRecord... objects); @Override synchronized void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records); @Override void closeConfigurationStore(); @Override void onDelete(ConfiguredObject<?> parent); }
|
@Test public void testNoStorePath() throws Exception { when(_parent.getStorePath()).thenReturn(null); try { _store.init(_parent); fail("Store should not successfully configure if there is no path set"); } catch (ServerScopedRuntimeException e) { } }
@Test public void testInvalidStorePath() throws Exception { String unwritablePath = System.getProperty("file.separator"); assumeThat(new File(unwritablePath).canWrite(), is(equalTo(false))); when(_parent.getStorePath()).thenReturn(unwritablePath); try { _store.init(_parent); fail("Store should not successfully configure if there is an invalid path set"); } catch (ServerScopedRuntimeException e) { } }
|
PreferencesRecoverer { public void recoverPreferences(ConfiguredObject<?> parent, Collection<PreferenceRecord> preferenceRecords, PreferenceStore preferencesStore) { Set<UUID> corruptedRecords = new HashSet<>(); Map<UUID, Collection<PreferenceRecord>> objectToRecordMap = new HashMap<>(); for (PreferenceRecord preferenceRecord : preferenceRecords) { UUID associatedObjectId = getAssociatedObjectId(preferenceRecord.getAttributes()); if (associatedObjectId == null) { LOGGER.info("Could not find associated object for preference : {}", preferenceRecord.getId()); corruptedRecords.add(preferenceRecord.getId()); } else { Collection<PreferenceRecord> objectPreferences = objectToRecordMap.get(associatedObjectId); if (objectPreferences == null) { objectPreferences = new HashSet<>(); objectToRecordMap.put(associatedObjectId, objectPreferences); } objectPreferences.add(preferenceRecord); } } setUserPreferences(parent, objectToRecordMap, preferencesStore, corruptedRecords); if (!objectToRecordMap.isEmpty()) { LOGGER.warn("Could not recover preferences associated with: {}", objectToRecordMap.keySet()); for (Collection<PreferenceRecord> records: objectToRecordMap.values()) { for (PreferenceRecord record : records) { corruptedRecords.add(record.getId()); } } } if (!corruptedRecords.isEmpty()) { LOGGER.warn("Removing unrecoverable corrupted preferences: {}", corruptedRecords); preferencesStore.replace(corruptedRecords, Collections.<PreferenceRecord>emptySet()); } } PreferencesRecoverer(final TaskExecutor executor); void recoverPreferences(ConfiguredObject<?> parent,
Collection<PreferenceRecord> preferenceRecords,
PreferenceStore preferencesStore); }
|
@Test public void testRecoverEmptyPreferences() throws Exception { _recoverer.recoverPreferences(_testObject, Collections.<PreferenceRecord>emptyList(), _store); assertNotNull("Object should have UserPreferences", _testObject.getUserPreferences()); assertNotNull("Child object should have UserPreferences", _testChildObject.getUserPreferences()); }
@Test public void testRecoverPreferences() throws Exception { final UUID p1Id = UUID.randomUUID(); Map<String, Object> pref1Attributes = PreferenceTestHelper.createPreferenceAttributes( _testObject.getId(), p1Id, "X-testType", "testPref1", null, TestPrincipalUtils.getTestPrincipalSerialization(TEST_USERNAME), null, Collections.<String, Object>emptyMap()); PreferenceRecord record1 = new PreferenceRecordImpl(p1Id, pref1Attributes); final UUID p2Id = UUID.randomUUID(); Map<String, Object> pref2Attributes = PreferenceTestHelper.createPreferenceAttributes( _testChildObject.getId(), p2Id, "X-testType", "testPref2", null, TestPrincipalUtils.getTestPrincipalSerialization(TEST_USERNAME), null, Collections.<String, Object>emptyMap()); PreferenceRecord record2 = new PreferenceRecordImpl(p2Id, pref2Attributes); _recoverer.recoverPreferences(_testObject, Arrays.asList(record1, record2), _store); Subject.doAs(_testSubject, new PrivilegedAction<Void>() { @Override public Void run() { Set<Preference> preferences = awaitPreferenceFuture(_testObject.getUserPreferences().getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) preferences.size()); Set<Preference> childPreferences = awaitPreferenceFuture(_testChildObject.getUserPreferences().getPreferences()); assertEquals("Unexpected number of preferences", (long) 1, (long) childPreferences.size()); return null; } }); }
|
JsonFilePreferenceStore extends AbstractJsonFileStore implements PreferenceStore { @Override public synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater) throws StoreException { if (_storeState != StoreState.CLOSED) { throw new IllegalStateException(String.format("PreferenceStore cannot be opened when in state '%s'", _storeState)); } try { setup(DEFAULT_FILE_NAME, _storePath, _posixFilePermissions, Collections.singletonMap("version", BrokerModel.MODEL_VERSION)); StoreContent storeContent; try { storeContent = _objectMapper.readValue(getConfigFile(), StoreContent.class); } catch (IOException e) { throw new StoreException("Failed to read preferences from store", e); } ModelVersion storedVersion = ModelVersion.fromString(storeContent.getVersion()); ModelVersion currentVersion = new ModelVersion(BrokerModel.MODEL_MAJOR_VERSION, BrokerModel.MODEL_MINOR_VERSION); if (currentVersion.lessThan(storedVersion)) { throw new IllegalStateException(String.format( "Cannot downgrade preference store storedVersion from '%s' to '%s'", currentVersion.toString(), BrokerModel.MODEL_VERSION)); } Collection<PreferenceRecord> records = Arrays.<PreferenceRecord>asList(storeContent.getPreferences()); if (storedVersion.lessThan(currentVersion)) { records = updater.updatePreferences(storedVersion.toString(), records); storeContent.setVersion(BrokerModel.MODEL_VERSION); storeContent.setPreferences(records.toArray(new StoredPreferenceRecord[records.size()])); save(storeContent); } for (StoredPreferenceRecord preferenceRecord : storeContent.getPreferences()) { _recordMap.put(preferenceRecord.getId(), preferenceRecord); } _storeState = StoreState.OPENED; return records; } catch (Exception e) { _storeState = StoreState.ERRORED; close(); throw e; } } JsonFilePreferenceStore(String path, String posixFilePermissions); @Override synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); @Override synchronized void close(); @Override synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords); @Override synchronized void replace(final Collection<UUID> preferenceRecordsToRemove,
final Collection<PreferenceRecord> preferenceRecordsToAdd); @Override synchronized void onDelete(); }
|
@Test public void testOpenAndLoad() throws Exception { UUID prefId = UUID.randomUUID(); Map<String, Object> attributes = Collections.<String, Object>singletonMap("test1", "test2"); createSingleEntryTestFile(prefId, attributes); Collection<PreferenceRecord> records = _store.openAndLoad(_updater); assertEquals("Unexpected size of stored preferences", (long) 1, (long) records.size()); PreferenceRecord storeRecord = records.iterator().next(); assertEquals("Unexpected stored preference id", prefId, storeRecord.getId()); assertEquals("Unexpected stored preference attributes", attributes, new HashMap<>(storeRecord.getAttributes())); verify(_updater, never()).updatePreferences(anyString(), anyCollection()); }
|
JsonFilePreferenceStore extends AbstractJsonFileStore implements PreferenceStore { @Override public synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords) { if (_storeState != StoreState.OPENED) { throw new IllegalStateException("PreferenceStore is not opened"); } if (preferenceRecords.isEmpty()) { return; } updateOrCreateInternal(preferenceRecords); } JsonFilePreferenceStore(String path, String posixFilePermissions); @Override synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); @Override synchronized void close(); @Override synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords); @Override synchronized void replace(final Collection<UUID> preferenceRecordsToRemove,
final Collection<PreferenceRecord> preferenceRecordsToAdd); @Override synchronized void onDelete(); }
|
@Test public void testUpdateOrCreate() throws Exception { final UUID id = UUID.randomUUID(); final Map<String, Object> attributes = new HashMap<>(); attributes.put("test1", "test2"); final PreferenceRecord record = new PreferenceRecordImpl(id, attributes); _store.openAndLoad(_updater); _store.updateOrCreate(Collections.singleton(record)); assertSinglePreferenceRecordInStore(id, attributes); }
@Test public void testUpdateFailIfNotOpened() throws Exception { try { _store.updateOrCreate(Collections.<PreferenceRecord>emptyList()); fail("Should not be able to update or create"); } catch (IllegalStateException e) { } }
|
JsonFilePreferenceStore extends AbstractJsonFileStore implements PreferenceStore { @Override public synchronized void replace(final Collection<UUID> preferenceRecordsToRemove, final Collection<PreferenceRecord> preferenceRecordsToAdd) { if (_storeState != StoreState.OPENED) { throw new IllegalStateException("PreferenceStore is not opened"); } if (preferenceRecordsToRemove.isEmpty() && preferenceRecordsToAdd.isEmpty()) { return; } _recordMap.keySet().removeAll(preferenceRecordsToRemove); updateOrCreateInternal(preferenceRecordsToAdd); } JsonFilePreferenceStore(String path, String posixFilePermissions); @Override synchronized Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); @Override synchronized void close(); @Override synchronized void updateOrCreate(final Collection<PreferenceRecord> preferenceRecords); @Override synchronized void replace(final Collection<UUID> preferenceRecordsToRemove,
final Collection<PreferenceRecord> preferenceRecordsToAdd); @Override synchronized void onDelete(); }
|
@Test public void testReplace() throws Exception { UUID prefId = UUID.randomUUID(); Map<String, Object> attributes = Collections.<String, Object>singletonMap("test1", "test2"); createSingleEntryTestFile(prefId, attributes); final UUID newPrefId = UUID.randomUUID(); final Map<String, Object> newAttributes = new HashMap<>(); newAttributes.put("test3", "test4"); final PreferenceRecord newRecord = new PreferenceRecordImpl(newPrefId, newAttributes); _store.openAndLoad(_updater); _store.replace(Collections.singleton(prefId), Collections.singleton(newRecord)); assertSinglePreferenceRecordInStore(newPrefId, newAttributes); }
@Test public void testReplaceFailIfNotOpened() throws Exception { try { _store.replace(Collections.<UUID>emptyList(), Collections.<PreferenceRecord>emptyList()); fail("Should not be able to replace"); } catch (IllegalStateException e) { } }
|
UpgraderHelper { public static Map<String, String> renameContextVariables(final Map<String, String> context, final Map<String, String> oldToNewNameMapping) { final Map<String, String> newContext = new HashMap<>(context); oldToNewNameMapping.forEach((oldName, newName) -> { if (newContext.containsKey(oldName)) { final String value = newContext.remove(oldName); newContext.put(newName, value); } }); return newContext; } static Map<String, String> renameContextVariables(final Map<String, String> context,
final Map<String, String> oldToNewNameMapping); static Map<String, String> reverse(Map<String, String> map); static final Map<String, String> MODEL9_MAPPING_FOR_RENAME_TO_ALLOW_DENY_CONTEXT_VARIABLES; }
|
@Test public void renameContextVariables() { final Map<String, String> context = new HashMap<>(); context.put("foo", "fooValue"); context.put("bar", "barValue"); final Map<String, String> newContext = UpgraderHelper.renameContextVariables(context, Collections.singletonMap("foo", "newFoo")); assertThat(newContext, is(notNullValue())); assertThat(newContext.size(), equalTo(context.size())); assertThat(newContext.get("bar"), equalTo(context.get("bar"))); assertThat(newContext.get("newFoo"), equalTo(context.get("foo"))); }
|
AbstractConsumerTarget implements ConsumerTarget<T> { @Override final public boolean close() { if (_state.compareAndSet(State.OPEN, State.CLOSED)) { setNotifyWorkDesired(false); List<MessageInstanceConsumer> consumers = new ArrayList<>(_consumers); _consumers.clear(); for (MessageInstanceConsumer consumer : consumers) { consumer.close(); } getSession().removeTicker(_suspendedConsumerLoggingTicker); return true; } else { return false; } } protected AbstractConsumerTarget(final boolean isMultiQueue,
final AMQPConnection<?> amqpConnection); @Override void acquisitionRemoved(final MessageInstance node); @Override boolean isMultiQueue(); @Override void notifyWork(); @Override final boolean isNotifyWorkDesired(); @Override boolean processPending(); @Override void consumerAdded(final MessageInstanceConsumer sub); @Override ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub); List<MessageInstanceConsumer> getConsumers(); @Override final boolean isSuspended(); @Override final State getState(); @Override final void send(final MessageInstanceConsumer consumer, MessageInstance entry, boolean batch); @Override long getUnacknowledgedMessages(); @Override long getUnacknowledgedBytes(); @Override boolean sendNextMessage(); @Override final boolean close(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); }
|
@Test public void testClose() throws Exception { _consumerTarget = new TestAbstractConsumerTarget(); assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size()); _consumerTarget.consumerAdded(_consumer); assertEquals("Unexpected number of consumers after add", (long) 1, (long) _consumerTarget.getConsumers().size()); _consumerTarget.close(); assertEquals("Unexpected number of consumers after close", (long) 0, (long) _consumerTarget.getConsumers().size()); verify(_consumer, times(1)).close(); }
|
AbstractConsumerTarget implements ConsumerTarget<T> { @Override public void notifyWork() { @SuppressWarnings("unchecked") final T target = (T) this; getSession().notifyWork(target); } protected AbstractConsumerTarget(final boolean isMultiQueue,
final AMQPConnection<?> amqpConnection); @Override void acquisitionRemoved(final MessageInstance node); @Override boolean isMultiQueue(); @Override void notifyWork(); @Override final boolean isNotifyWorkDesired(); @Override boolean processPending(); @Override void consumerAdded(final MessageInstanceConsumer sub); @Override ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub); List<MessageInstanceConsumer> getConsumers(); @Override final boolean isSuspended(); @Override final State getState(); @Override final void send(final MessageInstanceConsumer consumer, MessageInstance entry, boolean batch); @Override long getUnacknowledgedMessages(); @Override long getUnacknowledgedBytes(); @Override boolean sendNextMessage(); @Override final boolean close(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); }
|
@Test public void testNotifyWork() throws Exception { InOrder order = inOrder(_consumer); _consumerTarget = new TestAbstractConsumerTarget(); assertEquals("Unexpected number of consumers", (long) 0, (long) _consumerTarget.getConsumers().size()); _consumerTarget.consumerAdded(_consumer); _consumerTarget.setNotifyWorkDesired(true); order.verify(_consumer, times(1)).setNotifyWorkDesired(true); _consumerTarget.setNotifyWorkDesired(false); order.verify(_consumer, times(1)).setNotifyWorkDesired(false); _consumerTarget.setNotifyWorkDesired(true); order.verify(_consumer, times(1)).setNotifyWorkDesired(true); _consumerTarget.setNotifyWorkDesired(true); _consumerTarget.close(); order.verify(_consumer, times(1)).setNotifyWorkDesired(false); order.verify(_consumer, times(1)).close(); verifyNoMoreInteractions(_consumer); }
|
AbstractConsumerTarget implements ConsumerTarget<T> { @Override public boolean sendNextMessage() { MessageContainer messageContainer = null; MessageInstanceConsumer consumer = null; boolean iteratedCompleteList = false; while (messageContainer == null) { if (_pullIterator == null || !_pullIterator.hasNext()) { if (iteratedCompleteList) { break; } iteratedCompleteList = true; _pullIterator = getConsumers().iterator(); } if (_pullIterator.hasNext()) { consumer = _pullIterator.next(); messageContainer = consumer.pullMessage(); } } if (messageContainer != null) { MessageInstance entry = messageContainer.getMessageInstance(); try { send(consumer, entry, false); } catch (MessageConversionException mce) { restoreCredit(entry.getMessage()); final TransactionLogResource owningResource = entry.getOwningResource(); if (owningResource instanceof MessageSource) { final MessageSource.MessageConversionExceptionHandlingPolicy handlingPolicy = ((MessageSource) owningResource).getMessageConversionExceptionHandlingPolicy(); switch(handlingPolicy) { case CLOSE: entry.release(consumer); throw new ConnectionScopedRuntimeException(String.format( "Unable to convert message %s for this consumer", entry.getMessage()), mce); case ROUTE_TO_ALTERNATE: if (consumer.acquires()) { int enqueues = entry.routeToAlternate(null, null, null); if (enqueues == 0) { LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message discarded.", entry.getMessage(), mce.getMessage()); } else { LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message routed to alternate.", entry.getMessage(), mce.getMessage()); } } else { LOGGER.info("Failed to convert message {} for this browser because '{}'." + " Message skipped.", entry.getMessage(), mce.getMessage()); } break; case REJECT: entry.reject(consumer); entry.release(consumer); LOGGER.info("Failed to convert message {} for this consumer because '{}'." + " Message skipped.", entry.getMessage(), mce.getMessage()); break; default: throw new ServerScopedRuntimeException("Unrecognised policy " + handlingPolicy); } } else { throw new ConnectionScopedRuntimeException(String.format( "Unable to convert message %s for this consumer", entry.getMessage()), mce); } } finally { if (messageContainer.getMessageReference() != null) { messageContainer.getMessageReference().release(); } } return true; } else { return false; } } protected AbstractConsumerTarget(final boolean isMultiQueue,
final AMQPConnection<?> amqpConnection); @Override void acquisitionRemoved(final MessageInstance node); @Override boolean isMultiQueue(); @Override void notifyWork(); @Override final boolean isNotifyWorkDesired(); @Override boolean processPending(); @Override void consumerAdded(final MessageInstanceConsumer sub); @Override ListenableFuture<Void> consumerRemoved(final MessageInstanceConsumer sub); List<MessageInstanceConsumer> getConsumers(); @Override final boolean isSuspended(); @Override final State getState(); @Override final void send(final MessageInstanceConsumer consumer, MessageInstance entry, boolean batch); @Override long getUnacknowledgedMessages(); @Override long getUnacknowledgedBytes(); @Override boolean sendNextMessage(); @Override final boolean close(); @Override void queueDeleted(final Queue queue, final MessageInstanceConsumer sub); }
|
@Test public void testConversionExceptionPolicyClose() throws Exception { configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE); try { _consumerTarget.sendNextMessage(); fail("exception not thrown"); } catch (ConnectionScopedRuntimeException e) { final boolean condition = e.getCause() instanceof MessageConversionException; assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'", e.getCause().getClass().getSimpleName()), condition); } assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any()); }
@Test public void testConversionExceptionPolicyCloseForNonAcquiringConsumer() throws Exception { configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.CLOSE); try { _consumerTarget.sendNextMessage(); fail("exception not thrown"); } catch (ConnectionScopedRuntimeException e) { final boolean condition = e.getCause() instanceof MessageConversionException; assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'", e.getCause().getClass().getSimpleName()), condition); } assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any()); }
@Test public void testConversionExceptionPolicyReroute() throws Exception { configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.ROUTE_TO_ALTERNATE); _consumerTarget.sendNextMessage(); assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance).routeToAlternate(null, null, null); }
@Test public void testConversionExceptionPolicyRerouteForNonAcquiringConsumer() throws Exception { configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.ROUTE_TO_ALTERNATE); _consumerTarget.sendNextMessage(); assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any()); }
@Test public void testConversionExceptionPolicyReject() throws Exception { configureBehaviour(true, MessageSource.MessageConversionExceptionHandlingPolicy.REJECT); _consumerTarget.sendNextMessage(); assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance).reject(_consumer); verify(_messageInstance).release(_consumer); }
@Test public void testConversionExceptionPolicyRejectForNonAcquiringConsumer() throws Exception { configureBehaviour(false, MessageSource.MessageConversionExceptionHandlingPolicy.REJECT); _consumerTarget.sendNextMessage(); assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance).reject(_consumer); verify(_messageInstance).release(_consumer); }
@Test public void testConversionExceptionPolicyWhenOwningResourceIsNotMessageSource() throws Exception { final TransactionLogResource owningResource = mock(TransactionLogResource.class); when(_messageInstance.getOwningResource()).thenReturn(owningResource); try { _consumerTarget.sendNextMessage(); fail("exception not thrown"); } catch (ConnectionScopedRuntimeException e) { final boolean condition = e.getCause() instanceof MessageConversionException; assertTrue(String.format("ConnectionScopedRuntimeException has unexpected cause '%s'", e.getCause().getClass().getSimpleName()), condition); } assertTrue("message credit was not restored", _consumerTarget.isCreditRestored()); verify(_messageInstance, never()).routeToAlternate(any(Action.class), any(ServerTransaction.class), any()); }
|
AbstractStandardVirtualHostNode extends AbstractVirtualHostNode<X> implements VirtualHostNode<X> { @Override public QueueManagingVirtualHost<?> getVirtualHost() { VirtualHost<?> vhost = super.getVirtualHost(); if(vhost == null || vhost instanceof QueueManagingVirtualHost) { return (QueueManagingVirtualHost<?>)vhost; } else { throw new IllegalStateException(this + " has a virtual host which is not a queue managing virtual host " + vhost); } } AbstractStandardVirtualHostNode(Map<String, Object> attributes,
Broker<?> parent); @Override QueueManagingVirtualHost<?> getVirtualHost(); @Override String toString(); @Override Collection<RemoteReplicationNode<?>> getRemoteReplicationNodes(); }
|
@Test public void testActivateVHN_StoreHasVH() throws Exception { UUID virtualHostId = UUID.randomUUID(); ConfiguredObjectRecord vhostRecord = createVirtualHostConfiguredObjectRecord(virtualHostId); DurableConfigurationStore configStore = configStoreThatProduces(vhostRecord); Map<String, Object> nodeAttributes = new HashMap<>(); nodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE_NAME); nodeAttributes.put(VirtualHostNode.ID, _nodeId); VirtualHostNode<?> node = new TestVirtualHostNode(_broker, nodeAttributes, configStore); node.open(); node.start(); VirtualHost<?> virtualHost = node.getVirtualHost(); assertNotNull("Virtual host was not recovered", virtualHost); assertEquals("Unexpected virtual host name", TEST_VIRTUAL_HOST_NAME, virtualHost.getName()); assertEquals("Unexpected virtual host state", State.ACTIVE, virtualHost.getState()); assertEquals("Unexpected virtual host id", virtualHostId, virtualHost.getId()); node.close(); }
@Test public void testActivateVHN_StoreHasNoVH() throws Exception { DurableConfigurationStore configStore = configStoreThatProducesNoRecords(); Map<String, Object> nodeAttributes = new HashMap<>(); nodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE_NAME); nodeAttributes.put(VirtualHostNode.ID, _nodeId); VirtualHostNode<?> node = new TestVirtualHostNode(_broker, nodeAttributes, configStore); node.open(); node.start(); VirtualHost<?> virtualHost = node.getVirtualHost(); assertNull("Virtual host should not be automatically created", virtualHost); node.close(); }
@Test public void testActivateVHNWithVHBlueprint_StoreHasNoVH() throws Exception { DurableConfigurationStore configStore = new NullMessageStore() {}; String vhBlueprint = String.format("{ \"type\" : \"%s\", \"name\" : \"%s\"}", TestMemoryVirtualHost.VIRTUAL_HOST_TYPE, TEST_VIRTUAL_HOST_NAME); Map<String, String> context = Collections.singletonMap(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, vhBlueprint); Map<String, Object> nodeAttributes = new HashMap<>(); nodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE_NAME); nodeAttributes.put(VirtualHostNode.ID, _nodeId); nodeAttributes.put(VirtualHostNode.CONTEXT, context); VirtualHostNode<?> node = new TestVirtualHostNode(_broker, nodeAttributes, configStore); node.open(); node.start(); VirtualHost<?> virtualHost = node.getVirtualHost(); assertNotNull("Virtual host should be created by blueprint", virtualHost); assertEquals("Unexpected virtual host name", TEST_VIRTUAL_HOST_NAME, virtualHost.getName()); assertEquals("Unexpected virtual host state", State.ACTIVE, virtualHost.getState()); assertNotNull("Unexpected virtual host id", virtualHost.getId()); assertEquals("Initial configuration should be empty", "{}", node.getVirtualHostInitialConfiguration()); node.close(); }
@Test public void testActivateVHNWithVHBlueprintUsed_StoreHasNoVH() throws Exception { DurableConfigurationStore configStore = configStoreThatProducesNoRecords(); String vhBlueprint = String.format("{ \"type\" : \"%s\", \"name\" : \"%s\"}", TestMemoryVirtualHost.VIRTUAL_HOST_TYPE, TEST_VIRTUAL_HOST_NAME); Map<String, String> context = new HashMap<>(); context.put(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, vhBlueprint); Map<String, Object> nodeAttributes = new HashMap<>(); nodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE_NAME); nodeAttributes.put(VirtualHostNode.ID, _nodeId); nodeAttributes.put(VirtualHostNode.CONTEXT, context); nodeAttributes.put(VirtualHostNode.VIRTUALHOST_INITIAL_CONFIGURATION, "{}"); VirtualHostNode<?> node = new TestVirtualHostNode(_broker, nodeAttributes, configStore); node.open(); node.start(); VirtualHost<?> virtualHost = node.getVirtualHost(); assertNull("Virtual host should not be created by blueprint", virtualHost); node.close(); }
@Test public void testActivateVHNWithVHBlueprint_StoreHasExistingVH() throws Exception { UUID virtualHostId = UUID.randomUUID(); ConfiguredObjectRecord record = createVirtualHostConfiguredObjectRecord(virtualHostId); DurableConfigurationStore configStore = configStoreThatProduces(record); String vhBlueprint = String.format("{ \"type\" : \"%s\", \"name\" : \"%s\"}", TestMemoryVirtualHost.VIRTUAL_HOST_TYPE, "vhFromBlueprint"); Map<String, String> context = Collections.singletonMap(AbstractVirtualHostNode.VIRTUALHOST_BLUEPRINT_CONTEXT_VAR, vhBlueprint); Map<String, Object> nodeAttributes = new HashMap<>(); nodeAttributes.put(VirtualHostNode.NAME, TEST_VIRTUAL_HOST_NODE_NAME); nodeAttributes.put(VirtualHostNode.ID, _nodeId); nodeAttributes.put(VirtualHostNode.CONTEXT, context); VirtualHostNode<?> node = new TestVirtualHostNode(_broker, nodeAttributes, configStore); node.open(); node.start(); VirtualHost<?> virtualHost = node.getVirtualHost(); assertNotNull("Virtual host should be recovered", virtualHost); assertEquals("Unexpected virtual host name", TEST_VIRTUAL_HOST_NAME, virtualHost.getName()); assertEquals("Unexpected virtual host state", State.ACTIVE, virtualHost.getState()); assertEquals("Unexpected virtual host id", virtualHostId, virtualHost.getId()); node.close(); }
|
SuppressingInheritedAccessControlContextThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable runnable) { return Subject.doAsPrivileged(_subject, new PrivilegedAction<Thread>() { @Override public Thread run() { Thread thread = _defaultThreadFactory.newThread(runnable); if (_threadNamePrefix != null) { thread.setName(_threadNamePrefix + "-" + _threadId.getAndIncrement()); } return thread; } }, null); } SuppressingInheritedAccessControlContextThreadFactory(String threadNamePrefix, final Subject subject); @Override Thread newThread(final Runnable runnable); }
|
@Test public void testAccessControlContextIsNotInheritedByThread() throws Exception { final String principalName = getTestName(); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<AccessControlContext> threadAccessControlContextCapturer = new AtomicReference<>(); final AtomicReference<AccessControlContext> callerAccessControlContextCapturer = new AtomicReference<>(); final Set<Principal> principals = Collections.<Principal>singleton(new Principal() { @Override public String getName() { return principalName; } @Override public String toString() { return "Principal{" + getName() + "}"; } }); Subject subject = new Subject(false, principals, Collections.EMPTY_SET, Collections.EMPTY_SET); Subject.doAs(subject, new PrivilegedAction<Void>() { @Override public Void run() { callerAccessControlContextCapturer.set(AccessController.getContext()); SuppressingInheritedAccessControlContextThreadFactory factory = new SuppressingInheritedAccessControlContextThreadFactory(null, null); factory.newThread(new Runnable() { @Override public void run() { threadAccessControlContextCapturer.set(AccessController.getContext()); latch.countDown(); } }).start(); return null; } }); latch.await(3, TimeUnit.SECONDS); Subject callerSubject = Subject.getSubject(callerAccessControlContextCapturer.get()); Subject threadSubject = Subject.getSubject(threadAccessControlContextCapturer.get()); assertEquals("Unexpected subject in main thread", callerSubject, subject); assertNull("Unexpected subject in executor thread", threadSubject); }
|
FormattingStatisticsResolver implements Resolver { @Override public String resolve(String statNameWithFormatSpecifier, final Resolver unused) { String[] split = statNameWithFormatSpecifier.split(":", 2); String statName = split[0]; Object statisticValue = _statistics.get(statName); if (split.length > 1) { String formatterName = split[1].toLowerCase(); if (statisticValue instanceof Number) { final long value = ((Number) statisticValue).longValue(); switch (formatterName.toLowerCase()) { case BYTEUNIT: statisticValue = toIEC80000BinaryPrefixedValue(value); break; case DURATION: statisticValue = value < 0 ? "-" : Duration.ofMillis(value); break; case DATETIME: statisticValue = value < 0 ? "-" : Instant.ofEpochMilli(value).toString(); break; } } else if (statisticValue instanceof Date) { switch (formatterName.toLowerCase()) { case DATETIME: long time = ((Date) statisticValue).getTime(); statisticValue = time < 0 ? "-" : Instant.ofEpochMilli(time).toString(); break; } } } return statisticValue == null ? null : String.valueOf(statisticValue); } FormattingStatisticsResolver(final ConfiguredObject<?> object); @Override String resolve(String statNameWithFormatSpecifier, final Resolver unused); }
|
@Test public void testNoFormatting() throws Exception { assertEquals("10", _resolver.resolve(POSITIVE_VALUE_STAT_NAME, null)); assertEquals("0", _resolver.resolve(ZERO_VALUE_STAT_NAME, null)); assertEquals("-1", _resolver.resolve(NEGATIVE_VALUE_STAT_NAME, null)); }
@Test public void testDuration() throws Exception { assertEquals("PT17M28.577S", _resolver.resolve(LARGEST_POSITIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.DURATION, null)); assertEquals("PT0S", _resolver.resolve(ZERO_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.DURATION, null)); assertEquals("-", _resolver.resolve(NEGATIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.DURATION, null)); }
@Test public void testDateTime() throws Exception { assertEquals("1970-01-01T00:00:00Z", _resolver.resolve(ZERO_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.DATETIME, null)); assertEquals("1970-01-01T00:00:00Z", _resolver.resolve(EPOCH_DATE_STAT_NAME + ":" + FormattingStatisticsResolver.DATETIME, null)); assertEquals("-", _resolver.resolve(NEGATIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.DATETIME, null)); }
@Test public void testIEC80000BinaryPrefixed() throws Exception { NumberFormat formatter = NumberFormat.getInstance(); formatter.setMinimumFractionDigits(1); String ONE_POINT_ZERO = formatter.format(1L); assertEquals(ONE_POINT_ZERO + " MiB", _resolver.resolve(LARGEST_POSITIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals(ONE_POINT_ZERO + " KiB", _resolver.resolve(LARGER_POSITIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals("10 B", _resolver.resolve(POSITIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals("0 B", _resolver.resolve(ZERO_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals("-1 B", _resolver.resolve(NEGATIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals("-"+ ONE_POINT_ZERO + " KiB", _resolver.resolve(SMALLER_NEGATIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); assertEquals("-" + ONE_POINT_ZERO + " MiB", _resolver.resolve(SMALLEST_NEGATIVE_VALUE_STAT_NAME + ":" + FormattingStatisticsResolver.BYTEUNIT, null)); }
|
UpgradeFrom8To9 extends AbstractStoreUpgrade { @Override public void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, final ConfiguredObject<?> parent) { reportStarting(environment, 8); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); final Transaction transaction = environment.beginTransaction(null, null); try { Database userPreferencesDb = environment.openDatabase(transaction, "USER_PREFERENCES", dbConfig); userPreferencesDb.close(); try (Database userPreferencesVersionDb = environment.openDatabase(transaction, "USER_PREFERENCES_VERSION", dbConfig)) { if (userPreferencesVersionDb.count() == 0L) { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); StringBinding.stringToEntry(DEFAULT_VERSION, key); LongBinding.longToEntry(System.currentTimeMillis(), value); OperationStatus status = userPreferencesVersionDb.put(transaction, key, value); if (status != OperationStatus.SUCCESS) { throw new StoreException("Error initialising user preference version: " + status); } } } transaction.commit(); reportFinished(environment, 9); } catch (RuntimeException e) { try { if (transaction.isValid()) { transaction.abort(); } } finally { throw e; } } } @Override void performUpgrade(final Environment environment,
final UpgradeInteractionHandler handler,
final ConfiguredObject<?> parent); }
|
@Test public void testPerformUpgrade() throws Exception { UpgradeFrom8To9 upgrade = new UpgradeFrom8To9(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost()); assertDatabaseRecordCount(PREFERENCES_DB_NAME, 0); assertDatabaseRecordCount(PREFERENCES_VERSION_DB_NAME, 1); List<String> versions = loadVersions(); assertEquals("Unexpected number of versions loaded", 1, versions.size()); assertEquals("Unexpected version", "6.1", versions.get(0)); }
|
UpgradeFrom5To6 extends AbstractStoreUpgrade { @Override public void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, ConfiguredObject<?> parent) { reportStarting(environment, 5); upgradeMessages(environment, handler); upgradeConfiguredObjectsAndDependencies(environment, handler, parent.getName()); renameDatabases(environment, null); reportFinished(environment, 6); } @Override void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, ConfiguredObject<?> parent); }
|
@Test public void testPerformUpgrade() throws Exception { UpgradeFrom5To6 upgrade = new UpgradeFrom5To6(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost()); assertDatabaseRecordCounts(); assertContent(); assertConfiguredObjects(); assertQueueEntries(); }
@Test public void testPerformUpgradeWithMissingMessageChunkKeepsIncompleteMessage() throws Exception { corruptDatabase(); UpgradeFrom5To6 upgrade = new UpgradeFrom5To6(); upgrade.performUpgrade(_environment, new StaticAnswerHandler(UpgradeInteractionResponse.YES), getVirtualHost()); assertDatabaseRecordCounts(); assertConfiguredObjects(); assertQueueEntries(); }
@Test public void testPerformUpgradeWithMissingMessageChunkDiscardsIncompleteMessage() throws Exception { corruptDatabase(); UpgradeFrom5To6 upgrade = new UpgradeFrom5To6(); UpgradeInteractionHandler discardMessageInteractionHandler = new StaticAnswerHandler(UpgradeInteractionResponse.NO); upgrade.performUpgrade(_environment, discardMessageInteractionHandler, getVirtualHost()); assertDatabaseRecordCount(NEW_METADATA_DB_NAME, 12); assertDatabaseRecordCount(NEW_CONTENT_DB_NAME, 12); assertConfiguredObjects(); assertQueueEntries(); }
@Test public void testPerformXidUpgrade() throws Exception { File storeLocation = new File(TMP_FOLDER, getTestName()); storeLocation.mkdirs(); Environment environment = createEnvironment(storeLocation); try { populateOldXidEntries(environment); UpgradeFrom5To6 upgrade = new UpgradeFrom5To6(); upgrade.performUpgrade(environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost()); assertXidEntries(environment); } finally { try { environment.close(); } finally { deleteDirectoryIfExists(storeLocation); } } }
|
Upgrader { void upgrade(final int fromVersion, final int toVersion) throws StoreException { try { @SuppressWarnings("unchecked") Class<StoreUpgrade> upgradeClass = (Class<StoreUpgrade>) Class.forName("org.apache.qpid.server.store.berkeleydb.upgrade." + "UpgradeFrom"+fromVersion+"To"+toVersion); Constructor<StoreUpgrade> ctr = upgradeClass.getConstructor(); StoreUpgrade upgrade = ctr.newInstance(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, _parent); } catch (ClassNotFoundException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (NoSuchMethodException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (InvocationTargetException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (InstantiationException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } catch (IllegalAccessException e) { throw new StoreException("Unable to upgrade BDB data store from version " + fromVersion + " to version" + toVersion, e); } } Upgrader(Environment environment, ConfiguredObject<?> parent); void upgradeIfNecessary(); }
|
@Test public void testUpgrade() throws Exception { assertEquals("Unexpected store version", -1, getStoreVersion(_environment)); _upgrader.upgradeIfNecessary(); assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(_environment)); assertContent(); }
|
CompositeFilter extends Filter<ILoggingEvent> { @Override public FilterReply decide(ILoggingEvent event) { FilterReply reply = DENY; for(Filter<ILoggingEvent> filter : _filterList) { FilterReply filterReply = filter.decide(event); if (filterReply == DENY) { reply = filterReply; break; } if (filterReply == ACCEPT) { reply = filterReply; } } if(reply == ACCEPT) { switch(event.getLevel().toInt()) { case WARN_INT: _warnCount.incrementAndGet(); break; case ERROR_INT: _errorCount.incrementAndGet(); break; default: } return ACCEPT; } return DENY; } void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule); void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule); @Override FilterReply decide(ILoggingEvent event); long getErrorCount(); long getWarnCount(); }
|
@Test public void testDecideWithNoRule() { CompositeFilter compositeFilter = new CompositeFilter(); FilterReply reply = compositeFilter.decide(mock(ILoggingEvent.class)); assertEquals("Unexpected reply with no rule added", FilterReply.DENY, reply); }
|
Upgrader { public void upgradeIfNecessary() { boolean isEmpty = _environment.getDatabaseNames().isEmpty(); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); Database versionDb = null; try { versionDb = _environment.openDatabase(null, VERSION_DB_NAME, dbConfig); if(versionDb.count() == 0L) { int sourceVersion = isEmpty ? BDBConfigurationStore.VERSION: identifyOldStoreVersion(); DatabaseEntry key = new DatabaseEntry(); IntegerBinding.intToEntry(sourceVersion, key); DatabaseEntry value = new DatabaseEntry(); LongBinding.longToEntry(System.currentTimeMillis(), value); versionDb.put(null, key, value); } int version = getSourceVersion(versionDb); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Source message store version is " + version); } if(version > BDBConfigurationStore.VERSION) { throw new StoreException("Database version " + version + " is higher than the most recent known version: " + BDBConfigurationStore.VERSION); } performUpgradeFromVersion(version, versionDb); } finally { if (versionDb != null) { versionDb.close(); } } } Upgrader(Environment environment, ConfiguredObject<?> parent); void upgradeIfNecessary(); }
|
@Test public void testEmptyDatabaseUpgradeDoesNothing() throws Exception { File nonExistentStoreLocation = new File(TMP_FOLDER, getTestName()); deleteDirectoryIfExists(nonExistentStoreLocation); nonExistentStoreLocation.mkdir(); Environment emptyEnvironment = createEnvironment(nonExistentStoreLocation); try { _upgrader = new Upgrader(emptyEnvironment, getVirtualHost()); _upgrader.upgradeIfNecessary(); List<String> databaseNames = emptyEnvironment.getDatabaseNames(); List<String> expectedDatabases = new ArrayList<String>(); expectedDatabases.add(Upgrader.VERSION_DB_NAME); assertEquals("Expectedonly VERSION table in initially empty store after upgrade: ", expectedDatabases, databaseNames); assertEquals("Unexpected store version", BDBConfigurationStore.VERSION, getStoreVersion(emptyEnvironment)); } finally { emptyEnvironment.close(); nonExistentStoreLocation.delete(); } }
|
UpgradeFrom4To5 extends AbstractStoreUpgrade { @Override public void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, ConfiguredObject<?> parent) { Transaction transaction = null; reportStarting(environment, 4); transaction = environment.beginTransaction(null, null); final List<AMQShortString> potentialDurableSubs = findPotentialDurableSubscriptions(environment, transaction); Set<String> existingQueues = upgradeQueues(environment, handler, potentialDurableSubs, transaction); upgradeQueueBindings(environment, handler, potentialDurableSubs, transaction); Set<Long> messagesToDiscard = upgradeDelivery(environment, existingQueues, handler, transaction); upgradeContent(environment, handler, messagesToDiscard, transaction); upgradeMetaData(environment, handler, messagesToDiscard, transaction); renameRemainingDatabases(environment, handler, transaction); transaction.commit(); reportFinished(environment, 5); } @Override void performUpgrade(final Environment environment, final UpgradeInteractionHandler handler, ConfiguredObject<?> parent); }
|
@Test public void testPerformUpgradeWithHandlerAnsweringYes() throws Exception { UpgradeFrom4To5 upgrade = new UpgradeFrom4To5(); upgrade.performUpgrade(_environment, new StaticAnswerHandler(UpgradeInteractionResponse.YES), getVirtualHost()); assertQueues(new HashSet<String>(Arrays.asList(QUEUE_NAMES))); assertDatabaseRecordCount(DELIVERY_DB_NAME, TOTAL_MESSAGE_NUMBER); assertDatabaseRecordCount(MESSAGE_META_DATA_DB_NAME, TOTAL_MESSAGE_NUMBER); assertDatabaseRecordCount(EXCHANGE_DB_NAME, TOTAL_EXCHANGES); for (int i = 0; i < QUEUE_SIZES.length; i++) { assertQueueMessages(QUEUE_NAMES[i], QUEUE_SIZES[i]); } final List<BindingRecord> queueBindings = loadBindings(); assertEquals("Unxpected bindings size", TOTAL_BINDINGS, queueBindings.size()); assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE, "amq.topic", TOPIC_NAME, ""); assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE_WITH_SELECTOR, "amq.topic", SELECTOR_TOPIC_NAME, "testprop='true'"); assertBindingRecord(queueBindings, QUEUE_NAME, "amq.direct", QUEUE_NAME, null); assertBindingRecord(queueBindings, NON_DURABLE_QUEUE_NAME, "amq.direct", NON_DURABLE_QUEUE_NAME, null); assertBindingRecord(queueBindings, NONEXCLUSIVE_WITH_ERRONEOUS_OWNER, "amq.direct", NONEXCLUSIVE_WITH_ERRONEOUS_OWNER, null); assertQueueHasOwner(NONEXCLUSIVE_WITH_ERRONEOUS_OWNER, "misused-owner-as-description"); assertContent(); }
@Test public void testPerformUpgradeWithHandlerAnsweringNo() throws Exception { UpgradeFrom4To5 upgrade = new UpgradeFrom4To5(); upgrade.performUpgrade(_environment, new StaticAnswerHandler(UpgradeInteractionResponse.NO), getVirtualHost()); HashSet<String> queues = new HashSet<String>(Arrays.asList(QUEUE_NAMES)); assertTrue(NON_DURABLE_QUEUE_NAME + " should be in the list of queues" , queues.remove(NON_DURABLE_QUEUE_NAME)); assertQueues(queues); assertDatabaseRecordCount(DELIVERY_DB_NAME, 13); assertDatabaseRecordCount(MESSAGE_META_DATA_DB_NAME, 13); assertDatabaseRecordCount(EXCHANGE_DB_NAME, TOTAL_EXCHANGES); assertQueueMessages(DURABLE_SUBSCRIPTION_QUEUE, 1); assertQueueMessages(DURABLE_SUBSCRIPTION_QUEUE_WITH_SELECTOR, 1); assertQueueMessages(QUEUE_NAME, 10); assertQueueMessages(QUEUE_WITH_DLQ_NAME + "_DLQ", 1); final List<BindingRecord> queueBindings = loadBindings(); assertEquals("Unxpected list size", TOTAL_BINDINGS - 2, queueBindings.size()); assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE, "amq.topic", TOPIC_NAME, ""); assertBindingRecord(queueBindings, DURABLE_SUBSCRIPTION_QUEUE_WITH_SELECTOR, "amq.topic", SELECTOR_TOPIC_NAME, "testprop='true'"); assertBindingRecord(queueBindings, QUEUE_NAME, "amq.direct", QUEUE_NAME, null); assertQueueHasOwner(NONEXCLUSIVE_WITH_ERRONEOUS_OWNER, "misused-owner-as-description"); assertContent(); }
|
DatabaseTemplate { public void run(DatabaseRunnable databaseRunnable) { DatabaseCallable<Void> callable = runnableToCallable(databaseRunnable); call(callable); } DatabaseTemplate(Environment environment, String sourceDatabaseName, Transaction transaction); DatabaseTemplate(Environment environment, String sourceDatabaseName, String targetDatabaseName,
Transaction parentTransaction); void run(DatabaseRunnable databaseRunnable); T call(DatabaseCallable<T> databaseCallable); }
|
@Test public void testExecuteWithTwoDatabases() { String targetDatabaseName = "targetDatabase"; Database targetDatabase = mock(Database.class); Transaction txn = mock(Transaction.class); when(_environment.openDatabase(same(txn), same(targetDatabaseName), isA(DatabaseConfig.class))) .thenReturn(targetDatabase); DatabaseTemplate databaseTemplate = new DatabaseTemplate(_environment, SOURCE_DATABASE, targetDatabaseName, txn); DatabaseRunnable databaseOperation = mock(DatabaseRunnable.class); databaseTemplate.run(databaseOperation); verify(databaseOperation).run(_sourceDatabase, targetDatabase, txn); verify(_sourceDatabase).close(); verify(targetDatabase).close(); }
@Test public void testExecuteWithOneDatabases() { DatabaseTemplate databaseTemplate = new DatabaseTemplate(_environment, SOURCE_DATABASE, null, null); DatabaseRunnable databaseOperation = mock(DatabaseRunnable.class); databaseTemplate.run(databaseOperation); verify(databaseOperation).run(eq(_sourceDatabase), isNull(), isNull()); verify(_sourceDatabase).close(); }
|
UpgradeFrom7To8 extends AbstractStoreUpgrade { @Override public void performUpgrade(Environment environment, UpgradeInteractionHandler handler, ConfiguredObject<?> parent) { reportStarting(environment, 7); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); Database hierarchyDb = environment.openDatabase(null, "CONFIGURED_OBJECT_HIERARCHY", dbConfig); Database configuredObjectsDb = environment.openDatabase(null, "CONFIGURED_OBJECTS", dbConfig); Database configVersionDb = environment.openDatabase(null, "CONFIG_VERSION", dbConfig); Database messageMetadataDb = environment.openDatabase(null, "MESSAGE_METADATA", dbConfig); Database messageMetadataSeqDb = environment.openDatabase(null, "MESSAGE_METADATA.SEQ", dbConfig); long maxMessageId = getMaximumMessageId(messageMetadataDb); createMessageMetadataSequence(messageMetadataSeqDb, maxMessageId); Cursor objectsCursor = null; String stringifiedConfigVersion = BrokerModel.MODEL_VERSION; int configVersion = getConfigVersion(configVersionDb); if (configVersion > -1) { stringifiedConfigVersion = "0." + configVersion; } configVersionDb.close(); String virtualHostName = parent.getName(); Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); virtualHostAttributes.put("modelVersion", stringifiedConfigVersion); virtualHostAttributes.put("name", virtualHostName); UUID virtualHostId = UUIDGenerator.generateVhostUUID(virtualHostName); ConfiguredObjectRecord virtualHostRecord = new org.apache.qpid.server.store.ConfiguredObjectRecordImpl(virtualHostId, "VirtualHost", virtualHostAttributes); Transaction txn = environment.beginTransaction(null, null); try { objectsCursor = configuredObjectsDb.openCursor(txn, null); DatabaseEntry key = new DatabaseEntry(); DatabaseEntry value = new DatabaseEntry(); ObjectMapper mapper = new ObjectMapper(); while (objectsCursor.getNext(key, value, LockMode.RMW) == OperationStatus.SUCCESS) { UUID id = UUIDTupleBinding.getInstance().entryToObject(key); TupleInput input = TupleBinding.entryToInput(value); String type = input.readString(); String json = input.readString(); Map<String,Object> attributes = null; try { attributes = mapper.readValue(json, MAP_TYPE_REFERENCE); } catch (Exception e) { throw new StoreException(e); } String name = (String)attributes.get("name"); if (type.equals("Exchange")) { _defaultExchanges.remove(name); } if(!type.endsWith("Binding")) { storeVirtualHostHierarchyRecord(hierarchyDb, txn, id, virtualHostId); } else { try { DatabaseEntry hierarchyKey = new DatabaseEntry(); DatabaseEntry hierarchyValue = new DatabaseEntry(); Object queueIdString = attributes.remove("queue"); if(queueIdString instanceof String) { UUID queueId = UUID.fromString(queueIdString.toString()); UUIDTupleBinding.getInstance().objectToEntry(queueId,hierarchyValue); TupleOutput tupleOutput = new TupleOutput(); tupleOutput.writeLong(id.getMostSignificantBits()); tupleOutput.writeLong(id.getLeastSignificantBits()); tupleOutput.writeString("Queue"); TupleBinding.outputToEntry(tupleOutput, hierarchyKey); hierarchyDb.put(txn, hierarchyKey, hierarchyValue); } Object exchangeIdString = attributes.remove("exchange"); if(exchangeIdString instanceof String) { UUID exchangeId = UUID.fromString(exchangeIdString.toString()); UUIDTupleBinding.getInstance().objectToEntry(exchangeId,hierarchyValue); TupleOutput tupleOutput = new TupleOutput(); tupleOutput.writeLong(id.getMostSignificantBits()); tupleOutput.writeLong(id.getLeastSignificantBits()); tupleOutput.writeString("Exchange"); TupleBinding.outputToEntry(tupleOutput, hierarchyKey); hierarchyDb.put(txn, hierarchyKey, hierarchyValue); } TupleOutput tupleOutput = new TupleOutput(); tupleOutput.writeString(type); StringWriter writer = new StringWriter(); mapper.writeValue(writer,attributes); tupleOutput.writeString(writer.getBuffer().toString()); TupleBinding.outputToEntry(tupleOutput, value); objectsCursor.putCurrent(value); } catch (IOException e) { throw new StoreException(e); } } } } finally { if(objectsCursor != null) { objectsCursor.close(); } } storeConfiguredObjectEntry(configuredObjectsDb, txn, virtualHostRecord); for (Map.Entry<String, String> defaultExchangeEntry : _defaultExchanges.entrySet()) { UUID id = UUIDGenerator.generateExchangeUUID(defaultExchangeEntry.getKey(), virtualHostName); Map<String, Object> exchangeAttributes = new HashMap<String, Object>(); exchangeAttributes.put("name", defaultExchangeEntry.getKey()); exchangeAttributes.put("type", defaultExchangeEntry.getValue()); exchangeAttributes.put("lifetimePolicy", "PERMANENT"); ConfiguredObjectRecord exchangeRecord = new org.apache.qpid.server.store.ConfiguredObjectRecordImpl(id, "Exchange", exchangeAttributes); storeConfiguredObjectEntry(configuredObjectsDb, txn, exchangeRecord); storeVirtualHostHierarchyRecord(hierarchyDb, txn, id, virtualHostId); } txn.commit(); hierarchyDb.close(); configuredObjectsDb.close(); messageMetadataDb.close(); messageMetadataSeqDb.close(); reportFinished(environment, 8); } @Override void performUpgrade(Environment environment, UpgradeInteractionHandler handler, ConfiguredObject<?> parent); }
|
@Test public void testPerformUpgrade() throws Exception { UpgradeFrom7To8 upgrade = new UpgradeFrom7To8(); upgrade.performUpgrade(_environment, UpgradeInteractionHandler.DEFAULT_HANDLER, getVirtualHost()); assertDatabaseRecordCount(CONFIGURED_OBJECTS_DB_NAME, 11); assertDatabaseRecordCount(CONFIGURED_OBJECT_HIERARCHY_DB_NAME, 13); assertConfiguredObjects(); assertConfiguredObjectHierarchy(); }
|
BDBPreferenceStore extends AbstractBDBPreferenceStore { @Override public Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater) throws StoreException { StoreState storeState = getStoreState(); if (StoreState.OPENED.equals(storeState) || StoreState.OPENING.equals(storeState)) { throw new IllegalStateException("PreferenceStore is already opened"); } _environmentFacade = _environmentFactory.createEnvironmentFacade(null); return super.openAndLoad(updater); } BDBPreferenceStore(final ConfiguredObject<?> parent, final String storePath); @Override Collection<PreferenceRecord> openAndLoad(final PreferenceStoreUpdater updater); }
|
@Test public void testVersionAfterUpgrade() throws Exception { FileUtils.delete(_storeFile, true); _storeFile.mkdirs(); ModelVersion storeVersion = new ModelVersion(BrokerModel.MODEL_MAJOR_VERSION - 1, BrokerModel.MODEL_MINOR_VERSION); populateTestData(_testInitialRecords, storeVersion.toString()); _preferenceStore.openAndLoad(_updater); ModelVersion storedVersion = _preferenceStore.getStoredVersion(); assertEquals("Unexpected version", BrokerModel.MODEL_VERSION, storedVersion.toString()); }
@Test public void testOpenAndLoad() throws Exception { Collection<PreferenceRecord> recovered = _preferenceStore.openAndLoad(_updater); assertEquals("Unexpected store state", AbstractBDBPreferenceStore.StoreState.OPENED, _preferenceStore.getStoreState()); assertNotNull("Store was not properly opened", _preferenceStore.getEnvironmentFacade()); PreferenceTestHelper.assertRecords(_testInitialRecords, recovered); }
@Test public void testUpdateOrCreate() throws Exception { _preferenceStore.openAndLoad(_updater); PreferenceRecord oldRecord = _testInitialRecords.get(0); Collection<PreferenceRecord> records = Arrays.<PreferenceRecord>asList( new PreferenceRecordImpl(oldRecord.getId(), Collections.<String, Object>singletonMap("name", "test2")), new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test3"))); _preferenceStore.updateOrCreate(records); _preferenceStore.close(); Collection<PreferenceRecord> recovered = _preferenceStore.openAndLoad(_updater); List<PreferenceRecord> expected = new ArrayList<>(records); expected.add(_testInitialRecords.get(1)); PreferenceTestHelper.assertRecords(expected, recovered); }
@Test public void testReplace() throws Exception { _preferenceStore.openAndLoad(_updater); PreferenceRecord oldRecord1 = _testInitialRecords.get(0); PreferenceRecord oldRecord2 = _testInitialRecords.get(1); Collection<UUID> recordsToRemove = Collections.singleton(oldRecord1.getId()); Collection<PreferenceRecord> recordsToAddUpdate = Arrays.<PreferenceRecord>asList( new PreferenceRecordImpl(oldRecord2.getId(), Collections.<String, Object>singletonMap("name", "test2")), new PreferenceRecordImpl(UUID.randomUUID(), Collections.<String, Object>singletonMap("name", "test3"))); _preferenceStore.replace(recordsToRemove, recordsToAddUpdate); _preferenceStore.close(); Collection<PreferenceRecord> recovered = _preferenceStore.openAndLoad(_updater); PreferenceTestHelper.assertRecords(recordsToAddUpdate, recovered); }
|
CompositeFilter extends Filter<ILoggingEvent> { public void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule) { Iterator<Filter<ILoggingEvent>> it = _filterList.iterator(); while(it.hasNext()) { Filter f = it.next(); if (f.getName().equals(logInclusionRule.getName())) { _filterList.remove(f); break; } } } void addLogInclusionRule(LogBackLogInclusionRule logInclusionRule); void removeLogInclusionRule(LogBackLogInclusionRule logInclusionRule); @Override FilterReply decide(ILoggingEvent event); long getErrorCount(); long getWarnCount(); }
|
@Test public void testRemoveLogInclusionRule() { CompositeFilter compositeFilter = new CompositeFilter(); LogBackLogInclusionRule neutral = createRule(FilterReply.NEUTRAL, "neutral"); compositeFilter.addLogInclusionRule(neutral); LogBackLogInclusionRule deny = createRule(FilterReply.DENY, "deny"); compositeFilter.addLogInclusionRule(deny); LogBackLogInclusionRule accept = createRule(FilterReply.ACCEPT, "accept"); compositeFilter.addLogInclusionRule(accept); FilterReply reply = compositeFilter.decide(mock(ILoggingEvent.class)); assertEquals("Unexpected reply", FilterReply.DENY, reply); compositeFilter.removeLogInclusionRule(deny); final ILoggingEvent loggingEvent = mock(ILoggingEvent.class); when(loggingEvent.getLevel()).thenReturn(Level.ERROR); FilterReply reply2 = compositeFilter.decide(loggingEvent); assertEquals("Unexpected reply", FilterReply.ACCEPT, reply2); verify(neutral.asFilter(), times(2)).decide(any(ILoggingEvent.class)); verify(deny.asFilter()).decide(any(ILoggingEvent.class)); verify(accept.asFilter()).decide(any(ILoggingEvent.class)); }
|
Exporter { public static ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility( objectMapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } private Exporter(); static Exporter of(Nitrite db); static Exporter of(Nitrite db, ObjectMapper objectMapper); static ObjectMapper createObjectMapper(); Exporter withOptions(ExportOptions options); void exportTo(String file); void exportTo(File file); void exportTo(OutputStream stream); void exportTo(Writer writer); }
|
@Test public void testCreateObjectMapper() { ObjectMapper actualCreateObjectMapperResult = Exporter.createObjectMapper(); DeserializationConfig deserializationConfig = actualCreateObjectMapperResult.getDeserializationConfig(); assertTrue(actualCreateObjectMapperResult .getSerializerFactory() instanceof com.fasterxml.jackson.databind.ser.BeanSerializerFactory); PolymorphicTypeValidator polymorphicTypeValidator = actualCreateObjectMapperResult.getPolymorphicTypeValidator(); assertTrue(polymorphicTypeValidator instanceof LaissezFaireSubTypeValidator); assertTrue(actualCreateObjectMapperResult .getDeserializationContext() instanceof com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.Impl); assertSame(actualCreateObjectMapperResult.getFactory(), actualCreateObjectMapperResult.getJsonFactory()); assertTrue(actualCreateObjectMapperResult .getSerializerProviderInstance() instanceof com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.Impl); VisibilityChecker<?> visibilityChecker = actualCreateObjectMapperResult.getVisibilityChecker(); assertTrue(visibilityChecker instanceof VisibilityChecker.Std); assertNull(actualCreateObjectMapperResult.getPropertyNamingStrategy()); assertTrue(actualCreateObjectMapperResult .getSerializerProvider() instanceof com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.Impl); SubtypeResolver subtypeResolver = actualCreateObjectMapperResult.getSubtypeResolver(); assertTrue(subtypeResolver instanceof StdSubtypeResolver); assertNull(deserializationConfig.getProblemHandlers()); assertSame(visibilityChecker, deserializationConfig.getDefaultVisibilityChecker()); assertTrue(deserializationConfig .getClassIntrospector() instanceof com.fasterxml.jackson.databind.introspect.BasicClassIntrospector); assertTrue(deserializationConfig.getTimeZone() instanceof sun.util.calendar.ZoneInfo); assertTrue(deserializationConfig.isAnnotationProcessingEnabled()); assertNull(deserializationConfig.getPropertyNamingStrategy()); TypeFactory expectedTypeFactory = actualCreateObjectMapperResult.getTypeFactory(); assertSame(expectedTypeFactory, deserializationConfig.getTypeFactory()); assertTrue(deserializationConfig.getAttributes() instanceof ContextAttributes.Impl); JsonNodeFactory expectedNodeFactory = actualCreateObjectMapperResult.getNodeFactory(); assertSame(expectedNodeFactory, deserializationConfig.getNodeFactory()); assertNull(deserializationConfig.getDefaultMergeable()); assertNull(deserializationConfig.getHandlerInstantiator()); assertSame(actualCreateObjectMapperResult.getDateFormat(), deserializationConfig.getDateFormat()); assertNull(deserializationConfig.getFullRootName()); assertNull(deserializationConfig.getActiveView()); assertEquals(237020288, deserializationConfig.getDeserializationFeatures()); assertSame(subtypeResolver, deserializationConfig.getSubtypeResolver()); assertTrue(deserializationConfig .getAnnotationIntrospector() instanceof com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector); assertSame(polymorphicTypeValidator, deserializationConfig.getPolymorphicTypeValidator()); }
|
ObjectUtils { @SuppressWarnings("rawtypes") public static boolean deepEquals(Object o1, Object o2) { if (o1 == null && o2 == null) { return true; } else if (o1 == null || o2 == null) { return false; } if (o1 == o2) { return true; } if (o1 instanceof Number && o2 instanceof Number) { if (o1.getClass() != o2.getClass()) { return false; } return Numbers.compare((Number) o1, (Number) o2) == 0; } else if (o1 instanceof Iterable && o2 instanceof Iterable) { Object[] arr1 = toArray((Iterable) o1); Object[] arr2 = toArray((Iterable) o2); return deepEquals(arr1, arr2); } else if (o1.getClass().isArray() && o2.getClass().isArray()) { int length = Array.getLength(o1); if (length != Array.getLength(o2)) { return false; } for (int i = 0; i < length; i++) { Object item1 = Array.get(o1, i); Object item2 = Array.get(o2, i); if (!deepEquals(item1, item2)) { return false; } } return true; } else if (o1 instanceof Map && o2 instanceof Map) { Map map1 = (Map) o1; Map map2 = (Map) o2; return deepEquals(toArray(map1.entrySet()), toArray(map2.entrySet())); } else { return o1.equals(o2); } } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test public void testDeepEquals() { assertFalse(ObjectUtils.deepEquals("o1", "o2")); assertFalse(ObjectUtils.deepEquals(null, "o2")); assertFalse(ObjectUtils.deepEquals(new AnnotatedMethodMap(), "o2")); assertTrue(ObjectUtils.deepEquals(null, null)); assertFalse(ObjectUtils.deepEquals(new MutableByte(), "o2")); assertFalse(ObjectUtils.deepEquals(new JUnit4TestAdapterCache(), "o2")); assertFalse(ObjectUtils.deepEquals("o1", null)); }
@Test public void testDeepEquals2() { CharArraySet makeStopSetResult = StopFilter.makeStopSet(new String[]{"foo", "foo", "foo"}, true); makeStopSetResult.add((Object) "foo"); assertFalse(ObjectUtils.deepEquals(makeStopSetResult, new AnnotatedMethodMap())); }
@Test public void testDeepEquals3() { MutableByte o1 = new MutableByte(); assertFalse(ObjectUtils.deepEquals(o1, new MutableDouble())); }
@Test public void testDeepEquals4() { JUnit4TestAdapterCache o1 = new JUnit4TestAdapterCache(); assertTrue(ObjectUtils.deepEquals(o1, new JUnit4TestAdapterCache())); }
@Test public void testDeepEquals5() { MutableByte o1 = new MutableByte(); assertTrue(ObjectUtils.deepEquals(o1, new MutableByte())); }
@Test public void testDeepEquals6() { CharArraySet makeStopSetResult = StopFilter.makeStopSet(new String[]{"foo", "foo", "foo"}, true); makeStopSetResult.add((Object) "foo"); CharArraySet makeStopSetResult1 = StopFilter.makeStopSet(new String[]{"foo", "foo", "foo"}, true); makeStopSetResult1.add((Object) "foo"); assertTrue(ObjectUtils.deepEquals(makeStopSetResult, makeStopSetResult1)); }
@Test public void testDeepEquals7() { AnnotatedMethodMap o1 = new AnnotatedMethodMap(); assertTrue(ObjectUtils.deepEquals(o1, new AnnotatedMethodMap())); }
@Test public void testDeepEquals8() { MutableByte o2 = new MutableByte((byte) 65); assertFalse(ObjectUtils.deepEquals(new MutableByte(), o2)); }
|
ObjectUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T newInstance(Class<T> type, boolean createSkeleton) { try { if (type.isPrimitive() || type.isArray() || type == String.class) { return defaultValue(type); } ObjectInstantiator instantiator = getInstantiatorOf(type); T item = (T) instantiator.newInstance(); if (createSkeleton) { Field[] fields = type.getDeclaredFields(); if (fields.length > 0) { for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers())) { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); if (isSkeletonRequired(type, field.getType())) { field.set(item, newInstance(field.getType(), true)); } else { field.set(item, defaultValue(field.getType())); } } } } } return item; } catch (Throwable e) { throw new ObjectMappingException("failed to instantiate type " + type.getName(), e); } } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test public void testNewInstance() { EnclosingType type = newInstance(EnclosingType.class, true); System.out.println(type); }
|
ObjectUtils { public static boolean isValueType(Class<?> retType) { if (retType.isPrimitive() && retType != void.class) return true; if (Number.class.isAssignableFrom(retType)) return true; if (Boolean.class == retType) return true; if (Character.class == retType) return true; if (String.class == retType) return true; if (byte[].class.isAssignableFrom(retType)) return true; return Enum.class.isAssignableFrom(retType); } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test public void testIsValueType() { assertFalse(ObjectUtils.isValueType(Object.class)); }
|
NitriteBuilder { public Nitrite openOrCreate() { this.nitriteConfig.autoConfigure(); return new NitriteDatabase(nitriteConfig); } NitriteBuilder(); NitriteBuilder fieldSeparator(String separator); NitriteBuilder loadModule(NitriteModule module); NitriteBuilder addMigrations(Migration... migrations); NitriteBuilder schemaVersion(Integer version); Nitrite openOrCreate(); Nitrite openOrCreate(String username, String password); }
|
@Test public void testOpenOrCreate() { Nitrite actualOpenOrCreateResult = Nitrite.builder().openOrCreate("janedoe", "iloveyou"); PluginManager pluginManager = actualOpenOrCreateResult.getConfig().getPluginManager(); NitriteStore<?> store = actualOpenOrCreateResult.getStore(); assertFalse(actualOpenOrCreateResult.isClosed()); assertFalse(store.isClosed()); assertSame(store, pluginManager.getNitriteStore()); assertTrue(pluginManager.getNitriteMapper() instanceof org.dizitart.no2.mapper.MappableMapper); }
@Test(expected = SecurityException.class) public void testOpenOrCreate2() { NitriteBuilder builderResult = Nitrite.builder(); builderResult.openOrCreate("", "iloveyou"); NitriteConfig nitriteConfig = builderResult.getNitriteConfig(); PluginManager pluginManager = nitriteConfig.getPluginManager(); NitriteStore<?> nitriteStore = nitriteConfig.getNitriteStore(); assertFalse(nitriteStore.isClosed()); assertSame(nitriteStore, pluginManager.getNitriteStore()); assertTrue(pluginManager.getNitriteMapper() instanceof org.dizitart.no2.mapper.MappableMapper); }
@Test(expected = SecurityException.class) public void testOpenOrCreateNullPassword() { NitriteBuilder builder = Nitrite.builder(); builder.openOrCreate("abcd", null); }
@Test public void testConfigWithFile() { db = Nitrite.builder() .openOrCreate(); StoreConfig storeConfig = db.getStore().getStoreConfig(); assertTrue(storeConfig.isInMemory()); assertTrue(isNullOrEmpty(storeConfig.filePath())); NitriteCollection test = db.getCollection("test"); assertNotNull(test); db.commit(); db.close(); }
@Test public void testConfigWithFileNull() { db = Nitrite.builder().openOrCreate(); StoreConfig storeConfig = db.getStore().getStoreConfig(); assertTrue(storeConfig.isInMemory()); assertTrue(isNullOrEmpty(storeConfig.filePath())); NitriteCollection test = db.getCollection("test"); assertNotNull(test); db.commit(); db.close(); }
@Test(expected = SecurityException.class) public void testOpenOrCreateNullUserId() { NitriteBuilder builder = Nitrite.builder(); builder.openOrCreate(null, "abcd"); }
|
ObjectUtils { public static boolean isCompatibleTypes(Class<?> type1, Class<?> type2) { if (type1.equals(type2)) return true; if (type1.isAssignableFrom(type2)) return true; if (type1.isPrimitive()) { Class<?> wrapperType = toWrapperType(type1); return isCompatibleTypes(wrapperType, type2); } else if (type2.isPrimitive()) { Class<?> wrapperType = toWrapperType(type2); return isCompatibleTypes(type1, wrapperType); } return false; } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test public void testIsCompatibleTypes() { Class<?> type1 = Object.class; assertTrue(ObjectUtils.isCompatibleTypes(type1, Object.class)); }
|
ObjectUtils { @SuppressWarnings("unchecked") public static <T extends Serializable> T deepCopy(T oldObj) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(oldObj); oos.flush(); try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) { return (T) ois.readObject(); } } catch (IOException | ClassNotFoundException e) { throw new NitriteIOException("error while deep copying object", e); } } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test public void testDeepCopy() { assertNull(ObjectUtils.deepCopy(null)); assertEquals(NitriteId.createId("42"), ObjectUtils.deepCopy(NitriteId.createId("42"))); assertNotEquals(NitriteId.createId("41"), ObjectUtils.deepCopy(NitriteId.createId("42"))); assertEquals(Document.createDocument("foo", "foo"), ObjectUtils.deepCopy(Document.createDocument("foo", "foo"))); assertNotEquals(this, ObjectUtils.deepCopy(this)); }
|
ObjectUtils { public static <T> String getEntityName(Class<T> type) { if (type.isAnnotationPresent(Entity.class)) { Entity entity = type.getAnnotation(Entity.class); String name = entity.value(); if (name.contains(KEY_OBJ_SEPARATOR)) { throw new ValidationException(name + " is not a valid entity name"); } if (!StringUtils.isNullOrEmpty(name)) { return entity.value(); } } return type.getName(); } private ObjectUtils(); static String getEntityName(Class<T> type); static String findRepositoryName(Class<T> type, String key); static String findRepositoryName(String entityName, String key); static String getKeyName(String collectionName); static String getKeyedRepositoryType(String collectionName); @SuppressWarnings("rawtypes") static boolean deepEquals(Object o1, Object o2); @SuppressWarnings({"unchecked", "rawtypes"}) static T newInstance(Class<T> type, boolean createSkeleton); static boolean isValueType(Class<?> retType); static boolean isCompatibleTypes(Class<?> type1, Class<?> type2); static Object[] convertToObjectArray(Object array); static int compare(T c1, T c2); @SuppressWarnings("unchecked") static T deepCopy(T oldObj); }
|
@Test(expected = ValidationException.class) public void testInvalidEntity1() { ObjectUtils.getEntityName(InvalidEntity1.class); }
@Test(expected = ValidationException.class) public void testInvalidEntity2() { ObjectUtils.getEntityName(InvalidEntity2.class); }
@Test public void testValidEntity() { assertEquals("org.dizitart.no2.common.util.ObjectUtilsTest$ValidEntity3", ObjectUtils.getEntityName(ValidEntity3.class)); assertEquals("org.dizitart.no2.common.util.ObjectUtilsTest$ValidEntity4", ObjectUtils.getEntityName(ValidEntity4.class)); assertEquals("org.dizitart.no2.common.util.ObjectUtilsTest$ValidEntity5", ObjectUtils.getEntityName(ValidEntity5.class)); assertEquals("a-b", ObjectUtils.getEntityName(ValidEntity6.class)); }
@Test public void testGetEntityName() { assertEquals("java.lang.Object", ObjectUtils.getEntityName(Object.class)); }
|
Numbers { public static int compare(Number x, Number y) { if (isSpecial(x) || isSpecial(y)) { return Double.compare(x.doubleValue(), y.doubleValue()); } else { return toBigDecimal(x).compareTo(toBigDecimal(y)); } } private Numbers(); static int compare(Number x, Number y); static Object castNumber(Object value, Class<?> type); }
|
@Test public void testCompare() { assertEquals(compare(x, y), result); }
@Test public void testCompare2() { Integer x = new Integer(1); assertEquals(0, Numbers.compare(x, new Integer(1))); }
|
DocumentUtils { public static boolean isRecent(Document recent, Document older) { if (Objects.deepEquals(recent.getRevision(), older.getRevision())) { return recent.getLastModifiedSinceEpoch() >= older.getLastModifiedSinceEpoch(); } return recent.getRevision() > older.getRevision(); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }
|
@Test public void testIsRecent() throws InterruptedException { Document first = createDocument("key1", "value1"); Thread.sleep(500); Document second = createDocument("key1", "value2"); assertTrue(isRecent(second, first)); second = first.clone(); second.put(DOC_REVISION, 1); first.put("key2", "value3"); first.put(DOC_REVISION, 2); assertTrue(isRecent(first, second)); }
@Test public void testIsRecent2() { Document recent = Document.createDocument(); assertTrue(DocumentUtils.isRecent(recent, Document.createDocument())); }
|
DocumentUtils { public static Filter createUniqueFilter(Document document) { return Filter.byId(document.getId()); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }
|
@Test public void testCreateUniqueFilter() { Document doc = createDocument("score", 1034) .put("location", createDocument("state", "NY") .put("city", "New York") .put("address", createDocument("line1", "40") .put("line2", "ABC Street") .put("house", new String[]{"1", "2", "3"}))) .put("category", new String[]{"food", "produce", "grocery"}) .put("objArray", new Document[]{createDocument("value", 1), createDocument("value", 2)}); doc.getId(); Filter filter = createUniqueFilter(doc); assertNotNull(filter); assertTrue(filter instanceof IndexAwareFilter); }
|
DocumentUtils { public static <T> Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type) { if (nitriteMapper.isValueType(type)) { return Document.createDocument(); } T dummy = newInstance(type, true); Document document = nitriteMapper.convert(dummy, Document.class); return removeValues(document); } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }
|
@Test public void testSkeletonDocument() { Class type = Object.class; assertNull(DocumentUtils.skeletonDocument(new NitriteBuilderTest.CustomNitriteMapper(), type)); }
@Test public void testSkeletonDocument2() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper nitriteMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); assertEquals(0, DocumentUtils.skeletonDocument(nitriteMapper, Object.class).size()); }
@Test public void testDummyDocument() { NitriteMapper nitriteMapper = new MappableMapper(); Document document = skeletonDocument(nitriteMapper, DummyTest.class); assertTrue(document.containsKey("first")); assertTrue(document.containsKey("second")); assertNull(document.get("first")); assertNull(document.get("second")); }
|
DocumentUtils { public static boolean isSimilar(Document document, Document other, String... fields) { boolean result = true; if (document == null && other != null) return false; if (document != null && other == null) return false; if (document == null) return true; for (String field : fields) { result = result && Objects.deepEquals(document.get(field), other.get(field)); } return result; } private DocumentUtils(); static boolean isRecent(Document recent, Document older); static Filter createUniqueFilter(Document document); static Document skeletonDocument(NitriteMapper nitriteMapper, Class<T> type); static boolean isSimilar(Document document, Document other, String... fields); }
|
@Test public void testIsSimilar() { assertFalse(DocumentUtils.isSimilar(null, Document.createDocument(), "fields")); assertFalse(DocumentUtils.isSimilar(null, Document.createDocument(), (String) null)); assertTrue(DocumentUtils.isSimilar(null, null, "fields")); assertFalse(DocumentUtils.isSimilar(Document.createDocument(), null, "fields")); }
@Test public void testIsSimilar2() { Document document = Document.createDocument(); assertTrue(DocumentUtils.isSimilar(document, Document.createDocument(), "fields")); }
|
ThreadPoolManager { public static ExecutorService getThreadPool(int size, String threadName) { ExecutorService threadPool = Executors.newFixedThreadPool(size, threadFactory(threadName)); threadPools.add(threadPool); return threadPool; } static ExecutorService workerPool(); static ExecutorService getThreadPool(int size, String threadName); static ErrorAwareThreadFactory threadFactory(String name); static void runAsync(Runnable runnable); static void shutdownThreadPools(); }
|
@Test public void testGetThreadPool() { assertTrue(ThreadPoolManager.getThreadPool(3, "threadName") instanceof java.util.concurrent.ThreadPoolExecutor); }
|
LockService { public synchronized Lock getReadLock(String name) { if (lockRegistry.containsKey(name)) { ReentrantReadWriteLock rwLock = lockRegistry.get(name); return rwLock.readLock(); } ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); lockRegistry.put(name, rwLock); return rwLock.readLock(); } LockService(); synchronized Lock getReadLock(String name); synchronized Lock getWriteLock(String name); }
|
@Test public void testGetReadLock() { assertTrue( (new LockService()).getReadLock("name") instanceof java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock); }
|
LockService { public synchronized Lock getWriteLock(String name) { if (lockRegistry.containsKey(name)) { ReentrantReadWriteLock rwLock = lockRegistry.get(name); return rwLock.writeLock(); } ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); lockRegistry.put(name, rwLock); return rwLock.writeLock(); } LockService(); synchronized Lock getReadLock(String name); synchronized Lock getWriteLock(String name); }
|
@Test public void testGetWriteLock() { assertTrue((new LockService()) .getWriteLock("name") instanceof java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock); }
|
NotEqualsFilter extends IndexAwareFilter { @Override @SuppressWarnings("rawtypes") protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getValue() == null || getValue() instanceof Comparable) { if (getIndexer() instanceof ComparableIndexer) { ComparableIndexer comparableIndexer = (ComparableIndexer) getIndexer(); idSet = comparableIndexer.findNotEqual(getCollectionName(), getField(), (Comparable) getValue()); } else if (getIndexer() instanceof TextIndexer && getValue() instanceof String) { setIsFieldIndexed(false); } else { throw new FilterException("notEq filter is not supported on indexed field " + getField()); } } else { throw new FilterException(getValue() + " is not comparable"); } } return idSet; } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testFindIndexedIdSet() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", null); notEqualsFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> notEqualsFilter.findIndexedIdSet()); }
@Test public void testFindIndexedIdSet2() { assertEquals(0, (new NotEqualsFilter("field", "value")).findIndexedIdSet().size()); }
|
NotEqualsFilter extends IndexAwareFilter { @Override protected Set<NitriteId> findIdSet(NitriteMap<NitriteId, Document> collection) { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getOnIdField() && getValue() instanceof String) { NitriteId nitriteId = NitriteId.createId((String) getValue()); if (!collection.containsKey(nitriteId)) { idSet.add(nitriteId); } } return idSet; } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testFindIdSet() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); assertEquals(0, notEqualsFilter.findIdSet(new InMemoryMap<NitriteId, Document>("mapName", null)).size()); }
@Test public void testFindIdSet2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setOnIdField(true); assertEquals(0, notEqualsFilter.findIdSet(new InMemoryMap<>("mapName", null)).size()); assertTrue(notEqualsFilter.getValue() instanceof Integer); }
@Test(expected = InvalidIdException.class) public void testFindIdSet3() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setOnIdField(true); notEqualsFilter.findIdSet(new InMemoryMap<>("mapName", null)); assertTrue(notEqualsFilter.getValue() instanceof String); }
|
NotEqualsFilter extends IndexAwareFilter { @Override public boolean apply(Pair<NitriteId, Document> element) { Document document = element.getSecond(); Object fieldValue = document.get(getField()); return !deepEquals(fieldValue, getValue()); } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testApply() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); NitriteId first = NitriteId.newId(); assertTrue(notEqualsFilter.apply(new Pair<>(first, Document.createDocument()))); assertTrue(notEqualsFilter.getValue() instanceof String); }
@Test public void testApply2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); Pair<NitriteId, Document> pair = new Pair<>(); pair.setSecond(Document.createDocument()); assertTrue(notEqualsFilter.apply(pair)); assertTrue(notEqualsFilter.getValue() instanceof String); }
|
NotEqualsFilter extends IndexAwareFilter { @Override public void setIsFieldIndexed(Boolean isFieldIndexed) { if (!(getIndexer() instanceof TextIndexer && getValue() instanceof String)) { super.setIsFieldIndexed(isFieldIndexed); } } protected NotEqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testSetIsFieldIndexed() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setIndexer(new NitriteTextIndexer()); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getValue() instanceof Integer); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed2() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", 42); notEqualsFilter.setObjectFilter(true); notEqualsFilter.setIndexer(null); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed3() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed4() { NotEqualsFilter notEqualsFilter = new NotEqualsFilter("field", "value"); notEqualsFilter.setIndexer(new NitriteTextIndexer()); notEqualsFilter.setIsFieldIndexed(true); assertTrue(notEqualsFilter.getValue() instanceof String); }
|
RegexFilter extends FieldBasedFilter { @Override public boolean apply(Pair<NitriteId, Document> element) { Document document = element.getSecond(); Object fieldValue = document.get(getField()); if (fieldValue != null) { if (fieldValue instanceof String) { Matcher matcher = pattern.matcher((String) fieldValue); if (matcher.find()) { return true; } matcher.reset(); } else { throw new FilterException(getField() + " does not contain string value"); } } return false; } RegexFilter(String field, String value); @Override boolean apply(Pair<NitriteId, Document> element); }
|
@Test public void testApply() { RegexFilter regexFilter = new RegexFilter("field", "value"); Pair<NitriteId, Document> pair = new Pair<NitriteId, Document>(); pair.setSecond(Document.createDocument()); assertFalse(regexFilter.apply(pair)); }
@Test public void testApply2() { RegexFilter regexFilter = new RegexFilter("field", "value"); NitriteId first = NitriteId.newId(); assertFalse(regexFilter.apply(new Pair<NitriteId, Document>(first, Document.createDocument()))); }
|
NitriteBuilder { public NitriteBuilder fieldSeparator(String separator) { this.nitriteConfig.fieldSeparator(separator); return this; } NitriteBuilder(); NitriteBuilder fieldSeparator(String separator); NitriteBuilder loadModule(NitriteModule module); NitriteBuilder addMigrations(Migration... migrations); NitriteBuilder schemaVersion(Integer version); Nitrite openOrCreate(); Nitrite openOrCreate(String username, String password); }
|
@Test public void testFieldSeparator() { db = Nitrite.builder() .fieldSeparator("::") .openOrCreate(); Document document = createDocument("firstName", "John") .put("colorCodes", new Document[]{createDocument("color", "Red"), createDocument("color", "Green")}) .put("address", createDocument("street", "ABCD Road")); String street = document.get("address::street", String.class); assertEquals("ABCD Road", street); street = document.get("address.street", String.class); assertNull(street); assertEquals(document.get("colorCodes::1::color"), "Green"); }
|
FluentFilter { public Filter eq(Object value) { return new EqualsFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }
|
@Test public void testEq() { assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getOnIdField()); assertTrue(((EqualsFilter) FluentFilter.where("field").eq("value")).getValue() instanceof String); assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getObjectFilter()); assertFalse(((EqualsFilter) FluentFilter.where("field").eq("value")).getIsFieldIndexed()); assertEquals("field", ((EqualsFilter) FluentFilter.where("field").eq("value")).getField()); }
|
FluentFilter { public Filter notEq(Object value) { return new NotEqualsFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }
|
@Test public void testNotEq() { assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getOnIdField()); assertTrue(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getValue() instanceof String); assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getObjectFilter()); assertFalse(((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getIsFieldIndexed()); assertEquals("field", ((NotEqualsFilter) FluentFilter.where("field").notEq("value")).getField()); }
|
FluentFilter { public Filter text(String value) { return new TextFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }
|
@Test public void testText() { assertEquals("value", ((TextFilter) FluentFilter.where("field").text("value")).getStringValue()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getOnIdField()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getObjectFilter()); assertFalse(((TextFilter) FluentFilter.where("field").text("value")).getIsFieldIndexed()); assertEquals("field", ((TextFilter) FluentFilter.where("field").text("value")).getField()); }
|
FluentFilter { public Filter regex(String value) { return new RegexFilter(field, value); } private FluentFilter(); static FluentFilter where("$"); static FluentFilter where(String field); Filter eq(Object value); Filter notEq(Object value); Filter gt(Comparable<?> value); Filter gte(Comparable<?> value); Filter lt(Comparable<?> value); Filter lte(Comparable<?> value); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean inclusive); Filter between(Comparable<?> lowerBound, Comparable<?> upperBound, boolean lowerInclusive, boolean upperInclusive); Filter text(String value); Filter regex(String value); Filter in(Comparable<?>... values); Filter notIn(Comparable<?>... values); Filter elemMatch(Filter filter); }
|
@Test public void testRegex() { assertEquals("field", ((RegexFilter) FluentFilter.where("field").regex("value")).getField()); assertFalse(((RegexFilter) FluentFilter.where("field").regex("value")).getObjectFilter()); assertEquals("FieldBasedFilter(field=field, value=value, processed=true)", ((RegexFilter) FluentFilter.where("field").regex("value")).toString()); }
|
TextFilter extends StringFilter { @Override protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getIndexer() instanceof TextIndexer) { TextIndexer textIndexer = (TextIndexer) getIndexer(); idSet = textIndexer.findText(getCollectionName(), getField(), getStringValue()); } else { throw new FilterException(getField() + " is not full-text indexed"); } } return idSet; } TextFilter(String field, String value); @Override boolean apply(Pair<NitriteId, Document> element); }
|
@Test public void testFindIndexedIdSet() { assertEquals(0, (new TextFilter("field", "value")).findIndexedIdSet().size()); }
@Test public void testFindIndexedIdSet2() { TextFilter textFilter = new TextFilter("field", "value"); textFilter.setIndexer(null); textFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> textFilter.findIndexedIdSet()); }
@Test public void testFindIndexedIdSet3() { TextFilter textFilter = new TextFilter("field", "value"); textFilter.setIsFieldIndexed(true); assertThrows(FilterException.class, () -> textFilter.findIndexedIdSet()); }
|
EqualsFilter extends IndexAwareFilter { @Override @SuppressWarnings("rawtypes") protected Set<NitriteId> findIndexedIdSet() { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getIsFieldIndexed()) { if (getValue() == null || getValue() instanceof Comparable) { if (getIndexer() instanceof ComparableIndexer) { ComparableIndexer comparableIndexer = (ComparableIndexer) getIndexer(); idSet = comparableIndexer.findEqual(getCollectionName(), getField(), (Comparable) getValue()); } else if (getIndexer() instanceof TextIndexer && getValue() instanceof String) { setIsFieldIndexed(false); } else { throw new FilterException("eq filter is not supported on indexed field " + getField()); } } else { throw new FilterException(getValue() + " is not comparable"); } } return idSet; } EqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testFindIndexedIdSet() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); equalsFilter.setIndexer(new NitriteTextIndexer()); equalsFilter.setIsFieldIndexed(null); assertEquals(0, equalsFilter.findIndexedIdSet().size()); }
@Test public void testFindIndexedIdSet6() { assertEquals(0, (new EqualsFilter("field", "value")).findIndexedIdSet().size()); }
|
MappableMapper implements NitriteMapper { @Override @SuppressWarnings("unchecked") public <Source, Target> Target convert(Source source, Class<Target> type) { if (source == null) { return null; } if (isValue(source)) { return (Target) source; } else { if (Document.class.isAssignableFrom(type)) { return (Target) convertToDocument(source); } else if (source instanceof Document) { return convertFromDocument((Document) source, type); } } throw new ObjectMappingException("object must implements Mappable"); } MappableMapper(Class<?>... valueTypes); @Override @SuppressWarnings("unchecked") Target convert(Source source, Class<Target> type); @Override boolean isValueType(Class<?> type); @Override boolean isValue(Object object); @Override void initialize(NitriteConfig nitriteConfig); }
|
@Test public void testConvert() { MappableMapper mappableMapper = new MappableMapper(null); assertEquals(0, ((Integer) mappableMapper.<Object, Object>convert(0, Object.class)).intValue()); }
@Test public void testConvert2() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper mappableMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); assertEquals("source", mappableMapper.<Object, Object>convert("source", Object.class)); }
@Test public void testConvert3() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper mappableMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); assertEquals(0, ((Integer) mappableMapper.<Object, Object>convert(0, Object.class)).intValue()); }
|
EqualsFilter extends IndexAwareFilter { @Override protected Set<NitriteId> findIdSet(NitriteMap<NitriteId, Document> collection) { Set<NitriteId> idSet = new LinkedHashSet<>(); if (getOnIdField() && getValue() instanceof String) { NitriteId nitriteId = NitriteId.createId((String) getValue()); if (collection.containsKey(nitriteId)) { idSet.add(nitriteId); } } return idSet; } EqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testFindIdSet() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); assertEquals(0, equalsFilter.findIdSet(new InMemoryMap<NitriteId, Document>("mapName", null)).size()); }
@Test(expected = InvalidIdException.class) public void testFindIdSet2() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); equalsFilter.setOnIdField(true); equalsFilter.findIdSet(new InMemoryMap<>("mapName", null)); assertTrue(equalsFilter.getValue() instanceof String); }
@Test public void testFindIdSet3() { EqualsFilter equalsFilter = new EqualsFilter("field", 42); equalsFilter.setOnIdField(true); assertEquals(0, equalsFilter.findIdSet(new InMemoryMap<NitriteId, Document>("mapName", null)).size()); assertTrue(equalsFilter.getValue() instanceof Integer); }
|
EqualsFilter extends IndexAwareFilter { @Override public boolean apply(Pair<NitriteId, Document> element) { Document document = element.getSecond(); Object fieldValue = document.get(getField()); return deepEquals(fieldValue, getValue()); } EqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testApply() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); Pair<NitriteId, Document> pair = new Pair<NitriteId, Document>(); pair.setSecond(Document.createDocument()); assertFalse(equalsFilter.apply(pair)); assertTrue(equalsFilter.getValue() instanceof String); }
@Test public void testApply2() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); NitriteId first = NitriteId.newId(); assertFalse(equalsFilter.apply(new Pair<NitriteId, Document>(first, Document.createDocument()))); assertTrue(equalsFilter.getValue() instanceof String); }
|
EqualsFilter extends IndexAwareFilter { @Override public void setIsFieldIndexed(Boolean isFieldIndexed) { if (!(getIndexer() instanceof TextIndexer && getValue() instanceof String)) { super.setIsFieldIndexed(isFieldIndexed); } } EqualsFilter(String field, Object value); @Override boolean apply(Pair<NitriteId, Document> element); @Override void setIsFieldIndexed(Boolean isFieldIndexed); }
|
@Test public void testSetIsFieldIndexed() { EqualsFilter equalsFilter = new EqualsFilter("field", "value"); equalsFilter.setIsFieldIndexed(true); assertTrue(equalsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed2() { EqualsFilter equalsFilter = new EqualsFilter("field", 42); equalsFilter.setObjectFilter(true); equalsFilter.setIndexer(null); equalsFilter.setIsFieldIndexed(true); assertTrue(equalsFilter.getIsFieldIndexed()); }
@Test public void testSetIsFieldIndexed3() { EqualsFilter equalsFilter = new EqualsFilter("field", 42); equalsFilter.setIndexer(new NitriteTextIndexer()); equalsFilter.setIsFieldIndexed(true); assertTrue(equalsFilter.getValue() instanceof Integer); assertTrue(equalsFilter.getIsFieldIndexed()); }
|
UpdateOptions { public static UpdateOptions updateOptions(boolean insertIfAbsent) { UpdateOptions options = new UpdateOptions(); options.setInsertIfAbsent(insertIfAbsent); return options; } static UpdateOptions updateOptions(boolean insertIfAbsent); static UpdateOptions updateOptions(boolean insertIfAbsent, boolean justOnce); }
|
@Test public void testUpdateOptions() { UpdateOptions actualUpdateOptionsResult = UpdateOptions.updateOptions(true, true); assertTrue(actualUpdateOptionsResult.isInsertIfAbsent()); assertTrue(actualUpdateOptionsResult.isJustOnce()); }
@Test public void testUpdateOptions2() { assertTrue(UpdateOptions.updateOptions(true).isInsertIfAbsent()); }
|
CollectionFactory { public NitriteCollection getCollection(String name, NitriteConfig nitriteConfig, boolean writeCatalogue) { notNull(nitriteConfig, "configuration is null while creating collection"); notEmpty(name, "collection name is null or empty"); Lock lock = lockService.getWriteLock(this.getClass().getName()); try { lock.lock(); if (collectionMap.containsKey(name)) { NitriteCollection collection = collectionMap.get(name); if (collection.isDropped() || !collection.isOpen()) { collectionMap.remove(name); return createCollection(name, nitriteConfig, writeCatalogue); } return collectionMap.get(name); } else { return createCollection(name, nitriteConfig, writeCatalogue); } } finally { lock.unlock(); } } CollectionFactory(LockService lockService); NitriteCollection getCollection(String name, NitriteConfig nitriteConfig, boolean writeCatalogue); void clear(); }
|
@Test(expected = ValidationException.class) public void testGetCollectionMapStoreNull() { CollectionFactory factory = new CollectionFactory(new LockService()); assertNotNull(factory); NitriteConfig config = new NitriteConfig(); factory.getCollection(null, config, true); }
@Test(expected = ValidationException.class) public void testGetCollectionContextNull() { CollectionFactory factory = new CollectionFactory(new LockService()); factory.getCollection("test", null, false); }
|
WriteOperations { WriteResult update(Filter filter, Document update, UpdateOptions updateOptions) { DocumentCursor cursor; if (filter == null || filter == Filter.ALL) { cursor = readOperations.find(); } else { cursor = readOperations.find(filter); } WriteResultImpl writeResult = new WriteResultImpl(); Document document = update.clone(); document.remove(DOC_ID); if (!REPLICATOR.contentEquals(document.getSource())) { document.remove(DOC_REVISION); } if (document.size() == 0) { alert(EventType.Update, new CollectionEventInfo<>()); return writeResult; } long count = 0; for (Document doc : cursor) { if (doc != null) { count++; if (count > 1 && updateOptions.isJustOnce()) { break; } Document item = doc.clone(); Document oldDocument = doc.clone(); String source = document.getSource(); long time = System.currentTimeMillis(); NitriteId nitriteId = item.getId(); log.debug("Document to update {} in {}", item, nitriteMap.getName()); if (!REPLICATOR.contentEquals(document.getSource())) { document.remove(DOC_SOURCE); item.merge(document); int rev = item.getRevision(); item.put(DOC_REVISION, rev + 1); item.put(DOC_MODIFIED, time); } else { document.remove(DOC_SOURCE); item.merge(document); } nitriteMap.put(nitriteId, item); log.debug("Document {} updated in {}", item, nitriteMap.getName()); if (document.size() > 0) { writeResult.addToList(nitriteId); } indexOperations.updateIndex(oldDocument, item, nitriteId); CollectionEventInfo<Document> eventInfo = new CollectionEventInfo<>(); Document eventDoc = item.clone(); eventInfo.setItem(eventDoc); eventInfo.setEventType(EventType.Update); eventInfo.setTimestamp(time); eventInfo.setOriginator(source); alert(EventType.Update, eventInfo); } } if (count == 0) { log.debug("No document found to update by the filter {} in {}", filter, nitriteMap.getName()); if (updateOptions.isInsertIfAbsent()) { return insert(update); } else { return writeResult; } } log.debug("Filter {} updated total {} document(s) with options {} in {}", filter, count, updateOptions, nitriteMap.getName()); log.debug("Returning write result {} for collection {}", writeResult, nitriteMap.getName()); return writeResult; } WriteOperations(IndexOperations indexOperations,
ReadOperations readOperations,
NitriteMap<NitriteId, Document> nitriteMap,
EventBus<CollectionEventInfo<?>, CollectionEventListener> eventBus); WriteResult remove(Document document); }
|
@Test public void testUpdate() { InMemoryMap<NitriteId, Document> nitriteMap = new InMemoryMap<NitriteId, Document>("mapName", null); ReadOperations readOperations = new ReadOperations("collectionName", new NitriteConfig(), nitriteMap, null); WriteOperations writeOperations = new WriteOperations(null, readOperations, new InMemoryMap<NitriteId, Document>("mapName", null), null); UpdateOptions updateOptions = UpdateOptions.updateOptions(true); assertTrue(writeOperations.update(null, Document.createDocument(), updateOptions) instanceof WriteResultImpl); }
|
WriteOperations { WriteResult remove(Filter filter, boolean justOnce) { DocumentCursor cursor; if (filter == null || filter == Filter.ALL) { cursor = readOperations.find(); } else { cursor = readOperations.find(filter); } WriteResultImpl result = new WriteResultImpl(); long count = 0; for (Document document : cursor) { if (document != null) { count++; Document item = document.clone(); CollectionEventInfo<Document> eventInfo = removeAndCreateEvent(item, result); if (eventInfo != null) { alert(EventType.Remove, eventInfo); } if (justOnce) { break; } } } if (count == 0) { log.debug("No document found to remove by the filter {} in {}", filter, nitriteMap.getName()); return result; } log.debug("Filter {} removed total {} document(s) with options {} from {}", filter, count, justOnce, nitriteMap.getName()); log.debug("Returning write result {} for collection {}", result, nitriteMap.getName()); return result; } WriteOperations(IndexOperations indexOperations,
ReadOperations readOperations,
NitriteMap<NitriteId, Document> nitriteMap,
EventBus<CollectionEventInfo<?>, CollectionEventListener> eventBus); WriteResult remove(Document document); }
|
@Test public void testRemove() { InMemoryMap<NitriteId, Document> nitriteMap = new InMemoryMap<NitriteId, Document>("mapName", null); ReadOperations readOperations = new ReadOperations("collectionName", new NitriteConfig(), nitriteMap, null); assertTrue((new WriteOperations(null, readOperations, new InMemoryMap<NitriteId, Document>("mapName", null), null)) .remove(null, true) instanceof WriteResultImpl); }
|
ReadOperations { public DocumentCursor find() { RecordStream<Pair<NitriteId, Document>> recordStream = nitriteMap.entries(); return new DocumentCursorImpl(recordStream); } ReadOperations(String collectionName,
NitriteConfig nitriteConfig,
NitriteMap<NitriteId, Document> nitriteMap,
IndexOperations indexOperations); DocumentCursor find(); DocumentCursor find(Filter filter); }
|
@Test public void testFind() { InMemoryMap<NitriteId, Document> nitriteMap = new InMemoryMap<NitriteId, Document>("mapName", null); assertTrue((new ReadOperations("collectionName", new NitriteConfig(), nitriteMap, null)).find().isEmpty()); }
@Test public void testFind2() { InMemoryMap<NitriteId, Document> nitriteMap = new InMemoryMap<NitriteId, Document>("mapName", null); assertTrue((new ReadOperations("collectionName", new NitriteConfig(), nitriteMap, null)).find(null).isEmpty()); }
|
ReadOperations { Document getById(NitriteId nitriteId) { return nitriteMap.get(nitriteId); } ReadOperations(String collectionName,
NitriteConfig nitriteConfig,
NitriteMap<NitriteId, Document> nitriteMap,
IndexOperations indexOperations); DocumentCursor find(); DocumentCursor find(Filter filter); }
|
@Test public void testGetById() { InMemoryMap<NitriteId, Document> nitriteMap = new InMemoryMap<NitriteId, Document>("mapName", null); ReadOperations readOperations = new ReadOperations("collectionName", new NitriteConfig(), nitriteMap, null); assertNull(readOperations.getById(NitriteId.newId())); }
|
SortedDocumentCursor implements RecordStream<Pair<NitriteId, Document>> { @Override public Iterator<Pair<NitriteId, Document>> iterator() { Iterator<Pair<NitriteId, Document>> iterator = recordStream == null ? Collections.emptyIterator() : recordStream.iterator(); return new SortedDocumentIterator(field, sortOrder, collator, nullOrder, iterator); } SortedDocumentCursor(String field,
SortOrder sortOrder,
Collator collator,
NullOrder nullOrder,
RecordStream<Pair<NitriteId, Document>> recordStream); @Override Iterator<Pair<NitriteId, Document>> iterator(); }
|
@Test public void testIterator() { assertFalse( (new SortedDocumentCursor("field", SortOrder.Ascending, null, NullOrder.First, null)).iterator().hasNext()); }
@Test public void testIterator2() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); assertFalse((new SortedDocumentCursor("field", SortOrder.Ascending, null, NullOrder.First, new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())))).iterator().hasNext()); }
|
UnionStreamIterator implements Iterator<Pair<NitriteId, Document>> { @Override public boolean hasNext() { return nextItemSet || setNextEntry(); } UnionStreamIterator(RecordStream<Pair<NitriteId, Document>> lhsStream,
RecordStream<Pair<NitriteId, Document>> rhsStream); @Override boolean hasNext(); @Override Pair<NitriteId, Document> next(); }
|
@Test public void testHasNext() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); FilteredRecordStream lhsStream = new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())); FilteredRecordStream recordStream2 = new FilteredRecordStream(null, null); FilteredRecordStream recordStream3 = new FilteredRecordStream(recordStream2, Filter.byId(NitriteId.newId())); assertFalse( (new UnionStreamIterator(lhsStream, new FilteredRecordStream(recordStream3, Filter.byId(NitriteId.newId())))) .hasNext()); }
|
FilteredRecordStream implements RecordStream<Pair<NitriteId, Document>> { @Override public Iterator<Pair<NitriteId, Document>> iterator() { Iterator<Pair<NitriteId, Document>> iterator = recordStream == null ? Collections.emptyIterator() : recordStream.iterator(); return new FilteredIterator(iterator, filter); } FilteredRecordStream(RecordStream<Pair<NitriteId, Document>> recordStream, Filter filter); @Override Iterator<Pair<NitriteId, Document>> iterator(); }
|
@Test public void testIterator() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); FilteredRecordStream recordStream2 = new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())); assertTrue((new FilteredRecordStream(recordStream2, Filter.byId(NitriteId.newId()))) .iterator() instanceof FilteredRecordStream.FilteredIterator); }
|
JoinedDocumentStream implements RecordStream<Document> { @Override public String toString() { return toList().toString(); } JoinedDocumentStream(RecordStream<Pair<NitriteId, Document>> recordStream,
DocumentCursor foreignCursor,
Lookup lookup); @Override Iterator<Document> iterator(); @Override String toString(); }
|
@Test public void testToString() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); FilteredRecordStream recordStream2 = new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())); FilteredRecordStream recordStream3 = new FilteredRecordStream(null, null); DocumentCursorImpl foreignCursor = new DocumentCursorImpl( new FilteredRecordStream(recordStream3, Filter.byId(NitriteId.newId()))); assertEquals("[]", (new JoinedDocumentStream(recordStream2, foreignCursor, new Lookup())).toString()); }
|
ProjectedDocumentStream implements RecordStream<Document> { @Override public String toString() { return toList().toString(); } ProjectedDocumentStream(RecordStream<Pair<NitriteId, Document>> recordStream,
Document projection); @Override Iterator<Document> iterator(); @Override String toString(); }
|
@Test public void testToString() { assertEquals("[]", (new ProjectedDocumentStream(null, Document.createDocument())).toString()); }
@Test public void testToString2() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); FilteredRecordStream recordStream2 = new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())); assertEquals("[]", (new ProjectedDocumentStream(recordStream2, Document.createDocument())).toString()); }
|
DocumentCursorImpl implements DocumentCursor { @Override public DocumentCursor sort(String field, SortOrder sortOrder, Collator collator, NullOrder nullOrder) { return new DocumentCursorImpl(new SortedDocumentCursor(field, sortOrder, collator, nullOrder, recordStream)); } DocumentCursorImpl(RecordStream<Pair<NitriteId, Document>> recordStream); @Override DocumentCursor sort(String field, SortOrder sortOrder, Collator collator, NullOrder nullOrder); @Override DocumentCursor skipLimit(long skip, long limit); @Override RecordStream<Document> project(Document projection); @Override RecordStream<Document> join(DocumentCursor foreignCursor, Lookup lookup); @Override Iterator<Document> iterator(); }
|
@Test public void testSort() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); assertTrue((new DocumentCursorImpl(new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())))) .sort("field", SortOrder.Ascending, null, NullOrder.First).isEmpty()); }
|
DocumentCursorImpl implements DocumentCursor { @Override public DocumentCursor skipLimit(long skip, long limit) { return new DocumentCursorImpl(new BoundedDocumentStream(recordStream, skip, limit)); } DocumentCursorImpl(RecordStream<Pair<NitriteId, Document>> recordStream); @Override DocumentCursor sort(String field, SortOrder sortOrder, Collator collator, NullOrder nullOrder); @Override DocumentCursor skipLimit(long skip, long limit); @Override RecordStream<Document> project(Document projection); @Override RecordStream<Document> join(DocumentCursor foreignCursor, Lookup lookup); @Override Iterator<Document> iterator(); }
|
@Test public void testSkipLimit() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); assertTrue((new DocumentCursorImpl(new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())))) .skipLimit(1L, 1L).isEmpty()); }
|
DocumentCursorImpl implements DocumentCursor { @Override public RecordStream<Document> project(Document projection) { validateProjection(projection); return new ProjectedDocumentStream(recordStream, projection); } DocumentCursorImpl(RecordStream<Pair<NitriteId, Document>> recordStream); @Override DocumentCursor sort(String field, SortOrder sortOrder, Collator collator, NullOrder nullOrder); @Override DocumentCursor skipLimit(long skip, long limit); @Override RecordStream<Document> project(Document projection); @Override RecordStream<Document> join(DocumentCursor foreignCursor, Lookup lookup); @Override Iterator<Document> iterator(); }
|
@Test public void testProject() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); DocumentCursorImpl documentCursorImpl = new DocumentCursorImpl( new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId()))); assertTrue(documentCursorImpl.project(Document.createDocument()).isEmpty()); }
|
DocumentCursorImpl implements DocumentCursor { @Override public RecordStream<Document> join(DocumentCursor foreignCursor, Lookup lookup) { return new JoinedDocumentStream(recordStream, foreignCursor, lookup); } DocumentCursorImpl(RecordStream<Pair<NitriteId, Document>> recordStream); @Override DocumentCursor sort(String field, SortOrder sortOrder, Collator collator, NullOrder nullOrder); @Override DocumentCursor skipLimit(long skip, long limit); @Override RecordStream<Document> project(Document projection); @Override RecordStream<Document> join(DocumentCursor foreignCursor, Lookup lookup); @Override Iterator<Document> iterator(); }
|
@Test public void testJoin() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); DocumentCursorImpl documentCursorImpl = new DocumentCursorImpl( new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId()))); FilteredRecordStream recordStream2 = new FilteredRecordStream(null, null); FilteredRecordStream recordStream3 = new FilteredRecordStream(recordStream2, Filter.byId(NitriteId.newId())); DocumentCursorImpl foreignCursor = new DocumentCursorImpl( new FilteredRecordStream(recordStream3, Filter.byId(NitriteId.newId()))); assertTrue(documentCursorImpl.join(foreignCursor, new Lookup()).isEmpty()); }
|
WriteResultImpl implements WriteResult { void setNitriteIds(Set<NitriteId> nitriteIds) { this.nitriteIds = nitriteIds; } int getAffectedCount(); @Override Iterator<NitriteId> iterator(); }
|
@Test public void testSetNitriteIds() { WriteResultImpl writeResultImpl = new WriteResultImpl(); writeResultImpl.setNitriteIds(new HashSet<NitriteId>()); assertEquals("WriteResultImpl(nitriteIds=[])", writeResultImpl.toString()); }
|
WriteResultImpl implements WriteResult { void addToList(NitriteId nitriteId) { if (nitriteIds == null) { nitriteIds = new HashSet<>(); } nitriteIds.add(nitriteId); } int getAffectedCount(); @Override Iterator<NitriteId> iterator(); }
|
@Test public void testAddToList() { WriteResultImpl writeResultImpl = new WriteResultImpl(); writeResultImpl.addToList(NitriteId.newId()); assertEquals(1, writeResultImpl.getAffectedCount()); }
|
MappableMapper implements NitriteMapper { protected <Target> Target convertFromDocument(Document source, Class<Target> type) { if (source == null) { return null; } if (Mappable.class.isAssignableFrom(type)) { Target item = newInstance(type, false); if (item == null) return null; ((Mappable) item).read(this, source); return item; } throw new ObjectMappingException("object must implements Mappable"); } MappableMapper(Class<?>... valueTypes); @Override @SuppressWarnings("unchecked") Target convert(Source source, Class<Target> type); @Override boolean isValueType(Class<?> type); @Override boolean isValue(Object object); @Override void initialize(NitriteConfig nitriteConfig); }
|
@Test public void testConvertFromDocument() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper mappableMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); assertNull(mappableMapper.<Object>convertFromDocument(null, Object.class)); }
@Test public void testConvertFromDocument2() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; MappableMapper mappableMapper = new MappableMapper(forNameResult, forNameResult1, Object.class); Class type = Object.class; assertThrows(ObjectMappingException.class, () -> mappableMapper.convertFromDocument(Document.createDocument(), type)); }
@Test public void testConvertFromDocument3() { Class<?> forNameResult = Object.class; Class<?> forNameResult1 = Object.class; assertNull( (new MappableMapper(forNameResult, forNameResult1, Object.class)).convertFromDocument(null, null)); }
|
WriteResultImpl implements WriteResult { public int getAffectedCount() { if (nitriteIds == null) return 0; return nitriteIds.size(); } int getAffectedCount(); @Override Iterator<NitriteId> iterator(); }
|
@Test public void testGetAffectedCount() { assertEquals(0, (new WriteResultImpl()).getAffectedCount()); }
|
BoundedDocumentStream implements RecordStream<Pair<NitriteId, Document>> { @Override public Iterator<Pair<NitriteId, Document>> iterator() { Iterator<Pair<NitriteId, Document>> iterator = recordStream == null ? Collections.emptyIterator() : recordStream.iterator(); return new BoundedIterator<>(iterator, offset, limit); } BoundedDocumentStream(RecordStream<Pair<NitriteId, Document>> recordStream, final long offset, final long limit); @Override Iterator<Pair<NitriteId, Document>> iterator(); }
|
@Test public void testIterator() { assertTrue((new BoundedDocumentStream(null, 1L, 1L)).iterator() instanceof BoundedDocumentStream.BoundedIterator); }
@Test public void testIterator2() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); BoundedDocumentStream recordStream2 = new BoundedDocumentStream( new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())), 1L, 1L); assertTrue( (new BoundedDocumentStream(new FilteredRecordStream(recordStream2, Filter.byId(NitriteId.newId())), 1L, 1L)) .iterator() instanceof BoundedDocumentStream.BoundedIterator); }
@Test public void testIterator3() { FilteredRecordStream recordStream = new FilteredRecordStream(null, null); FilteredRecordStream recordStream1 = new FilteredRecordStream(recordStream, Filter.byId(NitriteId.newId())); assertTrue( (new BoundedDocumentStream(new FilteredRecordStream(recordStream1, Filter.byId(NitriteId.newId())), 1L, 1L)) .iterator() instanceof BoundedDocumentStream.BoundedIterator); }
|
NitriteId implements Comparable<NitriteId>, Serializable { public static boolean validId(Object value) { if (value == null) { throw new InvalidIdException("id cannot be null"); } try { Long.parseLong(value.toString()); return true; } catch (Exception e) { throw new InvalidIdException("id must be a string representation of 64bit decimal number"); } } private NitriteId(); private NitriteId(String value); static NitriteId newId(); static NitriteId createId(String value); static boolean validId(Object value); @Override int compareTo(NitriteId other); @Override String toString(); String getIdValue(); }
|
@Test public void testValidId() { assertThrows(InvalidIdException.class, () -> NitriteId.validId("value")); assertTrue(NitriteId.validId(42)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.