src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
BooksPageController { @RequestMapping(value = "/book/{id}", method = RequestMethod.GET) public String getBook(@PathVariable String id, Model model) { model.addAttribute("book", bookService.getBook(id)); return "book"; } @RequestMapping(value = "/books", method = RequestMethod.GET) String getBookList(Model model); @RequestMapping(value = "/book/{id}", method = RequestMethod.GET) String getBook(@PathVariable String id, Model model); } | @Test public void shouldLoadSingleBook() { Model mockModel = mock(Model.class); Book book = new Book(1, "title", "author", "isbn", "publicationDate"); when(bookService.getBook("1")).thenReturn(book); String viewName = booksPageController.getBook("1", mockModel); assertEquals("book", viewName); verify(mockModel).addAttribute(eq("book"), same(book)); } |
ConfigurationProperties { public static boolean tlsMutualAuthenticationRequired() { return enableMTLS; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadTLSMutualAuthenticationRequired() { System.clearProperty("mockserver.tlsMutualAuthenticationRequired"); assertFalse(tlsMutualAuthenticationRequired()); tlsMutualAuthenticationRequired(true); assertTrue(tlsMutualAuthenticationRequired()); assertEquals("true", System.getProperty("mockserver.tlsMutualAuthenticationRequired")); tlsMutualAuthenticationRequired(false); assertFalse(tlsMutualAuthenticationRequired()); assertEquals("false", System.getProperty("mockserver.tlsMutualAuthenticationRequired")); } |
ConfigurationProperties { public static String tlsMutualAuthenticationCertificateChain() { return tlsMutualAuthenticationCertificateChain; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadTLSMutualAuthenticationCertificateChain() throws IOException { System.clearProperty("mockserver.tlsMutualAuthenticationCertificateChain"); assertThat(tlsMutualAuthenticationCertificateChain(), is("")); File tempFile = File.createTempFile("some", "temp"); tlsMutualAuthenticationCertificateChain(tempFile.getAbsolutePath()); assertThat(tlsMutualAuthenticationCertificateChain(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.tlsMutualAuthenticationCertificateChain")); } |
ConfigurationProperties { public static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType() { return forwardProxyTLSX509CertificatesTrustManagerType; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadForwardProxyTLSX509CertificatesTrustManager() { System.clearProperty("mockserver.forwardProxyTLSX509CertificatesTrustManagerType"); assertThat(forwardProxyTLSX509CertificatesTrustManagerType(), is(ForwardProxyTLSX509CertificatesTrustManager.ANY)); forwardProxyTLSX509CertificatesTrustManagerType(ForwardProxyTLSX509CertificatesTrustManager.CUSTOM.name()); assertThat(forwardProxyTLSX509CertificatesTrustManagerType(), is(ForwardProxyTLSX509CertificatesTrustManager.CUSTOM)); assertEquals(ForwardProxyTLSX509CertificatesTrustManager.CUSTOM.name(), System.getProperty("mockserver.forwardProxyTLSX509CertificatesTrustManagerType")); } |
ConfigurationProperties { public static String forwardProxyTLSCustomTrustX509Certificates() { return forwardProxyTLSCustomTrustX509Certificates; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadForwardProxyTLSCustomTrustX509Certificates() throws IOException { System.clearProperty("mockserver.forwardProxyTLSCustomTrustX509Certificates"); assertThat(forwardProxyTLSCustomTrustX509Certificates(), is("")); File tempFile = File.createTempFile("some", "temp"); forwardProxyTLSCustomTrustX509Certificates(tempFile.getAbsolutePath()); assertThat(forwardProxyTLSCustomTrustX509Certificates(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.forwardProxyTLSCustomTrustX509Certificates")); } |
ConfigurationProperties { public static String forwardProxyPrivateKey() { return forwardProxyPrivateKey; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadForwardProxyPrivateKey() throws IOException { System.clearProperty("mockserver.forwardProxyPrivateKey"); assertThat(forwardProxyPrivateKey(), is("")); File tempFile = File.createTempFile("some", "temp"); forwardProxyPrivateKey(tempFile.getAbsolutePath()); assertThat(forwardProxyPrivateKey(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.forwardProxyPrivateKey")); } |
ConfigurationProperties { public static String forwardProxyCertificateChain() { return forwardProxyCertificateChain; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadForwardProxyCertificateChain() throws IOException { System.clearProperty("mockserver.forwardProxyCertificateChain"); assertThat(forwardProxyCertificateChain(), is("")); File tempFile = File.createTempFile("some", "temp"); forwardProxyCertificateChain(tempFile.getAbsolutePath()); assertThat(forwardProxyCertificateChain(), is(tempFile.getAbsolutePath())); assertEquals(tempFile.getAbsolutePath(), System.getProperty("mockserver.forwardProxyCertificateChain")); } |
ConfigurationProperties { public static boolean metricsEnabled() { return metricsEnabled; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadMetricsEnabled() { System.clearProperty("mockserver.metricsEnabled"); assertFalse(metricsEnabled()); metricsEnabled(true); assertTrue(metricsEnabled()); assertEquals("true", System.getProperty("mockserver.metricsEnabled")); } |
ConfigurationProperties { public static boolean disableSystemOut() { return disableSystemOut; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadDisableSystemOut() { boolean originalSetting = disableSystemOut(); try { disableSystemOut(true); assertTrue(disableSystemOut()); assertEquals("true", System.getProperty("mockserver.disableSystemOut")); disableSystemOut(false); assertFalse(disableSystemOut()); assertEquals("false", System.getProperty("mockserver.disableSystemOut")); } finally { disableSystemOut(originalSetting); } } |
ConfigurationProperties { public static boolean detailedMatchFailures() { return detailedMatchFailures; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadDetailedMatchFailures() { boolean originalSetting = detailedMatchFailures(); try { detailedMatchFailures(true); assertTrue(detailedMatchFailures()); assertEquals("true", System.getProperty("mockserver.detailedMatchFailures")); detailedMatchFailures(false); assertFalse(detailedMatchFailures()); assertEquals("false", System.getProperty("mockserver.detailedMatchFailures")); } finally { detailedMatchFailures(originalSetting); } } |
ConfigurationProperties { public static boolean launchUIForLogLevelDebug() { return Boolean.parseBoolean(readPropertyHierarchically(MOCKSERVER_LAUNCH_UI_FOR_LOG_LEVEL_DEBUG, "MOCKSERVER_LAUNCH_UI_FOR_LOG_LEVEL_DEBUG", "" + false)); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadLaunchUIForLogLevelDebug() { boolean originalSetting = launchUIForLogLevelDebug(); try { launchUIForLogLevelDebug(true); assertTrue(launchUIForLogLevelDebug()); assertEquals("true", System.getProperty("mockserver.launchUIForLogLevelDebug")); launchUIForLogLevelDebug(false); assertFalse(launchUIForLogLevelDebug()); assertEquals("false", System.getProperty("mockserver.launchUIForLogLevelDebug")); } finally { launchUIForLogLevelDebug(originalSetting); } } |
ConfigurationProperties { public static boolean matchersFailFast() { return matchersFailFast; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadMatchersFailFast() { boolean originalSetting = matchersFailFast(); try { matchersFailFast(true); assertTrue(matchersFailFast()); assertEquals("true", System.getProperty("mockserver.matchersFailFast")); matchersFailFast(false); assertFalse(matchersFailFast()); assertEquals("false", System.getProperty("mockserver.matchersFailFast")); } finally { matchersFailFast(originalSetting); } } |
ConfigurationProperties { public static String localBoundIP() { return readPropertyHierarchically(MOCKSERVER_LOCAL_BOUND_IP, "MOCKSERVER_LOCAL_BOUND_IP", ""); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadLocalBoundIP() { System.clearProperty("mockserver.localBoundIP"); assertEquals("", localBoundIP()); localBoundIP("127.0.0.1"); assertEquals("127.0.0.1", localBoundIP()); assertEquals("127.0.0.1", System.getProperty("mockserver.localBoundIP")); }
@Test public void shouldThrowIllegalArgumentExceptionForInvalidLocalBoundIP() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("'abc.def' is not an IP string literal")); localBoundIP("abc.def"); } |
ConfigurationProperties { public static boolean attemptToProxyIfNoMatchingExpectation() { return attemptToProxyIfNoMatchingExpectation; } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test public void shouldSetAndReadAttemptToProxyIfNoMatchingExpectation() { System.clearProperty("mockserver.attemptToProxyIfNoMatchingExpectation"); assertTrue(attemptToProxyIfNoMatchingExpectation()); attemptToProxyIfNoMatchingExpectation(false); assertFalse(attemptToProxyIfNoMatchingExpectation()); assertEquals("false", System.getProperty("mockserver.attemptToProxyIfNoMatchingExpectation")); } |
ConfigurationProperties { @Deprecated public static InetSocketAddress httpProxy() { return readInetSocketAddressProperty(MOCKSERVER_HTTP_PROXY, "MOCKSERVER_HTTP_PROXY"); } static int defaultMaxExpectations(); static void defaultMaxExpectations(int defaultMaxExpectations); static int maxExpectations(); static void maxExpectations(int count); static int defaultMaxLogEntries(); static void defaultMaxLogEntries(int defaultMaxLogEntries); static int maxLogEntries(); static void maxLogEntries(int count); static int ringBufferSize(); static boolean outputMemoryUsageCsv(); static void outputMemoryUsageCsv(boolean enable); static String memoryUsageCsvDirectory(); static void memoryUsageCsvDirectory(String directory); static int maxWebSocketExpectations(); static void maxWebSocketExpectations(int count); static int maxInitialLineLength(); static void maxInitialLineLength(int length); static int maxHeaderSize(); static void maxHeaderSize(int size); static int maxChunkSize(); static void maxChunkSize(int size); static int nioEventLoopThreadCount(); static void nioEventLoopThreadCount(int count); static int actionHandlerThreadCount(); static void actionHandlerThreadCount(int count); static int webSocketClientEventLoopThreadCount(); static void webSocketClientEventLoopThreadCount(int count); static long maxSocketTimeout(); static void maxSocketTimeout(long milliseconds); static long maxFutureTimeout(); static void maxFutureTimeout(long milliseconds); static int socketConnectionTimeout(); static void socketConnectionTimeout(int milliseconds); static void alwaysCloseSocketConnections(boolean alwaysClose); static boolean alwaysCloseSocketConnections(); static String sslCertificateDomainName(); static void sslCertificateDomainName(String domainName); @SuppressWarnings("UnstableApiUsage") static void addSubjectAlternativeName(String host); static String[] sslSubjectAlternativeNameDomains(); static void addSslSubjectAlternativeNameDomains(String... additionalSubjectAlternativeNameDomains); static void clearSslSubjectAlternativeNameDomains(); @SuppressWarnings("unused") static boolean containsSslSubjectAlternativeName(String domainOrIp); static String[] sslSubjectAlternativeNameIps(); static void addSslSubjectAlternativeNameIps(String... additionalSubjectAlternativeNameIps); static void clearSslSubjectAlternativeNameIps(); static boolean rebuildTLSContext(); static void rebuildTLSContext(boolean rebuildTLSContext); static boolean rebuildServerTLSContext(); static void rebuildServerTLSContext(boolean rebuildServerTLSContext); static void useBouncyCastleForKeyAndCertificateGeneration(boolean enable); static boolean useBouncyCastleForKeyAndCertificateGeneration(); static void preventCertificateDynamicUpdate(boolean prevent); static boolean preventCertificateDynamicUpdate(); static String certificateAuthorityPrivateKey(); static void certificateAuthorityPrivateKey(String certificateAuthorityPrivateKey); static String certificateAuthorityCertificate(); static void certificateAuthorityCertificate(String certificateAuthorityCertificate); static boolean dynamicallyCreateCertificateAuthorityCertificate(); static void dynamicallyCreateCertificateAuthorityCertificate(boolean enable); static String directoryToSaveDynamicSSLCertificate(); static void directoryToSaveDynamicSSLCertificate(String directoryToSaveDynamicSSLCertificate); static String privateKeyPath(); static void privateKeyPath(String privateKeyPath); static String x509CertificatePath(); static void x509CertificatePath(String x509CertificatePath); static boolean tlsMutualAuthenticationRequired(); static void tlsMutualAuthenticationRequired(boolean enable); static String tlsMutualAuthenticationCertificateChain(); static void tlsMutualAuthenticationCertificateChain(String trustCertificateChain); static ForwardProxyTLSX509CertificatesTrustManager forwardProxyTLSX509CertificatesTrustManagerType(); static void forwardProxyTLSX509CertificatesTrustManagerType(String trustManagerType); static String forwardProxyTLSCustomTrustX509Certificates(); static void forwardProxyTLSCustomTrustX509Certificates(String customX509Certificates); static String forwardProxyPrivateKey(); static void forwardProxyPrivateKey(String privateKey); static String forwardProxyCertificateChain(); static void forwardProxyCertificateChain(String certificateChain); static Level logLevel(); static String javaLoggerLogLevel(); static void logLevel(String level); static boolean disableSystemOut(); static void disableSystemOut(boolean disable); static boolean detailedMatchFailures(); static void detailedMatchFailures(boolean enable); static boolean launchUIForLogLevelDebug(); static void launchUIForLogLevelDebug(boolean enable); static boolean matchersFailFast(); static void matchersFailFast(boolean enable); static boolean metricsEnabled(); static void metricsEnabled(boolean enable); static String localBoundIP(); @SuppressWarnings("UnstableApiUsage") static void localBoundIP(String localBoundIP); static boolean attemptToProxyIfNoMatchingExpectation(); static void attemptToProxyIfNoMatchingExpectation(boolean enable); @Deprecated static InetSocketAddress httpProxy(); @Deprecated static void httpProxy(String hostAndPort); @Deprecated static InetSocketAddress httpsProxy(); @Deprecated static void httpsProxy(String hostAndPort); @Deprecated static InetSocketAddress socksProxy(); @Deprecated static void socksProxy(String hostAndPort); static InetSocketAddress forwardHttpProxy(); static void forwardHttpProxy(String hostAndPort); static InetSocketAddress forwardHttpsProxy(); static void forwardHttpsProxy(String hostAndPort); static InetSocketAddress forwardSocksProxy(); static void forwardSocksProxy(String hostAndPort); static String forwardProxyAuthenticationUsername(); static void forwardProxyAuthenticationUsername(String forwardProxyAuthenticationUsername); static String forwardProxyAuthenticationPassword(); static void forwardProxyAuthenticationPassword(String forwardProxyAuthenticationPassword); static String proxyAuthenticationRealm(); static void proxyAuthenticationRealm(String proxyAuthenticationRealm); static String proxyAuthenticationUsername(); static void proxyAuthenticationUsername(String proxyAuthenticationUsername); static String proxyAuthenticationPassword(); static void proxyAuthenticationPassword(String proxyAuthenticationPassword); static String initializationClass(); static void initializationClass(String initializationClass); static String initializationJsonPath(); static void initializationJsonPath(String initializationJsonPath); static boolean watchInitializationJson(); static void watchInitializationJson(boolean enable); static boolean persistExpectations(); static void persistExpectations(boolean enable); static String persistedExpectationsPath(); static void persistedExpectationsPath(String persistedExpectationsPath); static boolean enableCORSForAPI(); static boolean enableCORSForAPIHasBeenSetExplicitly(); static void enableCORSForAPI(boolean enable); static boolean enableCORSForAllResponses(); static void enableCORSForAllResponses(boolean enable); static String corsAllowHeaders(); static void corsAllowHeaders(String corsAllowHeaders); static String corsAllowMethods(); static void corsAllowMethods(String corsAllowMethods); static boolean corsAllowCredentials(); static void corsAllowCredentials(boolean allow); static int corsMaxAgeInSeconds(); static void corsMaxAgeInSeconds(int ageInSeconds); static String livenessHttpGetPath(); static void livenessHttpGetPath(String livenessPath); } | @Test @Deprecated public void shouldSetAndReadHttpProxy() { System.clearProperty("mockserver.httpProxy"); assertNull(httpProxy()); httpProxy("127.0.0.1:1090"); assertEquals("/127.0.0.1:1090", httpProxy().toString()); assertEquals("127.0.0.1:1090", System.getProperty("mockserver.httpProxy")); }
@Test @Deprecated public void shouldThrowIllegalArgumentExceptionForInvalidHttpProxy() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("Invalid httpProxy property must include <host>:<port> for example \"127.0.0.1:1090\" or \"localhost:1090\"")); httpProxy("abc.def"); } |
InventoryStockTakeResource extends BaseRestObjectResource<InventoryStockTake> { @Override public InventoryStockTake save(InventoryStockTake delegate) { if (!userCanProcessAdjustment()) { throw new RestClientException("The current user not authorized to process this operation."); } StockOperation operation = createOperation(delegate); operationService.submitOperation(operation); return newDelegate(); } InventoryStockTakeResource(); @Override DelegatingResourceDescription getRepresentationDescription(Representation rep); @Override InventoryStockTake newDelegate(); Boolean userCanProcessAdjustment(); @Override InventoryStockTake save(InventoryStockTake delegate); StockOperation createOperation(InventoryStockTake delegate); @Override Class<? extends IObjectDataService<InventoryStockTake>> getServiceClass(); } | @Test(expected = RestClientException.class) public void save_shouldThrowExceptionIfUserNotAuthorised() throws Exception { when(StockOperationTypeResource.userCanProcess(WellKnownOperationTypes.getAdjustment())).thenReturn(false); resource.save(delegate); } |
AdjustmentOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); if (!negateAppliedQuantity()) { tx.setQuantity(tx.getQuantity() * -1); } } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onCancelled_shouldSetStockroomAndNegateQuantity() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); adjustmentOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == -5); } } |
AdjustmentOperationType extends StockOperationTypeBase { @Override public void onCompleted(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onCompleted_shouldClearReservedTransactions() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); assertTrue(stockOperation.getReserved().size() == 1); adjustmentOperationType.onCompleted(stockOperation); assertTrue(stockOperation.getReserved().size() == 0); } |
ReceiptOperationType extends StockOperationTypeBase { @Override public void onCancelled(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(StockOperation operation); @Override void onCancelled(StockOperation operation); @Override void onCompleted(final StockOperation operation); } | @Test public void onCancelled_shouldClearReservedTransactions() throws Exception { ReceiptOperationType receiptOperationType = (ReceiptOperationType)stockOperationTypeDataService.getById(7); StockOperation stockOperation = stockOperationDataService.getById(4); assertTrue(stockOperation.getReserved().size() == 1); receiptOperationType.onCancelled(stockOperation); assertTrue(stockOperation.getReserved().size() == 0); } |
ReceiptOperationType extends StockOperationTypeBase { @Override public void onCompleted(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getDestination()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(StockOperation operation); @Override void onCancelled(StockOperation operation); @Override void onCompleted(final StockOperation operation); } | @Test public void onCompleted_shouldSetDestinationStockroom() throws Exception { ReceiptOperationType receiptOperationType = (ReceiptOperationType)stockOperationTypeDataService.getById(7); StockOperation stockOperation = stockOperationDataService.getById(4); receiptOperationType.onCompleted(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 4); } } |
StockOperationServiceImpl extends BaseOpenmrsService implements IStockOperationService { public void calculateReservations(StockOperation operation) { if (operation == null) { throw new IllegalArgumentException("The operation must be defined"); } List<ReservedTransaction> removeList = findDuplicateReservedTransactions(operation); for (ReservedTransaction tx : removeList) { operation.getReserved().remove(tx); } List<ReservedTransaction> transactions = sortReservedTransactions(operation); Map<Pair<Stockroom, Item>, ItemStock> stockMap = new HashMap<Pair<Stockroom, Item>, ItemStock>(); List<ReservedTransaction> newTransactions = new ArrayList<ReservedTransaction>(); boolean hasSource = operation.getSource() != null; boolean isAdjustment = operation.isAdjustmentType(); for (ReservedTransaction tx : transactions) { if (hasSource && (!isAdjustment || (isAdjustment && tx.getQuantity() < 0))) { ItemStock stock = findAndCloneStock(stockMap, operation.getSource(), tx.getItem()); findAndUpdateSourceDetail(newTransactions, operation, stock, tx); } else { if (tx.getBatchOperation() == null) { tx.setBatchOperation(operation); tx.setCalculatedBatch(false); } } } for (ReservedTransaction newTx : newTransactions) { operation.addReserved(newTx); } } @Autowired StockOperationServiceImpl(IStockOperationDataService operationService, IStockroomDataService stockroomService,
IItemStockDataService itemStockService); static void validateOperation(StockOperation operation); static void validateOperationItems(StockOperation operation); @Override StockOperation submitOperation(StockOperation operation); @Override StockOperation rollbackOperation(StockOperation operation); @Override void applyTransactions(Collection<StockOperationTransaction> transactions); @Override void applyTransactions(StockOperationTransaction... transactions); void calculateReservations(StockOperation operation); } | @Test public void calculateReservations_shouldUseFurthestExpirationFromTheSourceStockroom() throws Exception { Settings settings = ModuleSettings.loadSettings(); settings.setAutoSelectItemStockFurthestExpirationDate(true); ModuleSettings.saveSettings(settings); Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item0 = itemDataService.getById(0); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 15); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(item0, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(item2, 5); tx2.setCalculatedBatch(true); tx2.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(item0, testTx.getItem()); Assert.assertNull(testTx.getExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(item2, testTx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); }
@Test public void calculateReservations_shouldFirstDeductFromFurthestExpirationFromTheSourceStockroom() throws Exception { Settings settings = ModuleSettings.loadSettings(); settings.setAutoSelectItemStockFurthestExpirationDate(true); ModuleSettings.saveSettings(settings); Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item0 = itemDataService.getById(0); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 15); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(item0, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(item2, -11); tx2.setCalculatedBatch(true); tx2.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(3, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(item0, testTx.getItem()); Assert.assertNull(testTx.getExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(item2, testTx.getItem()); Integer deductedQuantity = detail1.getQuantity() * -1; Assert.assertEquals(deductedQuantity, testTx.getQuantity()); }
@Test public void calculateReservations_shouldUseFurthestNullExpirationFromTheSourceStockroom() throws Exception { Settings settings = ModuleSettings.loadSettings(); settings.setAutoSelectItemStockFurthestExpirationDate(true); ModuleSettings.saveSettings(settings); Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item0 = itemDataService.getById(0); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(item0, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(item2, 5); tx2.setCalculatedBatch(true); tx2.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(item0, testTx.getItem()); Assert.assertNull(testTx.getExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(item2, testTx.getItem()); Assert.assertNull(testTx.getExpiration()); }
@Test public void calculateReservations_shouldUseClosestExpirationFromTheSourceStockroom() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item0 = itemDataService.getById(0); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(item0, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(item2, 10); tx2.setCalculatedBatch(true); tx2.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(item0, testTx.getItem()); Assert.assertNull(testTx.getExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(item2, testTx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar2.getTime(), testTx.getExpiration())); }
@Test public void calculateReservations_shouldUseOldestBatchOperationWithTheCalculatedExpiration() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item0 = itemDataService.getById(0); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item0); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item0); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item0); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(item0, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); tx = Iterators.get(operation.getReserved().iterator(), 0); Assert.assertEquals(item0, tx.getItem()); Assert.assertEquals(1, (int)tx.getBatchOperation().getId()); }
@Test public void calculateReservations_shouldSetTheExpirationToNullIfNoValidItemStockCanBeFound() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(newItem, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertNull(tx.getExpiration()); }
@Test public void calculateReservations_shouldSetTheBatchToNullIfNoValidItemStockCanBeFound() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(newItem, 3); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertNull(tx.getBatchOperation()); }
@Test(expected = IllegalArgumentException.class) public void calculateReservations_shouldThrowIllegalArgumentExceptionIfOperationIsNull() throws Exception { service.calculateReservations(null); }
@Test public void calculateReservations_shouldUseDateAndTimeForExpirationCalculation() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); calendar2.add(Calendar.MINUTE, 20); detail2.setExpiration(calendar2.getTime()); ItemStockDetail detail3 = new ItemStockDetail(); detail3.setItem(item2); detail3.setStockroom(sourceRoom); detail3.setQuantity(20); detail3.setCalculatedBatch(false); detail3.setCalculatedExpiration(false); detail3.setBatchOperation(operationDataService.getById(1)); Calendar calendar3 = Calendar.getInstance(); calendar3.add(Calendar.YEAR, 1); detail3.setExpiration(calendar3.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); stock2.addDetail(detail3); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(item2, 10); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); tx = Iterators.get(operation.getReserved().iterator(), 0); Assert.assertEquals(item2, tx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar3.getTime(), tx.getExpiration())); }
@Test public void calculateReservations_shouldCreateAdditionalTransactionsWhenWhenMultipleDetailsAreNeedToFulfillRequest() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item item2 = itemDataService.getById(2); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(item2); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(item2); detail2.setStockroom(sourceRoom); detail2.setQuantity(20); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(1)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 1); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, item2); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(item2, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(item2, testTx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar2.getTime(), testTx.getExpiration())); Assert.assertEquals(1, (int)testTx.getBatchOperation().getId()); Assert.assertEquals(20, (int)testTx.getQuantity()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input != tx; } }); Assert.assertEquals(item2, testTx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); Assert.assertEquals(2, (int)testTx.getBatchOperation().getId()); Assert.assertEquals(5, (int)testTx.getQuantity()); }
@Test public void calculateReservations_shouldCreateAdditionalNullQualifierTransactionWhenThereIsNotEnoughValidItemStockToFulfillRequest() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(10); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); stock.addDetail(detail1); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); itemStockDataService.save(stock); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(newItem, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return tx == input; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); Assert.assertEquals(2, (int)testTx.getBatchOperation().getId()); Assert.assertEquals(10, (int)testTx.getQuantity()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return tx != input; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertTrue(testTx.isCalculatedExpiration()); Assert.assertNull(testTx.getExpiration()); Assert.assertTrue(testTx.isCalculatedBatch()); Assert.assertNull(testTx.getBatchOperation()); Assert.assertEquals(15, (int)testTx.getQuantity()); }
@Test public void calculateReservations_shouldCopySourceCalculationSettingsIntoSourceCalculationFields() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(100); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(100); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(true); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, newItem); stock2.addDetail(detail1); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(newItem, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertEquals(newItem, tx.getItem()); Assert.assertFalse(tx.isSourceCalculatedBatch()); Assert.assertTrue(tx.isSourceCalculatedExpiration()); }
@Test public void calculateReservations_shouldSetTheBatchOperationToTheSpecifiedOperationIfThereIsNoSourceStockroom() throws Exception { Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); itemDataService.save(newItem); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getReceipt()); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); operation.setStatus(StockOperationStatus.PENDING); ReservedTransaction tx = operation.addReserved(newItem, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertEquals(newItem, tx.getItem()); Assert.assertEquals(operation, tx.getBatchOperation()); }
@Test public void calculateReservations_shouldCombineTransactionsForTheSameItemStockAndQualifiers() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(100); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(100); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(true); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, newItem); stock2.addDetail(detail1); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); operation.setStatus(StockOperationStatus.PENDING); ReservedTransaction tx = operation.addReserved(newItem, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); tx = operation.addReserved(newItem, 30); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); tx = Iterators.get(operation.getReserved().iterator(), 0); Assert.assertEquals(newItem, tx.getItem()); Assert.assertEquals(55, (int)tx.getQuantity()); }
@Test public void calculateReservations_shouldHandleMultipleTransactionsForTheSameItemButWithDifferentQualifiers() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(10); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); stock.addDetail(detail1); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); itemStockDataService.save(stock); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(newItem, 15); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(newItem, 5, calendar1.getTime()); tx2.setCalculatedBatch(true); tx2.setCalculatedExpiration(false); service.calculateReservations(operation); Assert.assertEquals(3, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertEquals(5, (int)testTx.getQuantity()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); Assert.assertTrue(testTx.isCalculatedExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertEquals(5, (int)testTx.getQuantity()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); Assert.assertFalse(testTx.isCalculatedExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input != tx && input != tx2; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertEquals(10, (int)testTx.getQuantity()); Assert.assertNull(testTx.getExpiration()); Assert.assertTrue(testTx.isCalculatedExpiration()); }
@Test public void calculateReservations_shouldSetTheTransactionSourceCalculatedFlagsIfTheSourceWasCalculated() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(10); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(10); detail1.setCalculatedBatch(true); detail1.setCalculatedExpiration(true); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, newItem); stock2.addDetail(detail1); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); ReservedTransaction tx = operation.addReserved(newItem, 5); tx.setExpiration(detail1.getExpiration()); tx.setBatchOperation(detail1.getBatchOperation()); tx.setCalculatedBatch(false); tx.setCalculatedExpiration(false); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertEquals(newItem, tx.getItem()); Assert.assertEquals(5, (int)tx.getQuantity()); Assert.assertTrue(tx.isSourceCalculatedBatch()); Assert.assertTrue(tx.isSourceCalculatedExpiration()); }
@Test public void calculateReservations_shouldProcessNoncalculatedTransactionsBeforeCalculatedTransactions() throws Exception { Stockroom sourceRoom = stockroomDataService.getById(0); Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); newItem.setHasExpiration(true); itemDataService.save(newItem); Context.flushSession(); ItemStock stock = new ItemStock(); stock.setItem(newItem); stock.setStockroom(sourceRoom); stock.setQuantity(10); itemStockDataService.save(stock); Context.flushSession(); ItemStockDetail detail1 = new ItemStockDetail(); detail1.setItem(newItem); detail1.setStockroom(sourceRoom); detail1.setQuantity(20); detail1.setCalculatedBatch(false); detail1.setCalculatedExpiration(false); detail1.setBatchOperation(operationDataService.getById(2)); Calendar calendar1 = Calendar.getInstance(); calendar1.add(Calendar.YEAR, 5); detail1.setExpiration(calendar1.getTime()); ItemStockDetail detail2 = new ItemStockDetail(); detail2.setItem(newItem); detail2.setStockroom(sourceRoom); detail2.setQuantity(10); detail2.setCalculatedBatch(false); detail2.setCalculatedExpiration(false); detail2.setBatchOperation(operationDataService.getById(2)); Calendar calendar2 = Calendar.getInstance(); calendar2.add(Calendar.YEAR, 10); detail2.setExpiration(calendar2.getTime()); ItemStock stock2 = stockroomDataService.getItem(sourceRoom, newItem); stock2.addDetail(detail1); stock2.addDetail(detail2); itemStockDataService.save(stock2); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getTransfer()); operation.setStatus(StockOperationStatus.PENDING); operation.setSource(sourceRoom); operation.setDestination(destRoom); operation.setOperationNumber("A123"); operation.setOperationDate(new Date()); final ReservedTransaction tx = operation.addReserved(newItem, 5); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); final ReservedTransaction tx2 = operation.addReserved(newItem, 10); tx2.setExpiration(calendar2.getTime()); tx2.setBatchOperation(detail1.getBatchOperation()); tx2.setCalculatedBatch(false); tx2.setCalculatedExpiration(false); service.calculateReservations(operation); Assert.assertEquals(2, operation.getReserved().size()); ReservedTransaction testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertEquals(5, (int)testTx.getQuantity()); Assert.assertTrue(DateUtils.isSameDay(calendar1.getTime(), testTx.getExpiration())); Assert.assertTrue(testTx.isCalculatedBatch()); Assert.assertTrue(testTx.isCalculatedExpiration()); testTx = Iterators.find(operation.getReserved().iterator(), new Predicate<ReservedTransaction>() { @Override public boolean apply(@Nullable ReservedTransaction input) { return input == tx2; } }); Assert.assertEquals(newItem, testTx.getItem()); Assert.assertEquals(10, (int)testTx.getQuantity()); Assert.assertTrue(DateUtils.isSameDay(calendar2.getTime(), testTx.getExpiration())); Assert.assertFalse(testTx.isCalculatedBatch()); Assert.assertFalse(testTx.isCalculatedExpiration()); }
@Test public void calculateReservations_shouldSetBatchOperationToPastOperationsBeforeFutureOperations() throws Exception { Stockroom destRoom = stockroomDataService.getById(1); Item newItem = itemTest.createEntity(true); itemDataService.save(newItem); Context.flushSession(); StockOperation operation = new StockOperation(); operation.setInstanceType(WellKnownOperationTypes.getReceipt()); operation.setStatus(StockOperationStatus.PENDING); operation.setDestination(destRoom); operation.setOperationNumber("A123"); Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 100); operation.setOperationDate(cal.getTime()); operationDataService.save(operation); ReservedTransaction tx = operation.addReserved(newItem, 25); tx.setCalculatedBatch(true); tx.setCalculatedExpiration(true); service.calculateReservations(operation); Assert.assertEquals(1, operation.getReserved().size()); Assert.assertEquals(newItem, tx.getItem()); Assert.assertEquals(operation, tx.getBatchOperation()); }
@Test public void calculateReservations_shouldCreateSingleTransactionWhenNegativeSourceStockAndRemoving() throws Exception { Item item = itemTest.createEntity(true); item.setHasExpiration(true); itemDataService.save(item); Context.flushSession(); Stockroom sr = stockroomDataService.getById(0); ItemStock stock = new ItemStock(); stock.setItem(item); stock.setQuantity(-10); ItemStockDetail detail = new ItemStockDetail(); detail.setStockroom(sr); detail.setItem(item); detail.setBatchOperation(null); detail.setCalculatedBatch(true); detail.setCalculatedExpiration(true); detail.setExpiration(null); detail.setQuantity(-10); stock.addDetail(detail); sr.addItem(stock); stockroomDataService.save(sr); Context.flushSession(); StockOperation op = operationTest.createEntity(true); op.getReserved().clear(); op.setStatus(StockOperationStatus.NEW); op.setInstanceType(WellKnownOperationTypes.getDistribution()); op.setSource(sr); op.setOperationDate(new Date()); op.setDepartment(item.getDepartment()); op.addItem(item, 15); for (StockOperationItem itemStock : op.getItems()) { ReservedTransaction tx = new ReservedTransaction(itemStock); tx.setCreator(Context.getAuthenticatedUser()); tx.setDateCreated(new Date()); op.addReserved(tx); } service.calculateReservations(op); Set<ReservedTransaction> transactions = op.getReserved(); Assert.assertNotNull(transactions); Assert.assertEquals(1, transactions.size()); ReservedTransaction tx = Iterators.getOnlyElement(transactions.iterator()); Assert.assertEquals(15, (long)tx.getQuantity()); Assert.assertNull(tx.getBatchOperation()); Assert.assertNull(tx.getExpiration()); }
@Test public void calculateReservations_shouldThrowErrorWhenGlobalPropertyEnabledAndNetSourceStockWillBeNegativeAndRemoving() throws Exception { adminService.saveGlobalProperty(new GlobalProperty(RESTRICT_NEGATIVE_INVENTORY_STOCK_CREATION_FIELD, "true")); Item item = itemTest.createEntity(true); item.setHasExpiration(true); itemDataService.save(item); Context.flushSession(); Stockroom sr = stockroomDataService.getById(0); ItemStock stock = new ItemStock(); stock.setItem(item); stock.setQuantity(10); ItemStockDetail detail = new ItemStockDetail(); detail.setStockroom(sr); detail.setItem(item); detail.setBatchOperation(null); detail.setCalculatedBatch(true); detail.setCalculatedExpiration(true); detail.setExpiration(null); detail.setQuantity(10); stock.addDetail(detail); sr.addItem(stock); stockroomDataService.save(sr); Context.flushSession(); StockOperation op = operationTest.createEntity(true); op.getReserved().clear(); op.setStatus(StockOperationStatus.NEW); op.setInstanceType(WellKnownOperationTypes.getDistribution()); op.setSource(sr); op.setOperationDate(new Date()); op.setDepartment(item.getDepartment()); op.addItem(item, 55); Assert.assertTrue(isNegativeStockRestricted()); try { for (StockOperationItem itemStock : op.getItems()) { ReservedTransaction tx = new ReservedTransaction(itemStock); tx.setCreator(Context.getAuthenticatedUser()); tx.setDateCreated(new Date()); op.addReserved(tx); } service.calculateReservations(op); } catch (Exception ex) { Assert.assertNotNull(ex); Assert.assertTrue(ex.getMessage().contains("Resource stockroom does not have sufficient stock.")); } Set<ReservedTransaction> transactions = op.getReserved(); Assert.assertNotNull(transactions); Assert.assertEquals(1, transactions.size()); adminService.saveGlobalProperty(new GlobalProperty(RESTRICT_NEGATIVE_INVENTORY_STOCK_CREATION_FIELD, "false")); Assert.assertFalse(isNegativeStockRestricted()); }
@Test public void calculateReservations_shouldCreateSingleTransactionWhenNegativeSourceStockAndAdding() throws Exception { Item item = itemTest.createEntity(true); item.setHasExpiration(true); itemDataService.save(item); Context.flushSession(); Stockroom sr = stockroomDataService.getById(0); ItemStock stock = new ItemStock(); stock.setItem(item); stock.setQuantity(-10); ItemStockDetail detail = new ItemStockDetail(); detail.setStockroom(sr); detail.setItem(item); detail.setBatchOperation(null); detail.setCalculatedBatch(true); detail.setCalculatedExpiration(true); detail.setExpiration(null); detail.setQuantity(-10); stock.addDetail(detail); sr.addItem(stock); stockroomDataService.save(sr); Context.flushSession(); StockOperation op = operationTest.createEntity(true); op.getReserved().clear(); op.setStatus(StockOperationStatus.NEW); op.setInstanceType(WellKnownOperationTypes.getReceipt()); op.setDestination(sr); op.setOperationDate(new Date()); op.setDepartment(item.getDepartment()); Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 1); op.addItem(item, 15, cal.getTime()); for (StockOperationItem itemStock : op.getItems()) { ReservedTransaction tx = new ReservedTransaction(itemStock); tx.setCreator(Context.getAuthenticatedUser()); tx.setDateCreated(new Date()); op.addReserved(tx); } service.calculateReservations(op); Set<ReservedTransaction> transactions = op.getReserved(); Assert.assertNotNull(transactions); Assert.assertEquals(1, transactions.size()); ReservedTransaction tx = Iterators.getOnlyElement(transactions.iterator()); Assert.assertEquals(15, (long)tx.getQuantity()); Assert.assertEquals(op, tx.getBatchOperation()); Assert.assertTrue(DateUtils.isSameDay(cal.getTime(), tx.getExpiration())); } |
InventoryStockTakeResource extends BaseRestObjectResource<InventoryStockTake> { public StockOperation createOperation(InventoryStockTake delegate) { if (IdgenHelper.isOperationNumberGenerated()) { delegate.setOperationNumber(IdgenHelper.generateId()); } StockOperation operation = new StockOperation(); operation.setStatus(StockOperationStatus.NEW); operation.setInstanceType(WellKnownOperationTypes.getAdjustment()); operation.setSource(delegate.getStockroom()); operation.setOperationNumber(delegate.getOperationNumber()); operation.setOperationDate(new Date()); operation.setItems(createOperationsItemSet(operation, delegate.getItemStockSummaryList())); return operation; } InventoryStockTakeResource(); @Override DelegatingResourceDescription getRepresentationDescription(Representation rep); @Override InventoryStockTake newDelegate(); Boolean userCanProcessAdjustment(); @Override InventoryStockTake save(InventoryStockTake delegate); StockOperation createOperation(InventoryStockTake delegate); @Override Class<? extends IObjectDataService<InventoryStockTake>> getServiceClass(); } | @Test public void createOperation_shouldCreateOperation_generatedOperationNumber() throws Exception { when(StockOperationTypeResource.userCanProcess(WellKnownOperationTypes.getAdjustment())).thenReturn(true); when(IdgenHelper.isOperationNumberGenerated()).thenReturn(true); when(IdgenHelper.generateId()).thenReturn("A-Test-1"); List<ItemStockSummary> itemStockSummaries = new ArrayList<ItemStockSummary>(2); itemStockSummaries.add(iss1); itemStockSummaries.add(iss2); delegate.setItemStockSummaryList(itemStockSummaries); StockOperation operation = resource.createOperation(delegate); Assert.assertEquals("A-Test-1", operation.getOperationNumber()); Assert.assertEquals(2, operation.getItems().size()); Set<StockOperationItem> items = operation.getItems(); for (StockOperationItem item : items) { if (item.getItem().getId() == 1) { Assert.assertEquals(new Integer(-2), item.getQuantity()); } if (item.getItem().getId() == 2) { Assert.assertEquals(new Integer(5), item.getQuantity()); } } }
@Test public void createOperation_shouldCreateOperation_manualOperationNumber() throws Exception { when(StockOperationTypeResource.userCanProcess(WellKnownOperationTypes.getAdjustment())).thenReturn(true); when(IdgenHelper.isOperationNumberGenerated()).thenReturn(false); List<ItemStockSummary> itemStockSummaries = new ArrayList<ItemStockSummary>(2); itemStockSummaries.add(iss1); itemStockSummaries.add(iss2); delegate.setItemStockSummaryList(itemStockSummaries); StockOperation operation = resource.createOperation(delegate); Assert.assertEquals("M-Test-2", operation.getOperationNumber()); } |
TransferOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); tx.setQuantity(tx.getQuantity() * -1); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); } | @Test public void onPending_shouldNegateQuantityAndSetStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == -5); } } |
TransferOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); } | @Test public void onCancelled_shouldSetStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); assertTrue(transaction.getQuantity() == 5); } } |
TransferOperationType extends StockOperationTypeBase { @Override public void onCompleted(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getDestination()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(final StockOperation operation); } | @Test public void onCompleted_shouldSetDestinationStockroom() throws Exception { TransferOperationType transferOperationType = (TransferOperationType)stockOperationTypeDataService.getById(5); StockOperation stockOperation = stockOperationDataService.getById(8); transferOperationType.onCompleted(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 4); assertTrue(transaction.getQuantity() == 5); } } |
DistributionOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); tx.setPatient(operation.getPatient()); tx.setInstitution(operation.getInstitution()); tx.setQuantity(tx.getQuantity() * -1); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onPending_shouldNegateQuantityAndSetStockroomAndPatient() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); stockOperation.setPatient(patient); distributionOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertEquals(3, (int)transaction.getStockroom().getId()); assertEquals(-5, (int)transaction.getQuantity()); assertEquals(patient.getId(), transaction.getPatient().getPatientId()); } } |
DistributionOperationType extends StockOperationTypeBase { @Override public void onCancelled(final StockOperation operation) { executeCopyReservedAndClear(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onCancelled_shouldSetStockroom() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); distributionOperationType.onCancelled(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertNotNull(transactions); assertEquals(1, transactions.size()); for (StockOperationTransaction transaction : transactions) { assertEquals(3, (int)transaction.getStockroom().getId()); } } |
DistributionOperationType extends StockOperationTypeBase { @Override public void onCompleted(StockOperation operation) { operation.getReserved().clear(); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onCompleted_shouldClearReservedTransactions() throws Exception { DistributionOperationType distributionOperationType = (DistributionOperationType)stockOperationTypeDataService.getById(2); StockOperation stockOperation = stockOperationDataService.getById(5); assertEquals(1, stockOperation.getReserved().size()); distributionOperationType.onCompleted(stockOperation); assertEquals(0, stockOperation.getReserved().size()); } |
AdjustmentOperationType extends StockOperationTypeBase { @Override public void onPending(final StockOperation operation) { executeCopyReserved(operation, new Action2<ReservedTransaction, StockOperationTransaction>() { @Override public void apply(ReservedTransaction reserved, StockOperationTransaction tx) { tx.setStockroom(operation.getSource()); if (negateAppliedQuantity()) { tx.setQuantity(tx.getQuantity() * -1); } } }); } @Override boolean isNegativeItemQuantityAllowed(); @Override void onPending(final StockOperation operation); @Override void onCancelled(final StockOperation operation); @Override void onCompleted(StockOperation operation); } | @Test public void onPending_shouldNegateQuantityAndSetStockroomAndPatient() throws Exception { AdjustmentOperationType adjustmentOperationType = (AdjustmentOperationType)stockOperationTypeDataService.getById(0); StockOperation stockOperation = stockOperationDataService.getById(7); adjustmentOperationType.onPending(stockOperation); Set<StockOperationTransaction> transactions = stockOperation.getTransactions(); assertTrue(transactions.size() == 1); for (StockOperationTransaction transaction : transactions) { assertTrue(transaction.getStockroom().getId() == 3); } } |
DefaultConfiguration implements InternalActorSystemConfiguration, ApplicationContextAware { @Override public <T> T getProperty(Class component, String key, Class<T> targetType) { Map<String,Object> componentProperties = (Map<String, Object>) properties.get(generateComponentName(component)); if (componentProperties == null) { componentProperties = (Map<String, Object>) properties.get(component.getName()); } if(componentProperties != null) { Object value = componentProperties.get(key); if(value != null) { if(conversionService.canConvert(value.getClass(),targetType)) { return conversionService.convert(value,targetType); } } } return null; } @JsonCreator DefaultConfiguration(@JsonProperty("name") String name,
@JsonProperty("shards") int numberOfShards,
@JsonProperty("remoteActorSystems") List<DefaultRemoteConfiguration> remoteConfigurations); @JsonProperty("name") @Override String getName(); @JsonProperty("shards") @Override int getNumberOfShards(); @JsonAnySetter void setProperty(String name,Object value); @Override String getVersion(); @Override ElasticActor<?> getService(final String serviceId); @Override Set<String> getServices(); @Override T getProperty(Class component, String key, Class<T> targetType); @Override T getProperty(Class component, String key, Class<T> targetType, T defaultValue); @Override T getRequiredProperty(Class component, String key, Class<T> targetType); @Override void setApplicationContext(ApplicationContext applicationContext); @JsonProperty("remoteActorSystems") @Override List<DefaultRemoteConfiguration> getRemoteConfigurations(); } | @Test public void testLoadComplexObject() throws IOException { File configFile = ResourceUtils.getFile("classpath:ea-test.yaml"); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); DefaultConfiguration configuration = objectMapper.readValue(new FileInputStream(configFile), DefaultConfiguration.class); assertFalse(configuration.getProperty( TestActor.class, "pushConfigurations", List.class, Collections.emptyList()).isEmpty()); }
@Test public void testLoadComplexObject_fullClassName() throws IOException { File configFile = ResourceUtils.getFile("classpath:ea-test.yaml"); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); DefaultConfiguration configuration = objectMapper.readValue(new FileInputStream(configFile), DefaultConfiguration.class); assertFalse(configuration.getProperty( TestActorFullName.class, "pushConfigurations", List.class, Collections.emptyList()).isEmpty()); } |
ActorRefTools { public final ActorRef parse(String refSpec) { if (refSpec.startsWith("actor: int actorSeparatorIndex = 8; for (int i = 0; i < 3; i++) { int nextIndex = refSpec.indexOf('/', actorSeparatorIndex + 1); if (nextIndex == -1) { throw new IllegalArgumentException( format(EXCEPTION_FORMAT, refSpec)); } else { actorSeparatorIndex = nextIndex; } } int nextIndex = refSpec.indexOf('/', actorSeparatorIndex + 1); String actorId = (nextIndex == -1) ? null : refSpec.substring(nextIndex + 1); actorSeparatorIndex = (nextIndex == -1) ? actorSeparatorIndex : nextIndex; String[] components = (actorId == null) ? refSpec.substring(8).split("/") : refSpec.substring(8, actorSeparatorIndex).split("/"); String clusterName = components[0]; if (actorSystems.getClusterName().equals(clusterName)) { return handleLocalActorSystemReference(refSpec, components, actorId); } else { return handleRemoteActorSystemReference(refSpec, components, actorId); } } else { throw new IllegalArgumentException(format(EXCEPTION_FORMAT, refSpec)); } } ActorRefTools(InternalActorSystems actorSystems); final ActorRef parse(String refSpec); static boolean isService(ActorRef ref); } | @Test public void testParseRemoteShardRef() { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); ActorSystem actorSystem = mock(ActorSystem.class, withSettings().extraInterfaces(ShardAccessor.class)); ActorShard shard = mock(ActorShard.class); ShardKey shardKey = new ShardKey("Pi",0); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.getRemote("RemoteCluster","Pi")).thenReturn(actorSystem); when(((ShardAccessor) actorSystem).getShard("Pi/shards/0")).thenReturn(shard); when(shard.getKey()).thenReturn(shardKey); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef actorRef = actorRefTools.parse("actor: assertNotNull(actorRef); assertNull(actorRef.getActorId()); assertEquals(actorRef.toString(), "actor: }
@Test public void testParseActorRef() { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); InternalActorSystemConfiguration configuration = mock(InternalActorSystemConfiguration.class); ActorShard shard = mock(ActorShard.class); ShardKey shardKey = new ShardKey("Pi",0); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.get("Pi")).thenReturn(actorSystem); when(actorSystem.getConfiguration()).thenReturn(configuration); when(configuration.getNumberOfShards()).thenReturn(1); when(actorSystem.getShard("Pi/shards/0")).thenReturn(shard); when(shard.getKey()).thenReturn(shardKey); ActorShardRef shardRef = new ActorShardRef("LocalNode",shard,"master", actorSystem); when(internalActorSystems.createPersistentActorRef(shard,"master")).thenReturn(shardRef); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef actorRef = actorRefTools.parse("actor: assertNotNull(actorRef); assertEquals(actorRef.getActorId(),"master"); assertEquals(actorRef.toString(),"actor: }
@Test public void testParseShardRef() { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); InternalActorSystemConfiguration configuration = mock(InternalActorSystemConfiguration.class); ActorShard shard = mock(ActorShard.class); ShardKey shardKey = new ShardKey("Pi",0); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.get("Pi")).thenReturn(actorSystem); when(actorSystem.getConfiguration()).thenReturn(configuration); when(configuration.getNumberOfShards()).thenReturn(1); when(actorSystem.getShard("Pi/shards/0")).thenReturn(shard); when(shard.getKey()).thenReturn(shardKey); ActorShardRef shardRef = new ActorShardRef(null, "LocalNode",shard); when(internalActorSystems.createPersistentActorRef(shard,null)).thenReturn(shardRef); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef actorRef = actorRefTools.parse("actor: assertNotNull(actorRef); assertNull(actorRef.getActorId()); assertEquals(actorRef.toString(), "actor: }
@Test public void testParseServiceActorRefWithSlashInActorId() { String nodeId = UUID.randomUUID().toString(); InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); ActorNode node = mock(ActorNode.class); NodeKey nodeKey = new NodeKey("Pi",nodeId); when(internalActorSystems.getClusterName()).thenReturn("LocalCluster"); when(internalActorSystems.get("Pi")).thenReturn(actorSystem); when(actorSystem.getNode(nodeId)).thenReturn(node); when(node.getKey()).thenReturn(nodeKey); String serviceRefString = String.format("actor: ServiceActorRef serviceActorRef = new ServiceActorRef(actorSystem, "LocalCluster",node,"pi/calculate"); when(internalActorSystems.createServiceActorRef(node,"pi/calculate")).thenReturn(serviceActorRef); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef serviceRef = actorRefTools.parse(serviceRefString); assertNotNull(serviceRef); assertEquals(serviceRef.getActorId(),"pi/calculate"); assertEquals(serviceRef.toString(),serviceRefString); }
@Test public void testParseServiceActorRefOnAnotherNodeThatsNotYetJoinedMyClusterView() { String nodeId = "node001.elasticsoftwarefoundation.org"; InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); ActorNode localNode = mock(ActorNode.class); ActorNode remoteNode = mock(ActorNode.class); NodeKey nodeKey = new NodeKey("test",nodeId); NodeKey remoteNodeKey = new NodeKey("test","node002.elasticsoftwarefoundation.org"); when(internalActorSystems.getClusterName()).thenReturn("test.elasticsoftwarefoundation.org"); when(internalActorSystems.get("test")).thenReturn(actorSystem); when(actorSystem.getNode("node002.elasticsoftwarefoundation.org")).thenReturn(remoteNode); when(actorSystem.getNode()).thenReturn(localNode); when(localNode.getKey()).thenReturn(nodeKey); when(remoteNode.getKey()).thenReturn(remoteNodeKey); String serviceRefString = String.format("actor: ServiceActorRef localRef = new ServiceActorRef(actorSystem, "test.elasticsoftwarefoundation.org",localNode,"testService"); ServiceActorRef remoteRef = new ServiceActorRef(actorSystem, "test.elasticsoftwarefoundation.org",remoteNode,"testService"); when(internalActorSystems.createServiceActorRef(localNode,"testService")).thenReturn(localRef); when(internalActorSystems.createServiceActorRef(remoteNode,"testService")).thenReturn(remoteRef); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef serviceRef = actorRefTools.parse(serviceRefString); assertNotNull(serviceRef); assertEquals(serviceRef.getActorId(),"testService"); assertEquals(serviceRef.toString(),serviceRefString); }
@Test public void testParseServiceActorRefWithMultipleSlashesInActorId() { String nodeId = UUID.randomUUID().toString(); InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); ActorNode node = mock(ActorNode.class); NodeKey nodeKey = new NodeKey("Pi",nodeId); when(internalActorSystems.getClusterName()).thenReturn("LocalCluster"); when(internalActorSystems.get("Pi")).thenReturn(actorSystem); when(actorSystem.getNode(nodeId)).thenReturn(node); when(node.getKey()).thenReturn(nodeKey); String serviceRefString = String.format("actor: ServiceActorRef serviceActorRef = new ServiceActorRef(actorSystem, "LocalCluster",node,"pi/calculate/with/multiple/slashes"); when(internalActorSystems.createServiceActorRef(node,"pi/calculate/with/multiple/slashes")).thenReturn(serviceActorRef); ActorRefTools actorRefTools = new ActorRefTools(internalActorSystems); ActorRef serviceRef = actorRefTools.parse(serviceRefString); assertNotNull(serviceRef); assertEquals(serviceRef.getActorId(),"pi/calculate/with/multiple/slashes"); assertEquals(serviceRef.toString(),serviceRefString); } |
ScheduledMessageRefTools { public static ScheduledMessageRef parse(String refSpec, InternalActorSystems cluster) { if(refSpec.startsWith("message: final String[] components = refSpec.substring(10).split("/"); if(components.length == 6) { final ScheduledMessageKey key = new ScheduledMessageKey(UUID.fromString(components[5]),Long.parseLong(components[4])); final int shardId = Integer.parseInt(components[3]); if(components[0].equals(cluster.getClusterName())) { ActorShard localShard = cluster.get(components[1]).getShard(shardId); return new ScheduledMessageShardRef(components[0],localShard,key); } else { ActorSystem remoteActorSystem = cluster.getRemote(components[0],components[1]); if(remoteActorSystem != null) { ActorShard remoteShard = ((ShardAccessor)remoteActorSystem).getShard(shardId); return new ScheduledMessageShardRef(components[0],remoteShard,key); } else { return new DisconnectedRemoteScheduledMessageRef(components[0],components[1],shardId,key); } } } else { throw new IllegalArgumentException(format(EXCEPTION_FORMAT,refSpec)); } } else { throw new IllegalArgumentException(format(EXCEPTION_FORMAT,refSpec)); } } private ScheduledMessageRefTools(); static ScheduledMessageRef parse(String refSpec, InternalActorSystems cluster); } | @Test public void testParseLocalRef() { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); InternalActorSystem actorSystem = mock(InternalActorSystem.class); InternalActorSystemConfiguration configuration = mock(InternalActorSystemConfiguration.class); ActorShard shard = mock(ActorShard.class); ShardKey shardKey = new ShardKey("Pi",0); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.get("Pi")).thenReturn(actorSystem); when(actorSystem.getConfiguration()).thenReturn(configuration); when(configuration.getNumberOfShards()).thenReturn(1); when(actorSystem.getShard(0)).thenReturn(shard); when(shard.getKey()).thenReturn(shardKey); ScheduledMessageRef messageRef = ScheduledMessageRefTools.parse("message: assertNotNull(messageRef); assertEquals(messageRef.toString(),"message: }
@Test public void testParseRemoteRef() { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); ActorSystem remoteActorSystem = mock(ActorSystem.class,withSettings().extraInterfaces(ShardAccessor.class)); ActorShard shard = mock(ActorShard.class); ShardKey shardKey = new ShardKey("Pi",0); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.getRemote("RemoteCluster","Pi")).thenReturn(remoteActorSystem); when(((ShardAccessor)remoteActorSystem).getShard(0)).thenReturn(shard); when(shard.getKey()).thenReturn(shardKey); ScheduledMessageRef messageRef = ScheduledMessageRefTools.parse("message: assertNotNull(messageRef); assertEquals(messageRef.toString(),"message: assertTrue(messageRef instanceof ScheduledMessageShardRef); }
@Test() public void testParseDisconnectedRemoteRef() throws Exception { InternalActorSystems internalActorSystems = mock(InternalActorSystems.class); when(internalActorSystems.getClusterName()).thenReturn("LocalNode"); when(internalActorSystems.getRemote("RemoteCluster","Pi")).thenReturn(null); ScheduledMessageRef messageRef = ScheduledMessageRefTools.parse("message: assertNotNull(messageRef); assertEquals(messageRef.toString(),"message: assertTrue(messageRef instanceof DisconnectedRemoteScheduledMessageRef); try { messageRef.cancel(); fail("messageRef.cancel() did not throw IllegalArgumentException"); } catch (IllegalStateException e) { assertEquals(e.getMessage(),"Remote Actor Cluster RemoteCluster is not configured, ensure a correct remote configuration in the config.yaml"); } try { ((DisconnectedRemoteScheduledMessageRef) messageRef).getActorContainer(); fail("messageRef.get() did not throw IllegalArgumentException"); } catch (IllegalStateException e) { assertEquals(e.getMessage(),"Remote Actor Cluster RemoteCluster is not configured, ensure a correct remote configuration in the config.yaml"); } } |
ObjectMapperBuilder { public final ObjectMapper build() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Set<String> basePackages = new HashSet<>(); try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(RESOURCE_NAME); while (resources.hasMoreElements()) { URL url = resources.nextElement(); Properties props = new Properties(); props.load(url.openStream()); basePackages.add(props.getProperty("basePackage")); } } catch(IOException e) { logger.warn("Failed to load elasticactors.properties", e); } if(this.basePackages != null && !"".equals(this.basePackages)) { String[] otherPackages = this.basePackages.split(","); basePackages.addAll(Arrays.asList(otherPackages)); } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); for (String basePackage : basePackages) { configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage)); } Reflections reflections = new Reflections(configurationBuilder); registerSubtypes(reflections, objectMapper); SimpleModule jacksonModule = new SimpleModule("org.elasticsoftware.elasticactors",new Version(1,0,0,null,null,null)); registerCustomSerializers(reflections,jacksonModule); registerCustomDeserializers(reflections,jacksonModule); objectMapper.registerModule(jacksonModule); if(useAfterBurner) { AfterburnerModule afterburnerModule = new AfterburnerModule(); objectMapper.registerModule(afterburnerModule); } return objectMapper; } ObjectMapperBuilder(ActorRefFactory actorRefFactory,ScheduledMessageRefFactory scheduledMessageRefFactory, String version); ObjectMapperBuilder(ActorRefFactory actorRefFactory,ScheduledMessageRefFactory scheduledMessageRefFactory, String basePackages, String version); ObjectMapperBuilder setUseAfterBurner(boolean useAfterBurner); final ObjectMapper build(); static final String RESOURCE_NAME; } | @Test public void testBuildObjectMapper() { ActorRefFactory actorRefFactory = mock(ActorRefFactory.class); ScheduledMessageRefFactory scheduledMessageRefFactory = mock(ScheduledMessageRefFactory.class); ObjectMapper objectMapper = new ObjectMapperBuilder(actorRefFactory,scheduledMessageRefFactory,"1.0.0").build(); assertNotNull(objectMapper); } |
Indexer implements ActorStateUpdateListener { @Override public final void onUpdate(List<? extends ActorStateUpdate> updates) { updates.stream().filter( update -> update.getActorClass().getAnnotation(IndexConfig.class) != null ).forEach(update -> { IndexConfig indexConfig = update.getActorClass().getAnnotation(IndexConfig.class); Class messageClass = update.getMessageClass(); ActorLifecycleStep lifecycleStep = update.getLifecycleStep(); if (messageClass != null && contains(indexConfig.includedMessages(), messageClass)) { indexActorState(indexConfig, update); } else if (lifecycleStep != null) { if (lifecycleStep == ActorLifecycleStep.DESTROY) { deleteActorState(indexConfig, update); } else if (Arrays.binarySearch(indexConfig.indexOn(), lifecycleStep) >= 0) { indexActorState(indexConfig, update); } if (lifecycleStep == ActorLifecycleStep.ACTIVATE && indexConfig.versioningStrategy() == REINDEX_ON_ACTIVATE) { if (!activatedActors.contains(update.getActorRef().getActorId())) { deleteOldVersionsOfActor(indexConfig, update); activatedActors.add(update.getActorRef().getActorId()); } } } } ); } @Autowired Indexer(Client client); @Override final void onUpdate(List<? extends ActorStateUpdate> updates); } | @Test public void testBasicIndexingPostActivate() throws Exception { ActorStateUpdate update = createActorStateUpdateNoneVersioning(); when(update.getLifecycleStep()).thenReturn(ActorLifecycleStep.ACTIVATE); indexer.onUpdate(newArrayList(update)); await() .atMost(FIVE_SECONDS) .pollInterval(ONE_HUNDRED_MILLISECONDS) .until(() -> { refreshIndices(); return client.prepareGet("test_index", "type_name", "1").execute().get().isExists(); }); assertTrue(client.admin().indices().prepareExists("test_index_v1").execute().get().isExists()); }
@Test public void testBasicIndexingIncludedMessage() throws Exception { ActorStateUpdate update = createActorStateUpdateNoneVersioning(); when(update.getMessageClass()).thenReturn(IncludedMessageClass.class); indexer.onUpdate(newArrayList(update)); await() .atMost(FIVE_SECONDS) .pollInterval(ONE_HUNDRED_MILLISECONDS) .until(() -> { refreshIndices(); return client.prepareGet("test_index_v1", "type_name", "1").execute().get().isExists(); }); }
@Test public void testNoIndexingExcludedMessage() throws Exception { ActorStateUpdate update = createActorStateUpdateNoneVersioning(); when(update.getMessageClass()).thenReturn(ExcludedMessageClass.class); indexer.onUpdate(newArrayList(update)); assertFalse(client.admin().indices().prepareExists("test_index_v1").execute().get().isExists()); assertFalse(client.admin().indices().prepareExists("test_index").execute().get().isExists()); }
@Test public void testDeleteOnDestroy() throws Exception { testBasicIndexingPostActivate(); ActorStateUpdate update = createActorStateUpdateNoneVersioning(); when(update.getLifecycleStep()).thenReturn(ActorLifecycleStep.DESTROY); indexer.onUpdate(newArrayList(update)); await() .atMost(FIVE_SECONDS) .pollInterval(ONE_HUNDRED_MILLISECONDS) .until(() -> { refreshIndices(); return !client.prepareGet("test_index_v1", "type_name", "1").execute().get().isExists(); }); }
@Test(enabled = false) public void testBasicVersionBasedReindexing() throws Exception { ActorStateUpdate update = createActorStateUpdateReindexing("1.0.0"); when(update.getLifecycleStep()).thenReturn(ActorLifecycleStep.ACTIVATE); indexer.onUpdate(newArrayList(update)); await() .atMost(Durations.ONE_MINUTE) .pollInterval(ONE_HUNDRED_MILLISECONDS) .until(() -> { refreshIndices(); return client.prepareGet("test_index", "type_name", "1").execute().get().isExists(); }); assertTrue(client.admin().indices().prepareExists("test_index_v1-0").execute().get().isExists()); } |
HashingNodeSelector implements NodeSelector { @Override public PhysicalNode getPrimary(String shardKey) { return consistentHash.get(shardKey); } HashingNodeSelector(List<PhysicalNode> nodes); @Override List<PhysicalNode> getAll(); @Override PhysicalNode getPrimary(String shardKey); } | @Test public void testThreeNodes() throws UnknownHostException { List<PhysicalNode> clusterNodes = Arrays.asList( new PhysicalNode("c8b53fd9-4d95-43fc-a1f7-96ca9e305d4", InetAddress.getByName("192.168.56.1"), true), new PhysicalNode("3bf98a1a-3c43-4d90-86d3-20c8f22d96c0", InetAddress.getByName("192.168.56.1"), false), new PhysicalNode("45a3fad3-c823-42f9-b0e5-90370b232698", InetAddress.getByName("192.168.56.1"), false)); HashingNodeSelector hashingNodeSelector = new HashingNodeSelector(clusterNodes); PhysicalNode node0 = hashingNodeSelector.getPrimary("default/shards/0"); PhysicalNode node1 = hashingNodeSelector.getPrimary("default/shards/1"); PhysicalNode node2 = hashingNodeSelector.getPrimary("default/shards/2"); PhysicalNode node3 = hashingNodeSelector.getPrimary("default/shards/3"); PhysicalNode node4 = hashingNodeSelector.getPrimary("default/shards/4"); PhysicalNode node5 = hashingNodeSelector.getPrimary("default/shards/5"); PhysicalNode node6 = hashingNodeSelector.getPrimary("default/shards/6"); PhysicalNode node7 = hashingNodeSelector.getPrimary("default/shards/7"); assertEquals(node0.getId(),"c8b53fd9-4d95-43fc-a1f7-96ca9e305d4"); assertEquals(node1.getId(),"45a3fad3-c823-42f9-b0e5-90370b232698"); assertEquals(node2.getId(),"45a3fad3-c823-42f9-b0e5-90370b232698"); assertEquals(node3.getId(),"3bf98a1a-3c43-4d90-86d3-20c8f22d96c0"); assertEquals(node4.getId(),"c8b53fd9-4d95-43fc-a1f7-96ca9e305d4"); assertEquals(node5.getId(),"3bf98a1a-3c43-4d90-86d3-20c8f22d96c0"); assertEquals(node6.getId(),"45a3fad3-c823-42f9-b0e5-90370b232698"); assertEquals(node7.getId(),"45a3fad3-c823-42f9-b0e5-90370b232698"); } |
MethodActor extends TypedActor<Object> implements PersistenceAdvisor { @Override public void onReceive(ActorRef sender, Object message) throws Exception { List<HandlerMethodDefinition> definitions = handlerCache.get(message.getClass()); if (definitions != null) { for (HandlerMethodDefinition definition : definitions) { try (MessagingScope ignored = getManager().enter(definition.handlerMethod)) { handleMessage(sender, message, definition); } } } else { onUnhandled(sender, message); } } protected MethodActor(); @Override final boolean shouldUpdateState(Object message); @Override final boolean shouldUpdateState(ActorLifecycleStep lifecycleStep); @Override void onReceive(ActorRef sender, Object message); final void setOnUnhandledLogLevel(@Nonnull LogLevel logLevel); static final String LOGGING_UNHANDLED_LEVEL_PROPERTY; static final LogLevel DEFAULT_UNHANDLED_LEVEL; } | @Test public void testMethodCallOnImpl() throws Exception { ActorContext context = mock(ActorContext.class); ActorRef sender = mock(ActorRef.class); ActorRef self = mock(ActorRef.class); ActorSystem actorSystem = mock(ActorSystem.class); TestActorContextHolder.setContext(context); TestActorState state = new TestActorState(); when(context.getState(TestActorState.class)).thenReturn(state); when(context.getActorSystem()).thenReturn(actorSystem); TestPersistentMethodActor actor = new TestPersistentMethodActor(); actor.onReceive(sender,new TestMessage("hello world!")); assertNotNull(state.getActorSystem()); assertEquals(state.getActorSystem(),actorSystem); assertNotNull(state.getSender()); }
@Test public void testMethodCallOnExternalClass() throws Exception { ActorContext context = mock(ActorContext.class); ActorRef sender = mock(ActorRef.class); ActorRef self = mock(ActorRef.class); ActorSystem actorSystem = mock(ActorSystem.class); TestActorContextHolder.setContext(context); TestActorState state = new TestActorState(); when(context.getState(TestActorState.class)).thenReturn(state); when(context.getActorSystem()).thenReturn(actorSystem); TestPersistentMethodActor actor = new TestPersistentMethodActor(); actor.onReceive(sender,new AnotherTestMessage("hello world!")); assertNotNull(state.getActorSystem()); assertEquals(state.getActorSystem(),actorSystem); assertNotNull(state.getSender()); } |
ProjectionDescriptor extends TransformationDescriptor<Input, Output> { public static ProjectionDescriptor<Record, Record> createForRecords(RecordType inputType, String... fieldNames) { final SerializableFunction<Record, Record> javaImplementation = createRecordJavaImplementation(fieldNames, inputType); return new ProjectionDescriptor<>( javaImplementation, Arrays.asList(fieldNames), inputType, new RecordType(fieldNames) ); } ProjectionDescriptor(Class<Input> inputTypeClass,
Class<Output> outputTypeClass,
String... fieldNames); ProjectionDescriptor(BasicDataUnitType<Input> inputType, BasicDataUnitType<Output> outputType, String... fieldNames); private ProjectionDescriptor(SerializableFunction<Input, Output> javaImplementation,
List<String> fieldNames,
BasicDataUnitType<Input> inputType,
BasicDataUnitType<Output> outputType); static ProjectionDescriptor<Record, Record> createForRecords(RecordType inputType, String... fieldNames); List<String> getFieldNames(); } | @Test public void testRecordImplementation() { RecordType inputType = new RecordType("a", "b", "c"); final ProjectionDescriptor<Record, Record> descriptor = ProjectionDescriptor.createForRecords(inputType, "c", "a"); Assert.assertEquals(new RecordType("c", "a"), descriptor.getOutputType()); final Function<Record, Record> javaImplementation = descriptor.getJavaImplementation(); Assert.assertEquals( new Record("world", 10), javaImplementation.apply(new Record(10, "hello", "world")) ); } |
Bitmask implements Cloneable, Iterable<Integer> { public Bitmask flip(int fromIndex, int toIndex) { if (fromIndex < toIndex) { this.ensureCapacity(toIndex - 1); int fromLongPos = getLongPos(fromIndex); int untilLongPos = getLongPos(toIndex - 1); for (int longPos = fromLongPos; longPos <= untilLongPos; longPos++) { int fromOffset = (longPos == fromLongPos) ? getOffset(fromIndex) : 0; int untilOffset = (longPos == untilLongPos) ? getOffset(toIndex - 1) + 1 : BITS_PER_WORD; long flipMask = createAllSetBits(untilOffset) ^ createAllSetBits(fromOffset); this.bits[longPos] ^= flipMask; } this.cardinalityCache = -1; } return this; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testFlip() { testFlip(0, 256); testFlip(32, 256); testFlip(32, 224); testFlip(65, 67); } |
Bitmask implements Cloneable, Iterable<Integer> { public boolean isSubmaskOf(Bitmask that) { final int minBitsLength = Math.min(this.bits.length, that.bits.length); for (int i = 0; i < minBitsLength; i++) { if (this.bits[i] != (this.bits[i] & that.bits[i])) return false; } for (int i = minBitsLength; i < this.bits.length; i++) { if (this.bits[i] != 0L) return false; } return true; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testIsSubmaskOf() { Assert.assertTrue(createBitmask(0).isSubmaskOf(createBitmask(1, 0))); Assert.assertTrue(createBitmask(1).isSubmaskOf(createBitmask(1, 0))); Assert.assertFalse(createBitmask(1, 0).isSubmaskOf(createBitmask(0))); Assert.assertTrue(createBitmask(0, 1, 65).isSubmaskOf(createBitmask(0, 1, 65, 129))); Assert.assertTrue(createBitmask(0, 1, 129).isSubmaskOf(createBitmask(0, 1, 65, 129))); Assert.assertTrue(createBitmask(0, 1, 129).isSubmaskOf(createBitmask(0, 1, 65, 66, 129))); Assert.assertFalse(createBitmask(0, 1, 65, 66, 129).isSubmaskOf(createBitmask(0, 1, 65, 129))); Assert.assertTrue(createBitmask(0, 1, 129).isSubmaskOf(createBitmask(0, 1, 129))); } |
Bitmask implements Cloneable, Iterable<Integer> { public int cardinality() { if (this.cardinalityCache == -1) { this.cardinalityCache = 0; for (long bits : this.bits) { this.cardinalityCache += Long.bitCount(bits); } } return this.cardinalityCache; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testCardinality() { Assert.assertEquals(0, createBitmask(0).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(1, createBitmask(0, 65).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(2, createBitmask(0, 65, 66).orInPlace(createBitmask(0)).cardinality()); Assert.assertEquals(3, createBitmask(0, 65, 66, 128).orInPlace(createBitmask(0)).cardinality()); } |
Bitmask implements Cloneable, Iterable<Integer> { public Bitmask or(Bitmask that) { Bitmask copy = new Bitmask(this, that.bits.length << WORD_ADDRESS_BITS); return copy.orInPlace(that); } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testOr() { Assert.assertEquals(createBitmask(0, 0), createBitmask(0).or(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 0, 1), createBitmask(0, 1).or(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 0, 1, 65, 128), createBitmask(0, 1, 128).or(createBitmask(0, 0, 65))); Assert.assertEquals(createBitmask(0, 0, 1, 65, 128), createBitmask(0, 0, 65).or(createBitmask(0, 1, 128))); } |
Bitmask implements Cloneable, Iterable<Integer> { public Bitmask andNot(Bitmask that) { Bitmask copy = new Bitmask(this, that.bits.length << WORD_ADDRESS_BITS); return copy.andNotInPlace(that); } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testAndNot() { Assert.assertEquals(createBitmask(0), createBitmask(0).andNot(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 1), createBitmask(0, 0, 1).andNot(createBitmask(0, 0))); Assert.assertEquals(createBitmask(0, 1, 128), createBitmask(0, 1, 128).andNot(createBitmask(0, 0, 65))); Assert.assertEquals(createBitmask(0, 65), createBitmask(0, 1, 65, 128).andNot(createBitmask(0, 1, 128))); } |
Bitmask implements Cloneable, Iterable<Integer> { public int nextSetBit(int from) { int longPos = getLongPos(from); int offset = getOffset(from); while (longPos < this.bits.length) { long bits = this.bits[longPos]; int nextOffset = Long.numberOfTrailingZeros(bits & ~createAllSetBits(offset)); if (nextOffset < BITS_PER_WORD) { return longPos << WORD_ADDRESS_BITS | nextOffset; } longPos++; offset = 0; } return -1; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testNextSetBit() { testSetBits(); testSetBits(0); testSetBits(1); testSetBits(0, 1); testSetBits(420); testSetBits(1, 420); testSetBits(1, 420, 421, 500); testSetBits(1, 2, 3, 65); } |
ExpressionBuilder extends MathExBaseVisitor<Expression> { public static Expression parse(String specification) throws ParseException { MathExLexer lexer = new MathExLexer(new ANTLRInputStream(specification)); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseException("Syntax error.", e); } }); MathExParser parser = new MathExParser(new CommonTokenStream(lexer)); parser.removeErrorListeners(); parser.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object o, int i, int i1, String s, RecognitionException e) { throw new ParseException("Syntax error.", e); } }); MathExParser.ExpressionContext expressionContext = parser.expression(); return new ExpressionBuilder().visit(expressionContext); } static Expression parse(String specification); @Override Expression visitConstant(MathExParser.ConstantContext ctx); @Override Expression visitFunction(MathExParser.FunctionContext ctx); @Override Expression visitVariable(MathExParser.VariableContext ctx); @Override Expression visitParensExpression(MathExParser.ParensExpressionContext ctx); @Override Expression visitBinaryOperation(MathExParser.BinaryOperationContext ctx); @Override Expression visitUnaryOperation(MathExParser.UnaryOperationContext ctx); } | @Test public void shouldNotFailOnValidInput() { Collection<String> expressions = Arrays.asList( "x", "f(x)", "1 + 2 + -3", "1 + 2 * 3", "1 - 2 + 3", "x + 1 + 3*f(x, 3^2)", "(2 *a + 3* b + 5.3 * c0) + 3*abcdef" ); for (String expression : expressions) { ExpressionBuilder.parse(expression); } }
@Test public void shouldFailOnInvalidInput() { Collection<String> expressions = Arrays.asList( "2x", "f(x,)", "~3", "", "*2", "f(3, x" ); for (String expression : expressions) { boolean isFailed = false; try { ExpressionBuilder.parse(expression); } catch (ParseException e) { isFailed = true; } finally { Assert.assertTrue(isFailed); } } } |
DynamicPlugin implements Plugin { public static DynamicPlugin loadYaml(String yamlUrl) { final FileSystem fileSystem = FileSystems.getFileSystem(yamlUrl).orElseThrow( () -> new RheemException(String.format("No filesystem for %s.", yamlUrl)) ); Object yaml; try (final InputStream inputStream = fileSystem.open(yamlUrl)) { yaml = new Yaml().load(inputStream); } catch (IOException e) { throw new RheemException(String.format("Could not load %s.", yamlUrl)); } DynamicPlugin plugin = new DynamicPlugin(); try { DynamicPlugin.<Map<String, Object>>ifPresent(yaml, Map.class, values -> { DynamicPlugin.<Map<String, Object>>ifPresent(values.get("platforms"), Map.class, platforms -> { DynamicPlugin.<List<String>>ifPresent(platforms.get("include"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof Platform) { plugin.addRequiredPlatform((Platform) eval); } else { Collection<?> platformCollection = (Collection<?>) eval; for (Object platform : platformCollection) { plugin.addRequiredPlatform((Platform) platform); } } } }); DynamicPlugin.<List<String>>ifPresent(platforms.get("exclude"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof Platform) { plugin.excludeRequiredPlatform((Platform) eval); } else { Collection<?> platformCollection = (Collection<?>) eval; for (Object platform : platformCollection) { plugin.excludeRequiredPlatform((Platform) platform); } } } }); }); DynamicPlugin.<Map<String, Object>>ifPresent(values.get("mappings"), Map.class, mappings -> { DynamicPlugin.<List<String>>ifPresent(mappings.get("include"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof Mapping) { plugin.addMapping((Mapping) eval); } else { Collection<?> collection = (Collection<?>) eval; for (Object element : collection) { plugin.addMapping((Mapping) element); } } } }); DynamicPlugin.<List<String>>ifPresent(mappings.get("exclude"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof Mapping) { plugin.excludeMapping((Mapping) eval); } else { Collection<?> collection = (Collection<?>) eval; for (Object element : collection) { plugin.excludeMapping((Mapping) element); } } } }); }); DynamicPlugin.<Map<String, Object>>ifPresent(values.get("conversions"), Map.class, conversions -> { DynamicPlugin.<List<String>>ifPresent(conversions.get("include"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof ChannelConversion) { plugin.addChannelConversion((ChannelConversion) eval); } else { Collection<?> collection = (Collection<?>) eval; for (Object element : collection) { plugin.addChannelConversion((ChannelConversion) element); } } } }); DynamicPlugin.<List<String>>ifPresent(conversions.get("exclude"), List.class, expressions -> { for (String expression : expressions) { Object eval = ReflectionUtils.evaluate(expression); if (eval instanceof ChannelConversion) { plugin.excludeChannelConversion((ChannelConversion) eval); } else { Collection<?> collection = (Collection<?>) eval; for (Object element : collection) { plugin.excludeChannelConversion((ChannelConversion) element); } } } }); }); DynamicPlugin.<Map<String, Object>>ifPresent(values.get("properties"), Map.class, properties -> { properties.forEach(plugin::addProperty); }); }); return plugin; } catch (Exception e) { throw new RheemException(String.format("Configuration file %s seems to be corrupt.", yamlUrl), e); } } static DynamicPlugin loadYaml(String yamlUrl); @SuppressWarnings("unchecked") static void ifPresent(Object o, Class<? super T> t, Consumer<T> consumer); void addRequiredPlatform(Platform platform); void excludeRequiredPlatform(Platform platform); @Override Collection<Platform> getRequiredPlatforms(); @Override Collection<Platform> getExcludedRequiredPlatforms(); void addMapping(Mapping mapping); void excludeMapping(Mapping mapping); @Override Collection<Mapping> getMappings(); @Override Collection<Mapping> getExcludedMappings(); void addChannelConversion(ChannelConversion channelConversion); void excludeChannelConversion(ChannelConversion channelConversion); @Override Collection<ChannelConversion> getChannelConversions(); @Override Collection<ChannelConversion> getExcludedChannelConversions(); void addProperty(String key, Object value); @Override void setProperties(Configuration configuration); } | @Test public void testLoadYaml() { final DynamicPlugin plugin = DynamicPlugin.loadYaml(ReflectionUtils.getResourceURL("test-plugin.yaml").toString()); Set<Platform> expectedPlatforms = RheemCollections.asSet(DummyPlatform.getInstance()); Assert.assertEquals(expectedPlatforms, RheemCollections.asSet(plugin.getRequiredPlatforms())); Set<Platform> expectedExcludedPlatforms = Collections.emptySet(); Assert.assertEquals(expectedExcludedPlatforms, RheemCollections.asSet(plugin.getExcludedRequiredPlatforms())); Set<Mapping> expectedMappings = RheemCollections.asSet(new TestSinkMapping()); Assert.assertEquals(expectedMappings, RheemCollections.asSet(plugin.getMappings())); Set<Mapping> expectedExcludedMappings = RheemCollections.asSet(); Assert.assertEquals(expectedExcludedMappings, RheemCollections.asSet(plugin.getExcludedMappings())); Set<ChannelConversion> expectedConversions = RheemCollections.asSet(); Assert.assertEquals(expectedConversions, RheemCollections.asSet(plugin.getChannelConversions())); Set<ChannelConversion> expectedExcludedConversions = RheemCollections.asSet(CHANNEL_CONVERSIONS); Assert.assertEquals(expectedExcludedConversions, RheemCollections.asSet(plugin.getExcludedChannelConversions())); Configuration configuration = new Configuration(); plugin.setProperties(configuration); Assert.assertEquals(51.3d, configuration.getDoubleProperty("io.rheem.test.float"), 0.000001); Assert.assertEquals("abcdef", configuration.getStringProperty("io.rheem.test.string")); Assert.assertEquals(1234567890123456789L, configuration.getLongProperty("io.rheem.test.long")); } |
LoopIsolator extends OneTimeExecutable { public static void isolateLoops(RheemPlan rheemPlan) { new LoopIsolator(rheemPlan).run(); } private LoopIsolator(RheemPlan rheemPlan); static void isolateLoops(RheemPlan rheemPlan); static LoopSubplan isolate(Operator allegedLoopHead); } | @Test public void testWithSingleLoop() { TestSource<Integer> source = new TestSource<>(Integer.class); TestLoopHead<Integer> loopHead = new TestLoopHead<>(Integer.class); source.connectTo("out", loopHead, "initialInput"); TestMapOperator<Integer, Integer> inLoopMap = new TestMapOperator<>(Integer.class, Integer.class); loopHead.connectTo("loopOutput", inLoopMap, "in"); inLoopMap.connectTo("out", loopHead, "loopInput"); TestSink<Integer> sink = new TestSink<>(Integer.class); loopHead.connectTo("finalOutput", sink, "in"); RheemPlan rheemPlan = new RheemPlan(sink); LoopIsolator.isolateLoops(rheemPlan); final Operator allegedLoopSubplan = sink.getEffectiveOccupant(0).getOwner(); Assert.assertSame(LoopSubplan.class, allegedLoopSubplan.getClass()); Assert.assertSame(source, allegedLoopSubplan.getEffectiveOccupant(0).getOwner()); LoopSubplan loopSubplan = (LoopSubplan) allegedLoopSubplan; Assert.assertEquals(1, loopSubplan.getNumOutputs()); Assert.assertEquals(1, loopSubplan.getNumInputs()); Assert.assertSame(loopHead.getOutput("finalOutput"), loopSubplan.traceOutput(loopSubplan.getOutput(0))); List<InputSlot<?>> innerInputs = new ArrayList<>(loopSubplan.followInput(loopSubplan.getInput(0))); Assert.assertEquals(1, innerInputs.size()); Assert.assertSame(loopHead.getInput("initialInput"), innerInputs.get(0)); Assert.assertSame(loopSubplan, loopHead.getParent()); Assert.assertSame(loopSubplan, inLoopMap.getParent()); }
@Test public void testWithSingleLoopWithConstantInput() { TestSource<Integer> mainSource = new TestSource<>(Integer.class); TestSource<Integer> additionalSource = new TestSource<>(Integer.class); TestLoopHead<Integer> loopHead = new TestLoopHead<>(Integer.class); mainSource.connectTo("out", loopHead, "initialInput"); TestMapOperator<Integer, Integer> inLoopMap = new TestMapOperator<>(Integer.class, Integer.class); loopHead.broadcastTo("loopOutput", inLoopMap, "broadcast"); additionalSource.connectTo("out", inLoopMap, "in"); inLoopMap.connectTo("out", loopHead, "loopInput"); TestSink<Integer> sink = new TestSink<>(Integer.class); loopHead.connectTo("finalOutput", sink, "in"); RheemPlan rheemPlan = new RheemPlan(sink); LoopIsolator.isolateLoops(rheemPlan); final Operator allegedLoopSubplan = sink.getEffectiveOccupant(0).getOwner(); Assert.assertSame(LoopSubplan.class, allegedLoopSubplan.getClass()); Assert.assertSame(mainSource, allegedLoopSubplan.getEffectiveOccupant(0).getOwner()); LoopSubplan loopSubplan = (LoopSubplan) allegedLoopSubplan; Assert.assertEquals(1, loopSubplan.getNumOutputs()); Assert.assertEquals(2, loopSubplan.getNumInputs()); Assert.assertSame(loopHead.getOutput("finalOutput"), loopSubplan.traceOutput(loopSubplan.getOutput(0))); List<InputSlot<?>> innerInputs = new ArrayList<>(loopSubplan.followInput(loopSubplan.getInput(0))); Assert.assertEquals(1, innerInputs.size()); Assert.assertSame(loopHead.getInput("initialInput"), innerInputs.get(0)); Assert.assertSame(loopSubplan, loopHead.getParent()); Assert.assertSame(loopSubplan, inLoopMap.getParent()); }
@Test public void testNestedLoops() { TestSource<Integer> mainSource = new TestSource<>(Integer.class); mainSource.setName("mainSource"); TestLoopHead<Integer> outerLoopHead = new TestLoopHead<>(Integer.class); mainSource.connectTo("out", outerLoopHead, "initialInput"); outerLoopHead.setName("outerLoopHead"); TestMapOperator<Integer, Integer> inOuterLoopMap = new TestMapOperator<>(Integer.class, Integer.class); outerLoopHead.connectTo("loopOutput", inOuterLoopMap, "in"); inOuterLoopMap.setName("inOuterLoopMap"); TestLoopHead<Integer> innerLoopHead = new TestLoopHead<>(Integer.class); inOuterLoopMap.connectTo("out", innerLoopHead, "initialInput"); innerLoopHead.setName("innerLoopHead"); TestMapOperator<Integer, Integer> inInnerLoopMap = new TestMapOperator<>(Integer.class, Integer.class); innerLoopHead.connectTo("loopOutput", inInnerLoopMap, "in"); inInnerLoopMap.connectTo("out", innerLoopHead, "loopInput"); innerLoopHead.connectTo("finalOutput", outerLoopHead, "loopInput"); inInnerLoopMap.setName("inInnerLoopMap"); TestSink<Integer> sink = new TestSink<>(Integer.class); outerLoopHead.connectTo("finalOutput", sink, "in"); sink.setName("sink"); RheemPlan rheemPlan = new RheemPlan(sink); LoopIsolator.isolateLoops(rheemPlan); final Operator allegedOuterLoopSubplan = sink.getEffectiveOccupant(0).getOwner(); Assert.assertSame(LoopSubplan.class, allegedOuterLoopSubplan.getClass()); Assert.assertSame(mainSource, allegedOuterLoopSubplan.getEffectiveOccupant(0).getOwner()); LoopSubplan outerSubplan = (LoopSubplan) allegedOuterLoopSubplan; Assert.assertEquals(1, outerSubplan.getNumOutputs()); Assert.assertEquals(1, outerSubplan.getNumInputs()); Assert.assertSame(outerLoopHead.getOutput("finalOutput"), outerSubplan.traceOutput(outerSubplan.getOutput(0))); List<InputSlot<?>> innerInputs = new ArrayList<>(outerSubplan.followInput(outerSubplan.getInput(0))); Assert.assertEquals(1, innerInputs.size()); Assert.assertSame(outerLoopHead.getInput("initialInput"), innerInputs.get(0)); Assert.assertSame(outerSubplan, outerLoopHead.getParent()); Assert.assertSame(outerSubplan, inOuterLoopMap.getParent()); final Operator allegedInnerLoopSubplan = outerLoopHead.getEffectiveOccupant(outerLoopHead.getInput("loopInput")).getOwner(); Assert.assertSame(LoopSubplan.class, allegedInnerLoopSubplan.getClass()); LoopSubplan innerSubplan = (LoopSubplan) allegedInnerLoopSubplan; Assert.assertEquals(1, innerSubplan.getNumOutputs()); Assert.assertEquals(1, innerSubplan.getNumInputs()); Assert.assertSame(innerLoopHead.getOutput("finalOutput"), innerSubplan.traceOutput(innerSubplan.getOutput(0))); innerInputs = new ArrayList<>(innerSubplan.followInput(innerSubplan.getInput(0))); Assert.assertEquals(1, innerInputs.size()); Assert.assertSame(innerLoopHead.getInput("initialInput"), innerInputs.get(0)); Assert.assertSame(innerSubplan, innerLoopHead.getParent()); Assert.assertSame(innerSubplan, inInnerLoopMap.getParent()); } |
ReduceByMapping implements Mapping { @Override public Collection<PlanTransformation> getTransformations() { return Collections.singleton(new PlanTransformation(this.createSubplanPattern(), new ReplacementFactory())); } @Override Collection<PlanTransformation> getTransformations(); } | @Test public void testMapping() { UnarySource<Tuple2<String, Integer>> source = new TestSource<>(DataSetType.createDefault(Tuple2.class)); final ProjectionDescriptor<Tuple2<String, Integer>, String> keyDescriptor = new ProjectionDescriptor<>( DataUnitType.createBasicUnchecked(Tuple2.class), DataUnitType.createBasic(String.class), "field0"); GroupByOperator<Tuple2<String, Integer>, String> groupBy = new GroupByOperator<>( keyDescriptor, DataSetType.createDefaultUnchecked(Tuple2.class), DataSetType.createGroupedUnchecked(Tuple2.class) ); source.connectTo(0, groupBy, 0); final ReduceDescriptor<Tuple2<String, Integer>> reduceDescriptor = new ReduceDescriptor<>( (a, b) -> a, DataUnitType.createGroupedUnchecked(Tuple2.class), DataUnitType.createBasicUnchecked(Tuple2.class) ); ReduceOperator<Tuple2<String, Integer>> reduce = ReduceOperator.createGroupedReduce( reduceDescriptor, DataSetType.createGroupedUnchecked(Tuple2.class), DataSetType.createDefaultUnchecked(Tuple2.class) ); groupBy.connectTo(0, reduce, 0); UnarySink<Tuple2<String, Integer>> sink = new TestSink<>(DataSetType.createDefaultUnchecked(Tuple2.class)); reduce.connectTo(0, sink, 0); RheemPlan plan = new RheemPlan(); plan.addSink(sink); Mapping mapping = new ReduceByMapping(); for (PlanTransformation planTransformation : mapping.getTransformations()) { planTransformation.thatReplaces().transform(plan, Operator.FIRST_EPOCH + 1); } final Operator finalSink = plan.getSinks().iterator().next(); final Operator inputOperator = finalSink.getEffectiveOccupant(0).getOwner(); Assert.assertTrue(inputOperator instanceof ReduceByOperator); ReduceByOperator reduceBy = (ReduceByOperator) inputOperator; Assert.assertEquals(keyDescriptor, reduceBy.getKeyDescriptor()); Assert.assertEquals(reduceDescriptor, reduceBy.getReduceDescriptor()); Assert.assertEquals(source, reduceBy.getEffectiveOccupant(0).getOwner()); } |
PlanTransformation { private void replace(RheemPlan plan, SubplanMatch match, Operator replacement) { final Operator originalInputOperator = match.getInputMatch().getOperator(); for (int inputIndex = 0; inputIndex < originalInputOperator.getNumInputs(); inputIndex++) { final InputSlot originalInputSlot = originalInputOperator.getInput(inputIndex); final OutputSlot occupant = originalInputSlot.getOccupant(); if (occupant != null) { occupant.disconnectFrom(originalInputSlot); occupant.connectTo(replacement.getInput(inputIndex)); } } final Operator originalOutputOperator = match.getOutputMatch().getOperator(); for (int outputIndex = 0; outputIndex < originalOutputOperator.getNumOutputs(); outputIndex++) { final OutputSlot originalOutputSlot = originalOutputOperator.getOutput(outputIndex); for (InputSlot inputSlot : new ArrayList<InputSlot>(originalOutputSlot.getOccupiedSlots())) { originalOutputSlot.disconnectFrom(inputSlot); replacement.getOutput(outputIndex).connectTo(inputSlot); } } if (originalOutputOperator.isSink()) { plan.getSinks().remove(originalOutputOperator); final Collection<Operator> sinks = new PlanTraversal(true, true) .traverse(replacement) .getTraversedNodesWith(Operator::isSink); for (Operator sink : sinks) { plan.addSink(sink); } } } PlanTransformation(SubplanPattern pattern,
ReplacementSubplanFactory replacementFactory,
Platform... targetPlatforms); PlanTransformation thatReplaces(); int transform(RheemPlan plan, int epoch); Collection<Platform> getTargetPlatforms(); } | @Test public void testReplace() { UnarySource source = new TestSource(DataSetType.createDefault(TestDataUnit.class)); UnarySink sink = new TestSink(DataSetType.createDefault(TestDataUnit.class)); source.connectTo(0, sink, 0); RheemPlan plan = new RheemPlan(); plan.addSink(sink); OperatorPattern sinkPattern = new OperatorPattern("sink", new TestSink(DataSetType.createDefault(TestDataUnit.class)), false); SubplanPattern subplanPattern = SubplanPattern.createSingleton(sinkPattern); ReplacementSubplanFactory replacementSubplanFactory = new TestSinkToTestSink2Factory(); PlanTransformation planTransformation = new PlanTransformation(subplanPattern, replacementSubplanFactory).thatReplaces(); planTransformation.transform(plan, Operator.FIRST_EPOCH + 1); Assert.assertEquals(1, plan.getSinks().size()); final Operator replacedSink = plan.getSinks().iterator().next(); Assert.assertTrue(replacedSink instanceof TestSink2); Assert.assertEquals(source, replacedSink.getEffectiveOccupant(0).getOwner()); } |
PlanTransformation { private void introduceAlternative(RheemPlan plan, SubplanMatch match, Operator replacement) { final Operator originalOutputOperator = match.getOutputMatch().getOperator(); boolean wasTopLevel = originalOutputOperator.getParent() == null; OperatorAlternative operatorAlternative = OperatorAlternative.wrap(match.getInputMatch().getOperator(), originalOutputOperator); if (wasTopLevel && originalOutputOperator.isSink()) { plan.replaceSink(originalOutputOperator, operatorAlternative); } operatorAlternative.addAlternative(replacement); } PlanTransformation(SubplanPattern pattern,
ReplacementSubplanFactory replacementFactory,
Platform... targetPlatforms); PlanTransformation thatReplaces(); int transform(RheemPlan plan, int epoch); Collection<Platform> getTargetPlatforms(); } | @Test public void testIntroduceAlternative() { UnarySource source = new TestSource(DataSetType.createDefault(TestDataUnit.class)); UnarySink sink = new TestSink(DataSetType.createDefault(TestDataUnit.class)); source.connectTo(0, sink, 0); RheemPlan plan = new RheemPlan(); plan.addSink(sink); OperatorPattern sinkPattern = new OperatorPattern("sink", new TestSink(DataSetType.createDefault(TestDataUnit.class)), false); SubplanPattern subplanPattern = SubplanPattern.createSingleton(sinkPattern); ReplacementSubplanFactory replacementSubplanFactory = new TestSinkToTestSink2Factory(); PlanTransformation planTransformation = new PlanTransformation(subplanPattern, replacementSubplanFactory); planTransformation.transform(plan, Operator.FIRST_EPOCH + 1); Assert.assertEquals(1, plan.getSinks().size()); final Operator replacedSink = plan.getSinks().iterator().next(); Assert.assertTrue(replacedSink instanceof OperatorAlternative); OperatorAlternative operatorAlternative = (OperatorAlternative) replacedSink; Assert.assertEquals(2, operatorAlternative.getAlternatives().size()); Assert.assertTrue(operatorAlternative.getAlternatives().get(0).getContainedOperator() instanceof TestSink); Assert.assertTrue(operatorAlternative.getAlternatives().get(1).getContainedOperator() instanceof TestSink2); Assert.assertEquals(source, replacedSink.getEffectiveOccupant(0).getOwner()); } |
PlanTransformation { public int transform(RheemPlan plan, int epoch) { int numTransformations = 0; List<SubplanMatch> matches = this.pattern.match(plan, epoch - 1); for (SubplanMatch match : matches) { if (!this.meetsPlatformRestrictions(match)) { continue; } final Operator replacement = this.replacementFactory.createReplacementSubplan(match, epoch); if (match.getInputMatch() == match.getOutputMatch()) { this.logger.debug("Replacing {} with {} in epoch {}.", match.getOutputMatch().getOperator(), replacement, epoch); } else { this.logger.debug("Replacing {}..{} with {} in epoch {}.", match.getInputMatch().getOperator(), match.getOutputMatch().getOperator(), replacement, epoch); } if (this.isReplacing) { this.replace(plan, match, replacement); } else { this.introduceAlternative(plan, match, replacement); } numTransformations++; } return numTransformations; } PlanTransformation(SubplanPattern pattern,
ReplacementSubplanFactory replacementFactory,
Platform... targetPlatforms); PlanTransformation thatReplaces(); int transform(RheemPlan plan, int epoch); Collection<Platform> getTargetPlatforms(); } | @Test public void testFlatAlternatives() { UnarySource source = new TestSource(DataSetType.createDefault(TestDataUnit.class)); UnarySink sink = new TestSink(DataSetType.createDefault(TestDataUnit.class)); source.connectTo(0, sink, 0); RheemPlan plan = new RheemPlan(); plan.addSink(sink); OperatorPattern sinkPattern = new OperatorPattern("sink", new TestSink(DataSetType.createDefault(TestDataUnit.class)), false); SubplanPattern subplanPattern = SubplanPattern.createSingleton(sinkPattern); ReplacementSubplanFactory replacementSubplanFactory = new TestSinkToTestSink2Factory(); PlanTransformation planTransformation = new PlanTransformation(subplanPattern, replacementSubplanFactory); planTransformation.transform(plan, Operator.FIRST_EPOCH + 1); planTransformation.transform(plan, Operator.FIRST_EPOCH + 1); Assert.assertEquals(1, plan.getSinks().size()); final Operator replacedSink = plan.getSinks().iterator().next(); Assert.assertTrue(replacedSink instanceof OperatorAlternative); OperatorAlternative operatorAlternative = (OperatorAlternative) replacedSink; Assert.assertEquals(3, operatorAlternative.getAlternatives().size()); Assert.assertTrue(operatorAlternative.getAlternatives().get(0).getContainedOperator() instanceof TestSink); Assert.assertTrue(operatorAlternative.getAlternatives().get(1).getContainedOperator() instanceof TestSink2); Assert.assertTrue(operatorAlternative.getAlternatives().get(2).getContainedOperator() instanceof TestSink2); Assert.assertEquals(source, replacedSink.getEffectiveOccupant(0).getOwner()); } |
StageAssignmentTraversal extends OneTimeExecutable { public static ExecutionPlan assignStages(ExecutionTaskFlow executionTaskFlow, StageSplittingCriterion... additionalSplittingCriteria) { final StageAssignmentTraversal instance = new StageAssignmentTraversal(executionTaskFlow, additionalSplittingCriteria); return instance.buildExecutionPlan(); } private StageAssignmentTraversal(ExecutionTaskFlow executionTaskFlow,
StageSplittingCriterion... splittingCriteria); static ExecutionPlan assignStages(ExecutionTaskFlow executionTaskFlow,
StageSplittingCriterion... additionalSplittingCriteria); } | @Test public void testCircularPlatformAssignment() { final Platform mockedPlatformA = MockFactory.createPlatform("A"); final Platform mockedPlatformB = MockFactory.createPlatform("B"); final Platform mockedPlatformC = MockFactory.createPlatform("C"); final ExecutionOperator sourceOpA = MockFactory.createExecutionOperator("source A", 0, 1, mockedPlatformA); final ExecutionTask sourceTaskA = new ExecutionTask(sourceOpA); final ExecutionOperator joinOpA = MockFactory.createExecutionOperator("join A", 2, 1, mockedPlatformA); final ExecutionTask joinTaskA = new ExecutionTask(joinOpA); final ExecutionOperator mapOpB = MockFactory.createExecutionOperator("map B", 1, 1, mockedPlatformB); final ExecutionTask mapTaskB = new ExecutionTask(mapOpB); final ExecutionOperator mapOpC = MockFactory.createExecutionOperator("map C", 1, 1, mockedPlatformC); final ExecutionTask mapTaskC = new ExecutionTask(mapOpC); final ExecutionOperator mapOpA = MockFactory.createExecutionOperator("map A", 1, 1, mockedPlatformA); final ExecutionTask mapTaskA = new ExecutionTask(mapOpA); final ExecutionOperator sinkOpA = MockFactory.createExecutionOperator("sink A", 1, 0, mockedPlatformA); final ExecutionTask sinkTaskA = new ExecutionTask(sinkOpA); Channel sourceTaskAChannel1 = new TestChannel(true); sourceTaskA.setOutputChannel(0, sourceTaskAChannel1); sourceTaskAChannel1.addConsumer(joinTaskA, 0); sourceTaskAChannel1.addConsumer(mapTaskB, 0); Channel mapTaskBChannel1 = new TestChannel(false); mapTaskB.setOutputChannel(0, mapTaskBChannel1); mapTaskBChannel1.addConsumer(mapTaskC, 0); Channel mapTaskCChannel1 = new TestChannel(false); mapTaskC.setOutputChannel(0, mapTaskCChannel1); mapTaskCChannel1.addConsumer(mapTaskA, 0); Channel mapTaskAChannel1 = new TestChannel(false); mapTaskA.setOutputChannel(0, mapTaskAChannel1); mapTaskAChannel1.addConsumer(joinTaskA, 1); Channel joinTaskAChannel1 = new TestChannel(false); joinTaskA.setOutputChannel(0, joinTaskAChannel1); joinTaskAChannel1.addConsumer(sinkTaskA, 0); ExecutionTaskFlow executionTaskFlow = new ExecutionTaskFlow(Collections.singleton(sinkTaskA)); final ExecutionPlan executionPlan = StageAssignmentTraversal.assignStages(executionTaskFlow); Assert.assertEquals(1, executionPlan.getStartingStages().size()); ExecutionStage stage1 = executionPlan.getStartingStages().stream().findAny().get(); Assert.assertEquals(1, stage1.getStartTasks().size()); ExecutionTask stage1Task1 = stage1.getStartTasks().stream().findAny().get(); Assert.assertEquals(sourceTaskA, stage1Task1); Assert.assertEquals(2, stage1.getSuccessors().size()); }
@Test public void testZigZag() { final Platform mockedPlatformA = MockFactory.createPlatform("A"); final Platform mockedPlatformB = MockFactory.createPlatform("B"); final ExecutionOperator sourceOpA = MockFactory.createExecutionOperator("source A", 0, 1, mockedPlatformA); final ExecutionTask sourceTaskA = new ExecutionTask(sourceOpA); final ExecutionOperator joinOpA = MockFactory.createExecutionOperator("join A", 2, 1, mockedPlatformA); final ExecutionTask joinTaskA = new ExecutionTask(joinOpA); final ExecutionOperator sinkOpA = MockFactory.createExecutionOperator("sink A", 2, 0, mockedPlatformA); final ExecutionTask sinkTaskA = new ExecutionTask(sinkOpA); final ExecutionOperator mapOpB = MockFactory.createExecutionOperator("map B", 1, 1, mockedPlatformB); final ExecutionTask mapTaskB = new ExecutionTask(mapOpB); final ExecutionOperator joinOpB = MockFactory.createExecutionOperator("join B", 2, 1, mockedPlatformB); final ExecutionTask joinTaskB = new ExecutionTask(joinOpB); Channel sourceTaskAChannel1 = new TestChannel(true); sourceTaskA.setOutputChannel(0, sourceTaskAChannel1); sourceTaskAChannel1.addConsumer(mapTaskB, 0); sourceTaskAChannel1.addConsumer(joinTaskA, 0); Channel mapTaskBChannel = new TestChannel(true); mapTaskB.setOutputChannel(0, mapTaskBChannel); mapTaskBChannel.addConsumer(joinTaskA, 1); mapTaskBChannel.addConsumer(joinTaskB, 0); Channel joinTaskAChannel = new TestChannel(true); joinTaskA.setOutputChannel(0, joinTaskAChannel); joinTaskAChannel.addConsumer(sinkTaskA, 0); joinTaskAChannel.addConsumer(joinTaskB, 1); Channel joinTaskBChannel = new TestChannel(true); joinTaskB.setOutputChannel(0, joinTaskBChannel); joinTaskBChannel.addConsumer(sinkTaskA, 1); ExecutionTaskFlow executionTaskFlow = new ExecutionTaskFlow(Collections.singleton(sinkTaskA)); final ExecutionPlan executionPlan = StageAssignmentTraversal.assignStages(executionTaskFlow); Assert.assertEquals(1, executionPlan.getStartingStages().size()); ExecutionStage stage1 = executionPlan.getStartingStages().stream().findAny().get(); Assert.assertEquals(1, stage1.getStartTasks().size()); ExecutionTask stage1Task1 = stage1.getStartTasks().stream().findAny().get(); Assert.assertEquals(sourceTaskA, stage1Task1); Assert.assertEquals(2, stage1.getSuccessors().size()); } |
AggregatingCardinalityEstimator implements CardinalityEstimator { @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { return this.alternativeEstimators.stream() .map(alternativeEstimator -> alternativeEstimator.estimate(optimizationContext, inputEstimates)) .sorted((estimate1, estimate2) -> Double.compare(estimate2.getCorrectnessProbability(), estimate1.getCorrectnessProbability())) .findFirst() .orElseThrow(IllegalStateException::new); } AggregatingCardinalityEstimator(List<CardinalityEstimator> alternativeEstimators); @Override CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates); } | @Test public void testEstimate() { OptimizationContext optimizationContext = mock(OptimizationContext.class); when(optimizationContext.getConfiguration()).thenReturn(new Configuration()); CardinalityEstimator partialEstimator1 = new DefaultCardinalityEstimator(0.9, 1, false, cards -> cards[0] * 2); CardinalityEstimator partialEstimator2 = new DefaultCardinalityEstimator(0.8, 1, false, cards -> cards[0] * 3); CardinalityEstimator estimator = new AggregatingCardinalityEstimator( Arrays.asList(partialEstimator1, partialEstimator2) ); CardinalityEstimate inputEstimate = new CardinalityEstimate(10, 100, 0.3); CardinalityEstimate outputEstimate = estimator.estimate(optimizationContext, inputEstimate); CardinalityEstimate expectedEstimate = new CardinalityEstimate(2 * 10, 2 * 100, 0.3 * 0.9); Assert.assertEquals(expectedEstimate, outputEstimate); } |
SubplanCardinalityPusher extends CardinalityPusher { public static CardinalityPusher createFor(OperatorContainer container, Configuration configuration) { final CompositeOperator compositeOperator = container.toOperator(); final InputSlot<?>[] outerInputs = compositeOperator.getAllInputs(); final List<InputSlot<?>> innerInputs = Arrays.stream(outerInputs) .flatMap(inputSlot -> container.followInput(inputSlot).stream()) .collect(Collectors.toList()); final Collection<Operator> sourceOperators = compositeOperator.isSource() ? Collections.singleton(container.getSource()) : Collections.emptySet(); final CardinalityEstimationTraversal traversal = CardinalityEstimationTraversal.createPushTraversal( innerInputs, sourceOperators, configuration); return new SubplanCardinalityPusher(traversal, compositeOperator); } private SubplanCardinalityPusher(CardinalityEstimationTraversal traversal, final CompositeOperator compositeOperator); static CardinalityPusher createFor(OperatorContainer container, Configuration configuration); } | @Test public void testSimpleSubplan() { TestMapOperator<String, String> op1 = new TestMapOperator<>( DataSetType.createDefault(String.class), DataSetType.createDefault(String.class) ); TestMapOperator<String, String> op2 = new TestMapOperator<>( DataSetType.createDefault(String.class), DataSetType.createDefault(String.class) ); op1.connectTo(0, op2, 0); Subplan subplan = (Subplan) Subplan.wrap(op1, op2); OptimizationContext optimizationContext = new DefaultOptimizationContext(this.job, subplan); final OptimizationContext.OperatorContext subplanCtx = optimizationContext.getOperatorContext(subplan); final CardinalityEstimate inputCardinality = new CardinalityEstimate(123, 321, 0.123d); subplanCtx.setInputCardinality(0, inputCardinality); subplan.propagateInputCardinality(0, subplanCtx); final CardinalityPusher pusher = SubplanCardinalityPusher.createFor(subplan, this.configuration); pusher.push(subplanCtx, this.configuration); Assert.assertEquals(inputCardinality, subplanCtx.getOutputCardinality(0)); }
@Test public void testSourceSubplan() { TestSource<String> source = new TestSource<>(DataSetType.createDefault(String.class)); final CardinalityEstimate sourceCardinality = new CardinalityEstimate(123, 321, 0.123d); source.setCardinalityEstimators((optimizationContext, inputEstimates) -> sourceCardinality); TestMapOperator<String, String> op = new TestMapOperator<>( DataSetType.createDefault(String.class), DataSetType.createDefault(String.class) ); source.connectTo(0, op, 0); Subplan subplan = (Subplan) Subplan.wrap(source, op); OptimizationContext optimizationContext = new DefaultOptimizationContext(this.job, subplan); final OptimizationContext.OperatorContext subplanCtx = optimizationContext.getOperatorContext(subplan); final CardinalityPusher pusher = SubplanCardinalityPusher.createFor(subplan, this.configuration); pusher.push(subplanCtx, this.configuration); Assert.assertEquals(sourceCardinality, subplanCtx.getOutputCardinality(0)); }
@Test public void testDAGShapedSubplan() { final DataSetType<String> stringDataSetType = DataSetType.createDefault(String.class); TestMapOperator<String, String> map1 = new TestMapOperator<>(stringDataSetType, stringDataSetType); map1.setName("map1"); TestMapOperator<String, String> map2 = new TestMapOperator<>(stringDataSetType, stringDataSetType); map2.setName("map2"); TestMapOperator<String, String> map3 = new TestMapOperator<>(stringDataSetType, stringDataSetType); map3.setName("map3"); TestJoin<String, String, String> join1 = new TestJoin<>(stringDataSetType, stringDataSetType, stringDataSetType); join1.setName("join1"); TestMapOperator<String, String> map4 = new TestMapOperator<>(stringDataSetType, stringDataSetType); map4.setName("map4"); map1.connectTo(0, map2, 0); map1.connectTo(0, map3, 0); map2.connectTo(0, join1, 0); map3.connectTo(0, join1, 1); join1.connectTo(0, map4, 0); Subplan subplan = (Subplan) Subplan.wrap(map1, map4); OptimizationContext optimizationContext = new DefaultOptimizationContext(this.job, subplan); final OptimizationContext.OperatorContext subplanCtx = optimizationContext.getOperatorContext(subplan); final CardinalityEstimate inputCardinality = new CardinalityEstimate(10, 100, 0.9d); subplanCtx.setInputCardinality(0, inputCardinality); subplan.propagateInputCardinality(0, subplanCtx); final CardinalityPusher pusher = SubplanCardinalityPusher.createFor(subplan, this.configuration); pusher.push(subplanCtx, this.configuration); final CardinalityEstimate outputCardinality = subplanCtx.getOutputCardinality(0); final CardinalityEstimate expectedCardinality = new CardinalityEstimate(10 * 10, 100 * 100, 0.9d * 0.7d); Assert.assertEquals(expectedCardinality, outputCardinality); } |
RecordType extends BasicDataUnitType<Record> { @Override public boolean isSupertypeOf(BasicDataUnitType<?> that) { return this.equals(that); } RecordType(String... fieldNames); String[] getFieldNames(); @Override boolean isSupertypeOf(BasicDataUnitType<?> that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); int getIndex(String fieldName); } | @Test public void testSupertype() { DataSetType<Record> t1 = DataSetType.createDefault(Record.class); DataSetType<Record> t2 = DataSetType.createDefault(new RecordType("a", "b")); DataSetType<Record> t3 = DataSetType.createDefault(new RecordType("a", "b", "c")); Assert.assertTrue(t1.isSupertypeOf(t2)); Assert.assertFalse(t2.isSupertypeOf(t1)); Assert.assertTrue(t1.isSupertypeOf(t3)); Assert.assertFalse(t3.isSupertypeOf(t1)); Assert.assertTrue(t2.isSupertypeOf(t2)); Assert.assertFalse(t2.isSupertypeOf(t3)); Assert.assertTrue(t3.isSupertypeOf(t3)); Assert.assertFalse(t3.isSupertypeOf(t2)); } |
DefaultCardinalityEstimator implements CardinalityEstimator { @Override public CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates) { assert inputEstimates.length == this.numInputs || (this.isAllowMoreInputs && inputEstimates.length > this.numInputs) : String.format("Received %d input estimates, require %d%s.", inputEstimates.length, this.numInputs, this.isAllowMoreInputs ? "+" : ""); if (this.numInputs == 0) { final long estimate = this.singlePointEstimator.applyAsLong(new long[0], optimizationContext.getConfiguration()); return new CardinalityEstimate(estimate, estimate, this.certaintyProb); } long[] lowerAndUpperInputEstimates = this.extractEstimateValues(inputEstimates); long lowerEstimate = -1, upperEstimate = -1; long[] currentInputEstimates = new long[this.numInputs]; final int maximumBitMaskValue = 1 << this.numInputs; for (long positionBitmask = 0; positionBitmask < maximumBitMaskValue; positionBitmask++) { for (int pos = 0; pos < this.numInputs; pos++) { int bit = (int) ((positionBitmask >>> pos) & 0x1); currentInputEstimates[pos] = lowerAndUpperInputEstimates[(pos << 1) + bit]; } long currentEstimate = Math.max( this.singlePointEstimator.applyAsLong(currentInputEstimates, optimizationContext.getConfiguration()), 0 ); if (lowerEstimate == -1 || currentEstimate < lowerEstimate) { lowerEstimate = currentEstimate; } if (upperEstimate == -1 || currentEstimate > upperEstimate) { upperEstimate = currentEstimate; } } double correctnessProb = this.certaintyProb * Arrays.stream(inputEstimates) .mapToDouble(CardinalityEstimate::getCorrectnessProbability) .min() .orElseThrow(IllegalStateException::new); return new CardinalityEstimate(lowerEstimate, upperEstimate, correctnessProb); } DefaultCardinalityEstimator(double certaintyProb,
int numInputs,
boolean isAllowMoreInputs,
ToLongFunction<long[]> singlePointEstimator); DefaultCardinalityEstimator(double certaintyProb,
int numInputs,
boolean isAllowMoreInputs,
ToLongBiFunction<long[], Configuration> singlePointEstimator); @Override CardinalityEstimate estimate(OptimizationContext optimizationContext, CardinalityEstimate... inputEstimates); } | @Test public void testBinaryInputEstimation() { OptimizationContext optimizationContext = mock(OptimizationContext.class); when(optimizationContext.getConfiguration()).thenReturn(new Configuration()); CardinalityEstimate inputEstimate1 = new CardinalityEstimate(50, 60, 0.8); CardinalityEstimate inputEstimate2 = new CardinalityEstimate(10, 100, 0.4); final ToLongFunction<long[]> singlePointEstimator = inputEstimates -> (long) Math.ceil(0.8 * inputEstimates[0] * inputEstimates[1]); CardinalityEstimator estimator = new DefaultCardinalityEstimator( 0.9, 2, false, singlePointEstimator ); CardinalityEstimate estimate = estimator.estimate(optimizationContext, inputEstimate1, inputEstimate2); Assert.assertEquals(0.9 * 0.4, estimate.getCorrectnessProbability(), 0.001); Assert.assertEquals(singlePointEstimator.applyAsLong(new long[]{50, 10}), estimate.getLowerEstimate()); Assert.assertEquals(singlePointEstimator.applyAsLong(new long[]{60, 100}), estimate.getUpperEstimate()); } |
RheemCollections { public static <T> Collection<List<T>> createPowerList(Collection<T> base) { return createPowerList(base, base.size()); } private RheemCollections(); static void put(Map<K, Collection<V>> map, K key, V value); static Set<T> asSet(Collection<T> collection); static Set<T> asSet(Iterable<T> iterable); static Set<T> asSet(T... values); static List<T> asList(Collection<T> collection); static C asCollection(Iterable<T> iterable, Supplier<C> collectionFactory); static T getSingle(Collection<T> collection); static T getSingleOrNull(Collection<T> collection); static T getAny(Iterable<T> iterable); static java.util.Optional<T> getAnyOptional(Iterable<T> iterable); static C add(C collection, T element); static C addAll(C collection, C elements); static List<T> map(List<S> list, Function<S, T> mapFunction); static List<T> map(List<S> list, BiFunction<Integer, S, T> mapFunction); static Iterable<List<T>> streamedCrossProduct(List<? extends Iterable<T>> iterables); static ArrayList<T> createNullFilledArrayList(int k); static Collection<List<T>> createPowerList(Collection<T> base); static Collection<List<T>> createPowerList(Collection<T> base, int maxElements); static Map<K, V> createMap(Tuple<K, V>... keyValuePairs); } | @Test public void testCreatePowerList() { final List<Integer> list = RheemArrays.asList(0, 1, 2, 3, 4); final Collection<List<Integer>> powerList = RheemCollections.createPowerList(list, 3); Assert.assertEquals(1 + 5 + 10 + 10, powerList.size()); List<List<Integer>> expectedPowerSetMembers = Arrays.asList( RheemArrays.asList(), RheemArrays.asList(0), RheemArrays.asList(1), RheemArrays.asList(2), RheemArrays.asList(3), RheemArrays.asList(4), RheemArrays.asList(0, 1), RheemArrays.asList(0, 2), RheemArrays.asList(0, 3), RheemArrays.asList(0, 4), RheemArrays.asList(1, 2), RheemArrays.asList(1, 3), RheemArrays.asList(1, 4), RheemArrays.asList(2, 3), RheemArrays.asList(2, 4), RheemArrays.asList(3, 4), RheemArrays.asList(0, 1, 2), RheemArrays.asList(0, 1, 3), RheemArrays.asList(0, 1, 4), RheemArrays.asList(0, 2, 3), RheemArrays.asList(0, 2, 4), RheemArrays.asList(0, 3, 4), RheemArrays.asList(1, 2, 3), RheemArrays.asList(1, 2, 4), RheemArrays.asList(1, 3, 4), RheemArrays.asList(2, 3, 4) ); for (List<Integer> expectedPowerSetMember : expectedPowerSetMembers) { Assert.assertTrue(String.format("%s is not contained in %s.", expectedPowerSetMember, powerList), powerList.contains(expectedPowerSetMember)); } } |
ReflectionUtils { public static <T> T evaluate(String statement) throws IllegalArgumentException { statement = statement.trim(); Matcher matcher = defaultConstructorPattern.matcher(statement); if (matcher.matches()) { try { return instantiateDefault(matcher.group(1)); } catch (Exception e) { throw new IllegalArgumentException(String.format("Could not instantiate '%s'.", statement), e); } } matcher = arglessMethodPattern.matcher(statement); if (matcher.matches()) { try { return executeStaticArglessMethod(matcher.group(1), matcher.group(2)); } catch (Exception e) { throw new IllegalArgumentException(String.format("Could not execute '%s'.", statement), e); } } matcher = constantPattern.matcher(statement); if (matcher.matches()) { try { return retrieveStaticVariable(matcher.group(1), matcher.group(2)); } catch (Exception e) { throw new IllegalArgumentException(String.format("Could not execute '%s'.", statement), e); } } throw new IllegalArgumentException(String.format("Unknown expression type: '%s'.", statement)); } static String getDeclaringJar(Object object); static String getDeclaringJar(Class<?> cls); static InputStream loadResource(String resourceName); static URL getResourceURL(String resourceName); @SuppressWarnings("unchecked") static Class<T> specify(Class<? super T> baseClass); @SuppressWarnings("unchecked") static Class<T> generalize(Class<? extends T> baseClass); static T evaluate(String statement); @SuppressWarnings("unchecked") static T executeStaticArglessMethod(String className, String methodName); @SuppressWarnings("unchecked") static T retrieveStaticVariable(String className, String variableName); static T instantiateDefault(String className); static T instantiateDefault(Class<? extends T> cls); @SuppressWarnings("unchecked") static T instantiateSomehow(Class<T> cls, Tuple<Class<?>, Supplier<?>>... defaultParameters); @SuppressWarnings("unchecked") static T instantiateSomehow(Class<T> cls, List<Tuple<Class<?>, Supplier<?>>> defaultParameters); static Map<String, Type> getTypeParameters(Class<?> subclass, Class<?> superclass); @SuppressWarnings("unchecked") static T getProperty(Object obj, String property); static double toDouble(Object o); static Type getWrapperClass(Type type, int index); } | @Test public void testEvaluateWithInstantiation() { final Object val = ReflectionUtils.evaluate("new java.lang.String()"); Assert.assertEquals("", val); }
@Test public void testEvaluateWithStaticVariable() { final Object val = ReflectionUtils.evaluate("io.rheem.core.util.ReflectionUtilsTest.TEST_INT"); Assert.assertEquals(42, val); }
@Test public void testEvaluateWithStaticMethod() { final Object val = ReflectionUtils.evaluate("io.rheem.core.util.ReflectionUtilsTest.testInt()"); Assert.assertEquals(23, val); } |
ReflectionUtils { public static Map<String, Type> getTypeParameters(Class<?> subclass, Class<?> superclass) { List<Type> genericSupertypes = Stream.concat( Stream.of(subclass.getGenericSuperclass()), Stream.of(subclass.getGenericInterfaces()) ).collect(Collectors.toList()); for (Type supertype : genericSupertypes) { if (supertype instanceof Class<?>) { Class<?> cls = (Class<?>) supertype; if (!superclass.isAssignableFrom(cls)) continue; return getTypeParameters(cls, superclass); } else if (supertype instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) supertype; final Type rawType = parameterizedType.getRawType(); if (!(rawType instanceof Class<?>)) continue; Class<?> cls = (Class<?>) rawType; if (!superclass.isAssignableFrom(cls)) continue; final Map<String, Type> localTypeArguments = getTypeArguments(parameterizedType); if (cls.equals(superclass)) { return localTypeArguments; } else { final Map<String, Type> preliminaryResult = getTypeParameters(cls, superclass); final Map<String, Type> result = new HashMap<>(preliminaryResult.size()); for (Map.Entry<String, Type> entry : preliminaryResult.entrySet()) { if (entry.getValue() instanceof TypeVariable<?>) { final Type translatedTypeArgument = localTypeArguments.getOrDefault( ((TypeVariable) entry.getValue()).getName(), entry.getValue() ); result.put(entry.getKey(), translatedTypeArgument); } else { result.put(entry.getKey(), entry.getValue()); } } return result; } } } return Collections.emptyMap(); } static String getDeclaringJar(Object object); static String getDeclaringJar(Class<?> cls); static InputStream loadResource(String resourceName); static URL getResourceURL(String resourceName); @SuppressWarnings("unchecked") static Class<T> specify(Class<? super T> baseClass); @SuppressWarnings("unchecked") static Class<T> generalize(Class<? extends T> baseClass); static T evaluate(String statement); @SuppressWarnings("unchecked") static T executeStaticArglessMethod(String className, String methodName); @SuppressWarnings("unchecked") static T retrieveStaticVariable(String className, String variableName); static T instantiateDefault(String className); static T instantiateDefault(Class<? extends T> cls); @SuppressWarnings("unchecked") static T instantiateSomehow(Class<T> cls, Tuple<Class<?>, Supplier<?>>... defaultParameters); @SuppressWarnings("unchecked") static T instantiateSomehow(Class<T> cls, List<Tuple<Class<?>, Supplier<?>>> defaultParameters); static Map<String, Type> getTypeParameters(Class<?> subclass, Class<?> superclass); @SuppressWarnings("unchecked") static T getProperty(Object obj, String property); static double toDouble(Object o); static Type getWrapperClass(Type type, int index); } | @Test public void testGetTypeParametersWithReusedTypeParameters() { MyParameterizedClassA<Integer, String> myParameterizedObject = new MyParameterizedClassB<Integer, String>() { }; Map<String, Type> expectedTypeParameters = new HashMap<>(); expectedTypeParameters.put("A", Integer.class); expectedTypeParameters.put("B", String.class); final Map<String, Type> typeParameters = ReflectionUtils.getTypeParameters( myParameterizedObject.getClass(), MyParameterizedClassA.class ); Assert.assertEquals(expectedTypeParameters, typeParameters); }
@Test public void testGetTypeParametersWithIndirectTypeParameters() { MyParameterizedClassC myParameterizedObject = new MyParameterizedClassC() { }; Map<String, Type> expectedTypeParameters = new HashMap<>(); expectedTypeParameters.put("A", Long.class); final Map<String, Type> typeParameters = ReflectionUtils.getTypeParameters( myParameterizedObject.getClass(), MyParameterizedInterface.class ); Assert.assertEquals(expectedTypeParameters, typeParameters); } |
Bitmask implements Cloneable, Iterable<Integer> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Bitmask that = (Bitmask) o; if (this.cardinalityCache != -1 && that.cardinalityCache != -1 && this.cardinalityCache != that.cardinalityCache) { return false; } final Bitmask smallInstance; final Bitmask largeInstance; if (this.bits.length < that.bits.length) { smallInstance = this; largeInstance = that; } else { smallInstance = that; largeInstance = this; } for (int i = 0; i < smallInstance.bits.length; i++) { if (smallInstance.bits[i] != largeInstance.bits[i]) return false; } for (int i = smallInstance.bits.length; i < largeInstance.bits.length; i++) { if (largeInstance.bits[i] != 0L) return false; } return true; } Bitmask(); Bitmask(int startCapacity); Bitmask(Bitmask that); Bitmask(Bitmask that, int startCapacity); boolean set(int index); boolean get(int index); int cardinality(); boolean isEmpty(); Bitmask orInPlace(Bitmask that); Bitmask or(Bitmask that); Bitmask andInPlace(Bitmask that); Bitmask and(Bitmask that); Bitmask andNotInPlace(Bitmask that); Bitmask andNot(Bitmask that); Bitmask flip(int fromIndex, int toIndex); boolean isSubmaskOf(Bitmask that); boolean isDisjointFrom(Bitmask that); int nextSetBit(int from); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); IntStream stream(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); static Bitmask EMPTY_BITMASK; } | @Test public void testEquals() { Bitmask bitmask1 = createBitmask(64, 0, 3); Bitmask bitmask2 = createBitmask(256, 0, 3); Bitmask bitmask3 = createBitmask(256, 0, 3, 68); Assert.assertEquals(bitmask1, bitmask2); Assert.assertEquals(bitmask2, bitmask1); Assert.assertNotEquals(bitmask1, bitmask3); Assert.assertNotEquals(bitmask3, bitmask1); Assert.assertNotEquals(bitmask2, bitmask3); Assert.assertNotEquals(bitmask3, bitmask2); } |
CliArguments { public static CliArguments fromArgs(String... args) { final CliArguments arguments = new CliArguments(); JCommander.newBuilder() .addObject(arguments) .build().parse(args); arguments.validate(); return arguments; } CliArguments(); CliArguments(PasswordReader passwordReader); Algorithm algorithm(); String username(); String password(); int cost(); int iterations(); int keyLength(); String salt(); void validate(); static CliArguments fromArgs(String... args); boolean help(); } | @Test public void shouldErrorOutEncryptionAlgorithmIsNotSpecified() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Expected encryption algorithm: [-B, -P, -S]"); String[] args = {"-u", "admin", "-p", "badger"}; CliArguments.fromArgs(args); }
@Test public void shouldErrorOutOnInvalidBCryptArguments() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Argument to -C must be an integer value: 4 to 31"); String[] args = {"-B", "-u", "admin", "-p", "badger", "-C", "1"}; CliArguments.fromArgs(args); }
@Test public void shouldErrorOutIfRequiredOptionsMissingInCliArguments() throws Exception { thrown.expect(ParameterException.class); thrown.expectMessage("The following option is required: [-u]"); String[] args = {"-p", "badger"}; CliArguments.fromArgs(args); } |
Authenticator { public User authenticate(Credentials credentials, List<AuthConfig> authConfigs) throws IOException, NoSuchAlgorithmException { for (AuthConfig authConfig : authConfigs) { LOG.debug(String.format("[Authenticate] Authenticating User: %s using auth_config: %s", credentials.getUsername(), authConfig.getId())); try { final String passwordFilePath = authConfig.getConfiguration().getPasswordFilePath(); LOG.debug(String.format("[Authenticate] Fetching all user information from password file: %s", passwordFilePath)); Map<String, UserDetails> userMap = buildUserMap(passwordFileReader.read(passwordFilePath)); LOG.debug("[Authenticate] Done fetching all user information from password file."); UserDetails userDetails = userMap.get(credentials.getUsername().toLowerCase()); if (userDetails == null) { LOG.debug(String.format("[Authenticate] No user found with username: %s in auth config %s.", credentials.getUsername(), authConfig.getId())); continue; } LOG.debug(String.format("[Authenticate] Finding algorithm used for hashing password of user %s.", userDetails.username)); Algorithm algorithm = algorithmIdentifier.identify(userDetails.password); LOG.debug(String.format("[Authenticate] Algorithm found: %s.", algorithm.getName())); if (algorithm == Algorithm.SHA1) { LOG.warn(String.format("[Authenticate] User `%s`'s password is hashed using SHA1. Please use bcrypt hashing instead.", credentials.getUsername())); } LOG.debug("[Authenticate] Start matching input password with hashed password."); if (algorithm.matcher().matches(credentials.getPassword(), userDetails.password)) { LOG.info(String.format("[Authenticate] User `%s` successfully authenticated using auth config: %s", credentials.getUsername(), authConfig.getId())); return new User(userDetails.username, userDetails.username, null); } } catch (Exception e) { LOG.info(String.format("[Authenticate] Failed to authenticate user: %s using auth_config: %s", credentials.getUsername(), authConfig.getId())); LOG.debug("Exception: ", e); } } throw new AuthenticationException("Unable to authenticate user, user not found or bad credentials"); } Authenticator(); Authenticator(PasswordFileReader passwordFileReader, AlgorithmIdentifier algorithmIdentifier); User authenticate(Credentials credentials, List<AuthConfig> authConfigs); } | @Test public void shouldAuthenticateBCryptHashedPassword2AFormat() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "$2a$10$TpJTztc1Qpzpwd.HVjBvG.HlVLMYdMak1JYyi7yZQ6NC/aLgYiQpi"); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("$2a$10$TpJTztc1Qpzpwd.HVjBvG.HlVLMYdMak1JYyi7yZQ6NC/aLgYiQpi")).thenReturn(Algorithm.BCRYPT); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test public void shouldAuthenticateBCryptHashedPassword2bFormat() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "$2b$12$GhvMmNVjRW29ulnudl.LbuAnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m"); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("$2b$12$GhvMmNVjRW29ulnudl.LbuAnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m")).thenReturn(Algorithm.BCRYPT); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test(expected = AuthenticationException.class) public void shouldErrorOutIfFailedToAuthenticateUsingBCrypt() throws Exception { Credentials credentials = new Credentials("username", "badger"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "$2b$12$GhvMmNVjRW29ulnudl.LbuAnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m"); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("$2b$12$GhvMmNVjRW29ulnudl.LbuAnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m")).thenReturn(Algorithm.BCRYPT); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void shouldAuthenticatePBKDF2SHA1Format() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA1") .append("$1000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$08B9DF198D32E133ED25A0F54F8CDFDFE9E17CCBE8EB179172656A39778FBCE5").toString(); Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", hashed); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify(hashed)).thenReturn(Algorithm.PBKDF2WithHmacSHA1); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test(expected = AuthenticationException.class) public void shouldErrorOutIfFailedToAuthenticateUsingPBKDF2WithHmacSHA1() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA1") .append("$1000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$08B9DF198D32E133ED25A0F54F8CDFDFE9E17CCBE8EB179172656A39778FBCE5").toString(); Credentials credentials = new Credentials("username", "badger"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", hashed); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify(hashed)).thenReturn(Algorithm.PBKDF2WithHmacSHA1); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void shouldAuthenticatePBKDF2SHA256Format() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA256") .append("$2000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$42C61B48A132140583110B91E1D80C2B56CCC4DBCF835DAC4C0353C795C78A34").toString(); Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", hashed); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify(hashed)).thenReturn(Algorithm.PBKDF2WithHmacSHA256); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test(expected = AuthenticationException.class) public void shouldErrorOutIfFailedToAuthenticateUsingPBKDF2WithHmacSHA256() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA256") .append("$2000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$42C61B48A132140583110B91E1D80C2B56CCC4DBCF835DAC4C0353C795C78A34").toString(); Credentials credentials = new Credentials("username", "badger"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", hashed); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify(hashed)).thenReturn(Algorithm.PBKDF2WithHmacSHA256); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void authenticate_shouldMakeCaseInsensitiveMatchOfUsername() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("USERnamE", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("USERnamE", "USERnamE", null))); }
@Test public void shouldAuthenticateUserWithPasswordHavingSHAPrefix() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test public void shouldErrorOutInCaseOfInvalidPassword() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "invalid-password"); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); thrown.expect(AuthenticationException.class); thrown.expectMessage("Unable to authenticate user, user not found or bad credentials"); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void shouldErrorOutInCaseOfUserNotExistInPasswordFile() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); thrown.expect(AuthenticationException.class); thrown.expectMessage("Unable to authenticate user, user not found or bad credentials"); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void shouldAuthenticateUserInCaseOfMultipleAuthConfigs() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig1 = AuthConfigMother.authConfigWith("/var/etc/password_1.properties"); AuthConfig authConfig2 = AuthConfigMother.authConfigWith("/var/etc/password_2.properties"); final Properties properties = new Properties(); when(passwordFileReader.read(authConfig1.getConfiguration().getPasswordFilePath())).thenReturn(properties); final Properties validProperties = new Properties(); validProperties.put("username", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig2.getConfiguration().getPasswordFilePath())).thenReturn(validProperties); authenticator.authenticate(credentials, Arrays.asList(authConfig1, authConfig2)); }
@Test public void shouldNotErrorOutIfAuthenticationUsingAAuthConfigThrowsException() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig1 = AuthConfigMother.authConfigWith("/var/etc/password_1.properties"); AuthConfig authConfig2 = AuthConfigMother.authConfigWith("/var/etc/password_2.properties"); when(passwordFileReader.read(authConfig1.getConfiguration().getPasswordFilePath())).thenThrow(new RuntimeException()); final Properties validProperties = new Properties(); validProperties.put("username", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig2.getConfiguration().getPasswordFilePath())).thenReturn(validProperties); authenticator.authenticate(credentials, Arrays.asList(authConfig1, authConfig2)); }
@Test public void shouldAuthenticateUserAgainstASingleAuthConfigInCaseOfMultipleAuthConfigs() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig1 = AuthConfigMother.authConfigWith("/var/etc/password_1.properties"); AuthConfig authConfig2 = AuthConfigMother.authConfigWith("/var/etc/password_2.properties"); final Properties properties = new Properties(); properties.put("username", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig1.getConfiguration().getPasswordFilePath())).thenReturn(properties); authenticator.authenticate(credentials, Arrays.asList(authConfig1, authConfig2)); verify(passwordFileReader, times(0)).read(authConfig2.getConfiguration().getPasswordFilePath()); }
@Test public void shouldAuthenticateSHA1HashedPassword() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("W6ph5Mm5Pz8GgiULbPgzG37mj9g=")).thenReturn(Algorithm.SHA1); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); }
@Test(expected = AuthenticationException.class) public void shouldErrorOutIfFailedToAuthenticateUsingSHA1() throws Exception { Credentials credentials = new Credentials("username", "badger"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "W6ph5Mm5Pz8GgiULbPgzG37mj9g="); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("W6ph5Mm5Pz8GgiULbPgzG37mj9g=")).thenReturn(Algorithm.SHA1); authenticator.authenticate(credentials, Collections.singletonList(authConfig)); }
@Test public void shouldAuthenticateBCryptHashedPassword2YFormat() throws Exception { Credentials credentials = new Credentials("username", "password"); AuthConfig authConfig = AuthConfigMother.authConfigWith("/var/etc/password.properties"); final Properties properties = new Properties(); properties.put("username", "$2y$12$ctTt.M5B/A4EuehlSgOLcugsPP4nu01aNPWI6nZpX6w8Z6SHa5d72"); when(passwordFileReader.read(authConfig.getConfiguration().getPasswordFilePath())).thenReturn(properties); when(algorithmIdentifier.identify("$2y$12$ctTt.M5B/A4EuehlSgOLcugsPP4nu01aNPWI6nZpX6w8Z6SHa5d72")).thenReturn(Algorithm.BCRYPT); final User user = authenticator.authenticate(credentials, Collections.singletonList(authConfig)); assertThat(user, is(new User("username", "username", null))); } |
IsValidUserRequestExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = GSON.fromJson(request.requestBody(), JsonObject.class); Type type = new TypeToken<AuthConfig>() {}.getType(); String username = jsonObject.get("username").getAsString(); AuthConfig authConfig = GSON.fromJson(jsonObject.get("auth_config").toString(), type); final User found = find(username, authConfig); if (found != null) { return new DefaultGoPluginApiResponse(200); } return new DefaultGoPluginApiResponse(404); } IsValidUserRequestExecutor(GoPluginApiRequest request); protected IsValidUserRequestExecutor(GoPluginApiRequest request, PasswordFileReader passwordFileReader); @Override GoPluginApiResponse execute(); User find(String username, AuthConfig authConfig); } | @Test public void shouldReturn200WhenTheCurrentUserExistsInThePasswordFile() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); final Properties properties = new Properties(); properties.put("bob", "password1"); when(fileReader.read("/var/etc/password.properties")).thenReturn(properties); when(request.requestBody()).thenReturn(requestJson("bob")); final GoPluginApiResponse response = new IsValidUserRequestExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(200)); }
@Test public void shouldReturn404WhenTheCurrentUserDoesNotExistsInThePasswordFile() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); final Properties properties = new Properties(); properties.put("bob", "password1"); when(fileReader.read("/var/etc/password.properties")).thenReturn(properties); when(request.requestBody()).thenReturn(requestJson("john")); final GoPluginApiResponse response = new IsValidUserRequestExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(404)); }
@Test public void shouldLookForExactUsernameMatchInsteadOfRegExp() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); final Properties properties = new Properties(); properties.put("bobby", "password1"); when(fileReader.read("/var/etc/password.properties")).thenReturn(properties); when(request.requestBody()).thenReturn(requestJson("bob")); final GoPluginApiResponse response = new IsValidUserRequestExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(404)); }
@Test public void shouldLookForCaseInsensitiveUsernameMatch() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); final Properties properties = new Properties(); properties.put("bob", "password1"); when(fileReader.read("/var/etc/password.properties")).thenReturn(properties); when(request.requestBody()).thenReturn(requestJson("BoB")); final GoPluginApiResponse response = new IsValidUserRequestExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(200)); } |
GetPluginIconExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("content_type", getContentType()); jsonObject.addProperty("data", Base64.getEncoder().encodeToString(Util.readResourceBytes(getIcon()))); DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200, GSON.toJson(jsonObject)); return defaultGoPluginApiResponse; } @Override GoPluginApiResponse execute(); } | @Test public void rendersIconInBase64() throws Exception { GoPluginApiResponse response = new GetPluginIconExecutor().execute(); HashMap<String, String> hashMap = new Gson().fromJson(response.responseBody(), HashMap.class); assertThat(hashMap.size(), is(2)); assertThat(hashMap.get("content_type"), is("image/png")); assertThat(Util.readResourceBytes("/gocd_72_72_icon.png"), is(Base64.getDecoder().decode(hashMap.get("data")))); } |
UserAuthenticationExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { Credentials credentials = Credentials.fromJSON(request.requestBody()); final List<AuthConfig> authConfigs = AuthConfig.fromJSONList(request.requestBody()); Map<String, Object> userMap = new HashMap<>(); try { final User user = authenticator.authenticate(credentials, authConfigs); userMap.put("user", user); userMap.put("roles", Collections.emptyList()); return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, GSON.toJson(userMap)); } catch (AuthenticationException e) { LOG.info("[Authenticate] Failed to authenticate user: " + credentials.getUsername() + "."); LOG.debug(String.format("[Authenticate] Failed to authenticate user: `%s`", credentials.getUsername()), e); return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, GSON.toJson(userMap)); } } UserAuthenticationExecutor(GoPluginApiRequest request, Authenticator authenticator); @Override GoPluginApiResponse execute(); } | @Test public void shouldAuthenticate() throws Exception { final GoPluginApiRequest goApiRequest = mock(GoPluginApiRequest.class); final String requestBody = requestJson("username", "password"); when(goApiRequest.requestBody()).thenReturn(requestBody); final User user = new User("username", "displayName", "email"); when(authenticator.authenticate(Credentials.fromJSON(requestBody), AuthConfig.fromJSONList(requestBody))).thenReturn(user); final GoPluginApiResponse response = new UserAuthenticationExecutor(goApiRequest, authenticator).execute(); assertThat(response.responseCode(), is(200)); final String expectedResponseBody = "{\n" + " \"roles\": [],\n" + " \"user\": {\n" + " \"username\": \"username\",\n" + " \"display_name\": \"displayName\",\n" + " \"email\": \"email\"\n" + " }\n" + "}"; JSONAssert.assertEquals(expectedResponseBody, response.responseBody(), true); }
@Test public void shouldReturnAEmptyResponseOnAuthenticationFailure() throws Exception { final GoPluginApiRequest goApiRequest = mock(GoPluginApiRequest.class); final String requestBody = requestJson("username", "password"); when(goApiRequest.requestBody()).thenReturn(requestBody); when(authenticator.authenticate(Credentials.fromJSON(requestBody), AuthConfig.fromJSONList(requestBody))).thenThrow(new AuthenticationException("failed")); final GoPluginApiResponse response = new UserAuthenticationExecutor(goApiRequest, authenticator).execute(); assertThat(response.responseCode(), is(200)); JSONAssert.assertEquals("{}", response.responseBody(), true); } |
VerifyConnectionRequestExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { List<Map<String, String>> errors = validateAuthConfig(); if (errors.size() != 0) { return validationFailureResponse(errors); } VerifyConnectionResult result = verifyConnection(); if (!result.isSuccessful()) { return verifyConnectionFailureResponse(result.getError()); } return successResponse(); } VerifyConnectionRequestExecutor(GoPluginApiRequest request); @Override GoPluginApiResponse execute(); } | @Test public void execute_shouldValidateTheConfiguration() throws Exception { DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, null); request.setRequestBody("{}"); GoPluginApiResponse response = new VerifyConnectionRequestExecutor(request).execute(); String expectedResponse = "{\"message\":\"Validation failed for the given Auth Config\",\"errors\":[{\"message\":\"PasswordFilePath must not be blank.\",\"key\":\"PasswordFilePath\"}],\"status\":\"validation-failed\"}"; assertThat(response.responseBody(), is(expectedResponse)); }
@Test public void execute_shouldVerifyIfThePasswordFileExists() throws Exception { DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, null); request.setRequestBody("{\"PasswordFilePath\": \"some_path\"}"); GoPluginApiResponse response = new VerifyConnectionRequestExecutor(request).execute(); String expectedResponse = "{\"message\":\"No password file at path `some_path`.\",\"status\":\"failure\"}"; assertThat(response.responseBody(), is(expectedResponse)); }
@Test public void execute_shouldVerifyIfPasswordFilePathPointsToANormalFile() throws Exception { File folder = this.folder.newFolder("subfolder"); DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, null); request.setRequestBody(String.format("{\"PasswordFilePath\": \"%s\"}", folder.getAbsolutePath())); GoPluginApiResponse response = new VerifyConnectionRequestExecutor(request).execute(); String expectedResponse = String.format("{\"message\":\"Password file path `%s` is not a normal file.\",\"status\":\"failure\"}", folder.getAbsolutePath()); assertThat(response.responseBody(), is(expectedResponse)); }
@Test public void execute_shouldReturnASuccessResponseIfValidationAndVerificationPasses() throws Exception { File passwordFile = this.folder.newFile("password.properties"); DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, null); request.setRequestBody(String.format("{\"PasswordFilePath\": \"%s\"}", passwordFile.getAbsolutePath())); GoPluginApiResponse response = new VerifyConnectionRequestExecutor(request).execute(); assertThat(response.responseBody(), is("{\"message\":\"Connection ok\",\"status\":\"success\"}")); } |
GetCapabilitiesExecutor { public GoPluginApiResponse execute() { Capabilities capabilities = getCapabilities(); return new DefaultGoPluginApiResponse(SUCCESS_RESPONSE_CODE, capabilities.toJSON()); } GoPluginApiResponse execute(); } | @Test public void shouldExposeItsCapabilities() throws Exception { GoPluginApiResponse response = new GetCapabilitiesExecutor().execute(); assertThat(response.responseCode(), CoreMatchers.is(200)); String expectedJSON = "{\n" + " \"supported_auth_type\":\"password\",\n" + " \"can_search\":true,\n" + " \"can_authorize\":false,\n" + " \"can_get_user_roles\":false\n" + "}"; JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); } |
GetAuthConfigViewExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("template", Util.readResource("/auth-config.template.html")); DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200, GSON.toJson(jsonObject)); return defaultGoPluginApiResponse; } @Override GoPluginApiResponse execute(); } | @Test public void shouldRenderTheTemplateInJSON() throws Exception { GoPluginApiResponse response = new GetAuthConfigViewExecutor().execute(); assertThat(response.responseCode(), is(200)); Map<String, String> hashSet = new Gson().fromJson(response.responseBody(), HashMap.class); assertThat(hashSet, Matchers.hasEntry("template", Util.readResource("/auth-config.template.html"))); } |
GetAuthConfigMetadataExecutor implements RequestExecutor { public GoPluginApiResponse execute() throws Exception { final List<ProfileMetadata> authConfigMetadata = MetadataHelper.getMetadata(Configuration.class); return new DefaultGoPluginApiResponse(200, GSON.toJson(authConfigMetadata)); } GoPluginApiResponse execute(); } | @Test public void shouldSerializeAllFields() throws Exception { GoPluginApiResponse response = new GetAuthConfigMetadataExecutor().execute(); List list = new Gson().fromJson(response.responseBody(), List.class); assertEquals(list.size(), MetadataHelper.getMetadata(Configuration.class).size()); }
@Test public void assertJsonStructure() throws Exception { GoPluginApiResponse response = new GetAuthConfigMetadataExecutor().execute(); assertThat(response.responseCode(), is(200)); String expectedJSON = "[\n" + " {\n" + " \"key\": \"PasswordFilePath\",\n" + " \"metadata\": {\n" + " \"required\": true,\n" + " \"secure\": false\n" + " }\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, response.responseBody(), true); } |
AuthConfigValidateRequestExecutor implements RequestExecutor { public GoPluginApiResponse execute() throws Exception { Map<String, String> configuration = GSON.fromJson(request.requestBody(), Map.class); final List<Map<String, String>> validationResult = Configuration.validate(configuration); return DefaultGoPluginApiResponse.success(GSON.toJson(validationResult)); } AuthConfigValidateRequestExecutor(GoPluginApiRequest request); GoPluginApiResponse execute(); } | @Test public void shouldBarfWhenUnknownKeysArePassed() throws Exception { when(request.requestBody()).thenReturn(new Gson().toJson(Collections.singletonMap("foo", "bar"))); GoPluginApiResponse response = new AuthConfigValidateRequestExecutor(request).execute(); String json = response.responseBody(); String expectedJSON = "[\n" + " {\n" + " \"message\": \"PasswordFilePath must not be blank.\",\n" + " \"key\": \"PasswordFilePath\"\n" + " },\n" + " {\n" + " \"key\": \"foo\",\n" + " \"message\": \"Is an unknown property\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE); }
@Test public void shouldValidateMandatoryKeys() throws Exception { when(request.requestBody()).thenReturn(new Gson().toJson(Collections.emptyMap())); GoPluginApiResponse response = new AuthConfigValidateRequestExecutor(request).execute(); String json = response.responseBody(); String expectedJSON = "[\n" + " {\n" + " \"message\": \"PasswordFilePath must not be blank.\",\n" + " \"key\": \"PasswordFilePath\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedJSON, json, JSONCompareMode.NON_EXTENSIBLE); } |
CliArguments { public String password() { if (isBlank(password)) { password = passwordReader.readPassword(); } return password; } CliArguments(); CliArguments(PasswordReader passwordReader); Algorithm algorithm(); String username(); String password(); int cost(); int iterations(); int keyLength(); String salt(); void validate(); static CliArguments fromArgs(String... args); boolean help(); } | @Test public void shouldPromptForPasswordIfNotProvidedAsArgument() throws Exception { final PasswordReader passwordReader = mock(PasswordReader.class); when(passwordReader.readPassword()).thenReturn("password-from-cli"); final CliArguments arguments = new CliArguments(passwordReader); final String password = arguments.password(); assertThat(password, is("password-from-cli")); } |
SearchUserExecutor implements RequestExecutor { @Override public GoPluginApiResponse execute() throws Exception { Map<String, String> requestParam = Util.GSON.fromJson(request.requestBody(), Map.class); String searchTerm = requestParam.get(SEARCH_TERM); List<AuthConfig> authConfigs = AuthConfig.fromJSONList(request.requestBody()); final Set<User> users = searchUsers(searchTerm, authConfigs); return new DefaultGoPluginApiResponse(200, Util.GSON.toJson(users)); } SearchUserExecutor(GoPluginApiRequest request); protected SearchUserExecutor(GoPluginApiRequest request, PasswordFileReader passwordFileReader); @Override GoPluginApiResponse execute(); Set<User> search(String searchText, AuthConfig authConfig); static final String SEARCH_TERM; } | @Test public void shouldListUsersMatchingTheSearchTerm() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); final Properties properties = new Properties(); properties.put("username", "invalid-password"); when(fileReader.read("/var/etc/password.properties")).thenReturn(properties); when(request.requestBody()).thenReturn(requestJson("name")); final GoPluginApiResponse response = new SearchUserExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(200)); JSONAssert.assertEquals("[{\"username\":\"username\"}]", response.responseBody(), true); }
@Test public void shouldListUniqueUsersMatchingTheSearchTermAcrossMultiplePasswordFiles() throws Exception { final GoPluginApiRequest request = mock(GoPluginApiRequest.class); mockPasswordFileWith("/var/etc/password_1.properties", "myname"); mockPasswordFileWith("/var/etc/password_2.properties", "yournamed", "bar", "myname"); mockPasswordFileWith("/var/etc/password_3.properties", "nameless", "foo"); when(request.requestBody()).thenReturn(requestJsonWithMultipleAuthConfig("name")); final GoPluginApiResponse response = new SearchUserExecutor(request, fileReader).execute(); assertThat(response.responseCode(), is(200)); final String expectedResponseBody = "[\n" + " {\n" + " \"username\": \"myname\"\n" + " },\n" + " {\n" + " \"username\": \"yournamed\"\n" + " },\n" + " {\n" + " \"username\": \"nameless\"\n" + " }\n" + "]"; JSONAssert.assertEquals(expectedResponseBody, response.responseBody(), true); } |
PasswordFileReader { public Properties read(String passwordFilePath) throws IOException { final Properties properties = new Properties(); try (Reader inputStream = new InputStreamReader(new FileInputStream(passwordFilePath), UTF_8)) { properties.load(inputStream); } return properties; } Properties read(String passwordFilePath); } | @Test public void shouldReadPasswordFile() throws Exception { PasswordFileReader reader = new PasswordFileReader(); Properties properties = reader.read(PasswordFileReaderTest.class.getResource("/password.properties").getFile()); assertThat(properties.getProperty("username"), is("{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=")); } |
AlgorithmIdentifier { public Algorithm identify(String hash) { if (hash.startsWith("{SHA1}") || !hash.startsWith("$")) { return Algorithm.SHA1; } else { final Matcher matcher = PREFIX_PATTERN.matcher(hash); if (matcher.find()) { String algorithmPrefix = matcher.group(1); return Arrays.stream(Algorithm.values()) .filter(elem -> { List<String> strings = ALGORITHM_IDENTIFIER_PREFIXS.get(elem); return strings != null && strings.stream().anyMatch(algorithmPrefix::equalsIgnoreCase); }) .findFirst() .orElseThrow(() -> new NoSuchAlgorithmException("Failed to determine hashing algorithm.")); } throw new NoSuchAlgorithmException("Failed to determine hashing algorithm."); } } Algorithm identify(String hash); } | @Test public void shouldIdentifySHA1Password() throws Exception { assertThat(algorithmIdentifier.identify("{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g="), is(Algorithm.SHA1)); assertThat(algorithmIdentifier.identify("W6ph5Mm5Pz8GgiULbPgzG37mj9g="), is(Algorithm.SHA1)); }
@Test public void shouldIdentifyBCryptAlgorithmFromPrefix() throws Exception { assertThat(algorithmIdentifier.identify("$2a$...$..."), is(Algorithm.BCRYPT)); assertThat(algorithmIdentifier.identify("$2A$...$..."), is(Algorithm.BCRYPT)); assertThat(algorithmIdentifier.identify("$2b$...$..."), is(Algorithm.BCRYPT)); assertThat(algorithmIdentifier.identify("$2B$...$..."), is(Algorithm.BCRYPT)); assertThat(algorithmIdentifier.identify("$2Y$...$..."), is(Algorithm.BCRYPT)); assertThat(algorithmIdentifier.identify("$2y$...$..."), is(Algorithm.BCRYPT)); }
@Test public void shouldIdentifyPBKDF2WithHmacSHA1FromPrefix() throws Exception { assertThat(algorithmIdentifier.identify("$PBKDF2WithHmacSHA1$...$..."), is(Algorithm.PBKDF2WithHmacSHA1)); assertThat(algorithmIdentifier.identify("$pbkdf2withhmacsha1$...$..."), is(Algorithm.PBKDF2WithHmacSHA1)); }
@Test public void shouldIdentifyPBKDF2WithHmacSHA256FromPrefix() throws Exception { assertThat(algorithmIdentifier.identify("$PBKDF2WithHmacSHA256$...$..."), is(Algorithm.PBKDF2WithHmacSHA256)); assertThat(algorithmIdentifier.identify("$pbkdf2withhmacsha256$...$..."), is(Algorithm.PBKDF2WithHmacSHA256)); }
@Test(expected = NoSuchAlgorithmException.class) public void shouldErrorOutIfItFailedToDetectAlgorithm() throws Exception { algorithmIdentifier.identify("$foo"); } |
SHA1Matcher implements HashMatcher { @Override public boolean matches(String plainText, String hashed) { final String digest = sha1Digest(plainText.getBytes()); return hashed.equals(digest) || hashed.equals("{SHA}" + digest); } @Override boolean matches(String plainText, String hashed); } | @Test public void shouldReturnTrueForValidPassword() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("badger", "ThmbShxAtJepX80c2JY1FzOEmUk="); assertTrue(matching); }
@Test public void shouldReturnFalseForInvalidPassword() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("random", "ThmbShxAtJepX80c2JY1FzOEmUk="); assertFalse(matching); }
@Test public void shouldValidateHashWithSHAPrefix() throws Exception { HashMatcher sha1 = new SHA1Matcher(); final boolean matching = sha1.matches("badger", "{SHA}ThmbShxAtJepX80c2JY1FzOEmUk="); assertTrue(matching); } |
PBKDF2Provider implements HashProvider { @Override public String hash(CliArguments cliArguments) { try { PBEKeySpec keySpec = new PBEKeySpec(cliArguments.password().toCharArray(), cliArguments.salt().getBytes(), cliArguments.iterations(), cliArguments.keyLength()); SecretKeyFactory factory = SecretKeyFactory.getInstance(cliArguments.algorithm().getName()); final String hashedPasswd = DatatypeConverter.printHexBinary(factory.generateSecret(keySpec).getEncoded()); return format("%s=$%s$%s$%s$%s$%s", cliArguments.username(), cliArguments.algorithm().getName(), cliArguments.iterations(), cliArguments.keyLength(), cliArguments.salt(), hashedPasswd); } catch (Exception e) { throw new RuntimeException(e); } } @Override String hash(CliArguments cliArguments); } | @Test public void shouldGeneratePasswordFileEntryUsingPBKDF2WithHmacSHA1() throws Exception { when(cliArguments.algorithm()).thenReturn(Algorithm.PBKDF2WithHmacSHA1); when(cliArguments.iterations()).thenReturn(1000); when(cliArguments.keyLength()).thenReturn(256); when(cliArguments.salt()).thenReturn("812A9B665D09904B8239778EC8D18CF7"); final String hash = provider.hash(cliArguments); assertThat(hash, is("admin=$PBKDF2WithHmacSHA1$1000$256$812A9B665D09904B8239778EC8D18CF7$093763FF7F9A2E279940FFB89B341A4DDE5780E7046F248BA36FF9A9F5A5E79E")); }
@Test public void shouldGeneratePasswordFileEntryUsingPBKDF2WithHmacSHA256() throws Exception { when(cliArguments.algorithm()).thenReturn(Algorithm.PBKDF2WithHmacSHA256); when(cliArguments.iterations()).thenReturn(2000); when(cliArguments.keyLength()).thenReturn(512); when(cliArguments.salt()).thenReturn("812A9B665D09904B8239778EC8D18CF7"); final String hash = provider.hash(cliArguments); assertThat(hash, is("admin=$PBKDF2WithHmacSHA256$2000$512$812A9B665D09904B8239778EC8D18CF7$CE4952378009E7706F3E5B8DF33DEE6CCC53448460CB093353DF04800A22BD412F5F2F76BDBD1EACE832534B1BEC5F96FC115261967F67864D187D5860DB0470")); } |
PBKDF2Matcher implements HashMatcher { @Override public boolean matches(String plainText, String hashed) { PBKDF2HashInfo hashInfo = new PBKDF2HashInfo(hashed); String generatedHash = generateHash(plainText, hashInfo); return generatedHash.equalsIgnoreCase(hashInfo.getHashedPassword()); } @Override boolean matches(String plainText, String hashed); } | @Test public void shouldValidatePBKDF2WithHmacSHA256Hash() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA256") .append("$1000") .append("$256") .append("$8C6A56243A51EEDA40A9DD0ECCD1B55E") .append("$48FE9A232A70EE8E108BF07DCE80C966CF57BE35F8685469E2798F6820552284").toString(); final boolean matches = pbkdf2Matcher.matches("password", hashed); assertTrue(matches); }
@Test public void shouldValidatePBKDF2WithHmacSHA1Hash() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA1") .append("$1000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$FA487EEB17946558C49055E4ECB3FAA02A3C847738DF67231E5D1A5F33FBA7FC").toString(); final boolean matches = pbkdf2Matcher.matches("badger", hashed); assertTrue(matches); }
@Test public void shouldReturnFalseIfComputedHashIsDifferent() throws Exception { final String hashed = new StringBuilder() .append("$PBKDF2WithHmacSHA1") .append("$1000") .append("$256") .append("$85A1CCB7C4F4C535CBABDDBD01FECB7B") .append("$FF8DE0A276CDBC3E01A87E804B910753D214FAB1D9DB8334F801A29EC5D7A179").toString(); final boolean matches = pbkdf2Matcher.matches("badger", hashed); assertFalse(matches); } |
BCryptMatcher implements HashMatcher { @Override public boolean matches(String plainText, String hashed) { final String processedHash = hashed.replaceFirst("^\\$2y\\$", "\\$2a\\$").replaceFirst("^\\$2b\\$", "\\$2a\\$"); return BCrypt.checkpw(plainText, processedHash); } @Override boolean matches(String plainText, String hashed); } | @Test public void shouldReturnTrueForValidPassword() throws Exception { final boolean matches = bcryptMatcher.matches("bob", "$2y$05$6x2HXaQcqi7osijESYtUTeJBx5rYpIYQJlP51rFZCRpuE3hBH/LAq"); assertTrue(matches); }
@Test public void shouldReturnFalseForInvalidPassword() throws Exception { final boolean matches = bcryptMatcher.matches("bob", "$2y$05$6x2HXaQcqi7osijESYtUTeJBx5rYpIYQJlP51rFZCRpuE3hBH/dad"); assertFalse(matches); } |
BCryptProvider implements HashProvider { @Override public String hash(CliArguments arguments) { final String salt = BCrypt.gensalt(arguments.cost()); final String hashedPasswd = BCrypt.hashpw(arguments.password(), salt); return format("{0}={1}", arguments.username(), hashedPasswd); } @Override String hash(CliArguments arguments); } | @Test public void shouldGeneratePasswordFileEntryUsingBCrypt() throws Exception { when(cliArguments.algorithm()).thenReturn(Algorithm.BCRYPT); when(cliArguments.cost()).thenReturn(6); final String hash = provider.hash(cliArguments); assertThat(hash,startsWith("admin=$2a$06$")); } |
GraphicsBounds { public static Rectangle createBounds() { return new BufferedImage(800, 600, BufferedImage.TYPE_3BYTE_BGR) .createGraphics() .getDeviceConfiguration() .getBounds(); } static void main(String[] args); static Rectangle createBounds(); } | @Test void createBounds() throws Exception { assertThat(GraphicsBounds.createBounds()) .isEqualTo(new Rectangle(0, 0, 800, 600)); } |
HeaderExtractor implements IExtractor { @Override public String extractValue(IHttpRequest request) { return StringUtils.defaultIfEmpty(request.getHeaderField(key), null); } HeaderExtractor(String key); @Override String extractValue(IHttpRequest request); } | @Test public void testHeaderExtraction() { IHttpRequest request = mock(IHttpRequest.class); when(request.getHeaderField(eq("testField"))).thenReturn("test"); HeaderExtractor extractor = new HeaderExtractor("testField"); assertEquals("test", extractor.extractValue(request)); when(request.getHeaderField(eq("testField"))).thenReturn(null); assertEquals(null, extractor.extractValue(request)); when(request.getHeaderField(eq("testField"))).thenReturn(""); assertEquals(null, extractor.extractValue(request)); } |
FormExtractor implements IExtractor { @Override public String extractValue(IHttpRequest request) { return StringUtils.defaultIfEmpty(request.getFormParameterValue(key), null); } FormExtractor(String key); @Override String extractValue(IHttpRequest request); } | @Test public void testFormExtraction() { IHttpRequest request = mock(IHttpRequest.class); when(request.getFormParameterValue(eq("testField"))).thenReturn("test"); FormExtractor extractor = new FormExtractor("testField"); assertEquals("test", extractor.extractValue(request)); when(request.getFormParameterValue(eq("testField"))).thenReturn(null); assertEquals(null, extractor.extractValue(request)); when(request.getFormParameterValue(eq("testField"))).thenReturn(""); assertEquals(null, extractor.extractValue(request)); } |
ScopeParser { public Set<String> parseScope(String scope) { if (scope == null) { return null; } Scanner scanner = new Scanner(StringUtils.trim(scope)); try { scanner.useDelimiter(" "); Set<String> result = new HashSet<>(); while (scanner.hasNext(SCOPE_PATTERN)) { String scopeToken = scanner.next(SCOPE_PATTERN); result.add(scopeToken); } return result; } finally { scanner.close(); } } String render(Set<String> scopes); Set<String> parseScope(String scope); } | @Test public void testParsing() { assertEquals(null, parser.parseScope(null)); assertTrue(parser.parseScope("").isEmpty()); assertTrue(parser.parseScope("scope").contains("scope")); assertTrue(parser.parseScope("sco/pe").contains("sco/pe")); assertTrue(parser.parseScope("scope scope1").contains("scope1")); assertTrue(parser.parseScope("scope scope1 ").contains("scope1")); assertTrue(parser.parseScope(" scope scope1").contains("scope1")); assertTrue(parser.parseScope(" scope Scope1").contains("Scope1")); assertTrue(parser.parseScope(" scope Scope1!").contains("Scope1!")); parser.parseScope(" scope sc/ope1"); } |
ScopeParser { public String render(Set<String> scopes) { if (scopes == null) { return null; } StringBuffer buffer = new StringBuffer(); for (String scope : scopes) { if (buffer.length()>0) { buffer.append(" "); } buffer.append(scope); } return buffer.toString(); } String render(Set<String> scopes); Set<String> parseScope(String scope); } | @Test public void testRender() { Set<String> scopes = new HashSet<>(Arrays.asList("aa","bb","cc")); assertNull(parser.render(null)); assertEquals("aa bb cc", parser.render(scopes)); assertEquals(scopes, parser.parseScope(parser.render(scopes))); scopes = new HashSet<>(Arrays.asList("aa")); assertEquals("aa", parser.render(scopes)); scopes = new HashSet<>(); assertEquals("", parser.render(scopes)); } |
UrlBuilder { protected Map<String, String> parseQueryParameters(String query) { if (query == null) { return null; } Scanner scanner = new Scanner(query); try { scanner.useDelimiter("[&=]"); Map<String, String> result = new LinkedHashMap<>(); while (scanner.hasNext(".+")) { String key = scanner.next("[^=]+"); String value = null; if (scanner.hasNext("[^&]+")) { value = scanner.next("[^&]+"); } result.put(key, value); } return result; } finally { scanner.close(); } } URI addQueryParameters(Map<String, Object> parameters, URI baseUrl); String addQueryParameters(String queryParams, Map<String, Object> newParameters); URI setFragment(URI baseUri, String newFragment); } | @Test public void testParsing() { Map<String, String> params; params = urlBuilder.parseQueryParameters("a=b&c=d"); assertEquals("b", params.get("a")); assertEquals("d", params.get("c")); params = urlBuilder.parseQueryParameters("a=b&c="); assertEquals("b", params.get("a")); assertEquals(null, params.get("c")); } |
UrlBuilder { protected String render(Map<String, String> params) throws UnsupportedEncodingException { StringBuffer buffer = new StringBuffer(); for (Map.Entry<String, String> entry : params.entrySet()) { if (buffer.length()>0) { buffer.append("&"); } buffer.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name())); buffer.append("="); if (entry.getValue()!=null) { buffer.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name())); } } return buffer.toString(); } URI addQueryParameters(Map<String, Object> parameters, URI baseUrl); String addQueryParameters(String queryParams, Map<String, Object> newParameters); URI setFragment(URI baseUri, String newFragment); } | @Test public void testRender() throws UrlBuilderException, URISyntaxException { URI baseUri = new URI("http: Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put("cd","gh"); parameters.put("numtest",1); URI result = urlBuilder.addQueryParameters(parameters, baseUri); assertEquals("http: parameters.put("abc","g"); result = urlBuilder.addQueryParameters(parameters, baseUri); assertEquals("http: } |
FormParser { public Form parseForm(InputStream inputStream) throws FormParserException { Form result = new Form(); Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()); scanner.useDelimiter(Pattern.compile("[&=]")); try { while (scanner.hasNext(FIELD_PATTERN)) { String name = urlDecode(scanner.next(FIELD_PATTERN)); String value = urlDecode(scanner.next(FIELD_PATTERN)); result.param(name, value); } } catch (NoSuchElementException | UnsupportedEncodingException e) { throw new FormParserException(e); } finally { scanner.close(); } return result; } Form parseForm(InputStream inputStream); } | @Test public void testParse() throws FormParserException { Form f = parser.parseForm(toInputStream("a=b&c=d")); assertTrue(f.asMap().containsKey("a")); assertTrue(f.asMap().containsKey("c")); assertEquals("b", f.asMap().getFirst("a")); assertEquals("d", f.asMap().getFirst("c")); f = parser.parseForm(toInputStream("a=b")); try { f = parser.parseForm(toInputStream("a=")); fail(); } catch (Exception e) { } try { f = parser.parseForm(toInputStream("a=b&c")); fail(); } catch (Exception e) { } } |
ForcedRulesProgram implements Program { @Override public RelNode run(RelOptPlanner relOptPlanner, RelNode relNode, RelTraitSet relTraitSet, List<RelOptMaterialization> relOptMaterializationList, List<RelOptLattice> list1) { logger.debug("Running forced rules on:\n" + RelOptUtil.toString(relNode)); return replace(relNode, rules, relBuilderFactoryFactory.create(relOptPlanner.getContext())); } ForcedRulesProgram(JdbcRelBuilderFactoryFactory relBuilderFactoryFactory, ForcedRule... rules); @Override RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> list1); } | @Test public void testEmptyProgram_doesNothing() { program = new ForcedRulesProgram(superFactory); Mockito.doReturn(ImmutableList.of()).when(inNode).getInputs(); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(inNode, result); Mockito.verify(inNode, Mockito.never()).replaceInput(Mockito.anyInt(), Mockito.any()); }
@Test public void testRun_sendsRelBuilderFactory() { program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Mockito.verify(rule).apply(Mockito.any(), Mockito.same(miniFactory)); }
@Test public void testRun_recursesOverTree() { RelNode node2a = Mockito.mock(RelNode.class); RelNode node2b = Mockito.mock(RelNode.class); RelNode node3aa = Mockito.mock(RelNode.class); Mockito.doReturn(ImmutableList.of(node2a, node2b)).when(inNode).getInputs(); Mockito.doReturn(ImmutableList.of(node3aa)).when(node2a).getInputs(); Mockito.doReturn(ImmutableList.of()).when(node2b).getInputs(); Mockito.doReturn(ImmutableList.of()).when(node3aa).getInputs(); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(inNode, result); Mockito.verify(rule).apply(Mockito.same(inNode), Mockito.any()); Mockito.verify(rule).apply(Mockito.same(node2a), Mockito.any()); Mockito.verify(rule).apply(Mockito.same(node2b), Mockito.any()); Mockito.verify(rule).apply(Mockito.same(node3aa), Mockito.any()); }
@Test public void testRun_returnsReplacementNodes() { RelNode outNode = Mockito.mock(RelNode.class); Mockito.doReturn(outNode).when(rule).apply(Mockito.same(inNode), Mockito.any()); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(outNode, result); }
@Test public void testRun_scansWithinReplacements() { RelNode outNode = Mockito.mock(RelNode.class); Mockito.doReturn(outNode).when(rule).apply(Mockito.same(inNode), Mockito.any()); program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Mockito.verify(outNode).getInputs(); }
@Test public void testRun_replacesChildren() { RelNode node2a = Mockito.mock(RelNode.class); RelNode node2b = Mockito.mock(RelNode.class); RelNode outNode = Mockito.mock(RelNode.class); Mockito.doReturn(ImmutableList.of(node2a, node2b)).when(inNode).getInputs(); Mockito.doReturn(outNode).when(rule).apply(Mockito.same(node2b), Mockito.any()); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(inNode, result); Mockito.verify(inNode).replaceInput(Mockito.eq(1), Mockito.same(outNode)); }
@Test public void testRun_onlyAppliesOneRulePerNode() { ForcedRule rule2 = Mockito.mock(ForcedRule.class); RelNode outNode = Mockito.mock(RelNode.class); Mockito.doReturn(outNode).when(rule).apply(Mockito.same(inNode), Mockito.any()); program = new ForcedRulesProgram(superFactory, rule, rule2); program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Mockito.verify(rule).apply(Mockito.same(inNode), Mockito.any()); Mockito.verify(rule2, Mockito.never()).apply(Mockito.any(), Mockito.any()); } |
SequenceProgram implements Program { @Override public RelNode run(RelOptPlanner relOptPlanner, RelNode relNode, RelTraitSet relTraitSet, List<RelOptMaterialization> relOptMaterializationList, List<RelOptLattice> relOptLatticeList) { for (Program program : programs) { relNode = program.run(relOptPlanner, relNode, relTraitSet, relOptMaterializationList, relOptLatticeList); logger.debug("After running " + program + ":\n" + RelOptUtil.toString(relNode)); } return relNode; } SequenceProgram(Program... programs); @SuppressWarnings("Guava") // Must conform to Calcite's API static Function<Holder<Program>, Void> prepend(Program program); ImmutableList<Program> getPrograms(); @Override RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> relOptLatticeList); } | @Test public void testRun_chainsSubPrograms() { Program subProgram2 = Mockito.mock(Program.class); RelNode node2 = Mockito.mock(RelNode.class); RelNode node3 = Mockito.mock(RelNode.class); program = new SequenceProgram(subProgram, subProgram2); Mockito.doReturn(node2).when(subProgram).run(Mockito.any(), Mockito.same(inNode), Mockito.any(), Mockito.anyList(), Mockito.anyList()); Mockito.doReturn(node3).when(subProgram2).run(Mockito.any(), Mockito.same(node2), Mockito.any(), Mockito.anyList(), Mockito.anyList()); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(node3, result); }
@Test public void testEmptyProgram_doesNothing() { program = new SequenceProgram(); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(inNode, result); }
@Test public void testRun_propagatesToSubProgram() { RelNode node2 = Mockito.mock(RelNode.class); Mockito.doReturn(node2).when(subProgram).run(Mockito.any(), Mockito.same(inNode), Mockito.any(), Mockito.anyList(), Mockito.anyList()); RelNode result = program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Assert.assertSame(node2, result); }
@Test public void testRun_propagatesAllParameters() { RelNode node2 = Mockito.mock(RelNode.class); Mockito.doReturn(node2).when(subProgram).run(Mockito.any(), Mockito.same(inNode), Mockito.any(), Mockito.anyList(), Mockito.anyList()); program.run(planner, inNode, relTraitSet, relOptMaterializationList, relOptLatticeList); Mockito.verify(subProgram).run( Mockito.same(planner), Mockito.any(), Mockito.same(relTraitSet), Mockito.anyList(), Mockito.anyList() ); } |
SequenceProgram implements Program { @SuppressWarnings("Guava") public static Function<Holder<Program>, Void> prepend(Program program) { return (holder) -> { if (holder == null) { throw new IllegalStateException("No program holder"); } Program chain = holder.get(); if (chain == null) { chain = Programs.standard(); } holder.set(new SequenceProgram(program, chain)); return null; }; } SequenceProgram(Program... programs); @SuppressWarnings("Guava") // Must conform to Calcite's API static Function<Holder<Program>, Void> prepend(Program program); ImmutableList<Program> getPrograms(); @Override RelNode run(RelOptPlanner relOptPlanner,
RelNode relNode,
RelTraitSet relTraitSet,
List<RelOptMaterialization> relOptMaterializationList,
List<RelOptLattice> relOptLatticeList); } | @Test(expected = RuntimeException.class) public void testPrepend_throwsIfNoHolderIsGiven() { SequenceProgram.prepend(subProgram).apply(null); } |
JournalledJdbcTable extends JdbcTable { @Override public RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable) { JdbcRelBuilder relBuilder = relBuilderFactory.create( context.getCluster(), relOptTable.getRelOptSchema() ); relBuilder.scanJdbc( getJournalTable(), JdbcTableUtils.getQualifiedName(relOptTable, getJournalTable()) ); RexInputRef versionField = relBuilder.field(getVersionField()); RexInputRef subsequentVersionField = relBuilder.field(getSubsequentVersionField()); RexInputRef maxVersionField = relBuilder.appendField(relBuilder.makeOver( SqlStdOperatorTable.MAX, ImmutableList.of(versionField), relBuilder.fields(getKeyColumnNames()) )); relBuilder.filter( relBuilder.equals(versionField, maxVersionField), relBuilder.isNull(subsequentVersionField) ); return relBuilder.build(); } JournalledJdbcTable(
String tableName,
JournalledJdbcSchema journalledJdbcSchema,
JdbcTable journalTable,
String[] keyColumnNames
); @Override RelNode toRel(RelOptTable.ToRelContext context, RelOptTable relOptTable); } | @Test public void testToRel_changesTableToJournal() { table.toRel(context, relOptTable); Mockito.verify(relBuilder).scanJdbc(Mockito.same(journalTable), Mockito.any()); } |
JournalledJdbcSchema extends JdbcSchema { public static JournalledJdbcSchema create( SchemaPlus parentSchema, String name, Map<String, Object> operand ) { DataSource dataSource; try { dataSource = parseDataSource(operand); } catch (Exception e) { throw new IllegalArgumentException("Error while reading dataSource", e); } String catalog = (String) operand.get("jdbcCatalog"); String schema = (String) operand.get("jdbcSchema"); Expression expression = null; if (parentSchema != null) { expression = Schemas.subSchemaExpression(parentSchema, name, JdbcSchema.class); } final SqlDialect dialect = createDialect(dataSource); final JdbcConvention convention = JdbcConvention.of(dialect, expression, name); return new JournalledJdbcSchema(dataSource, dialect, convention, catalog, schema, operand); } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testFactoryWillAutomaticallyAddRules() { JournalledJdbcSchema.Factory.INSTANCE.setAutomaticallyAddRules(true); JournalledJdbcSchema.Factory.INSTANCE.create(null, "my-parent", options); try { Program def = Mockito.mock(Program.class); Holder<Program> holder = Holder.of(def); Hook.PROGRAM.run(holder); Assert.assertTrue(holder.get() instanceof SequenceProgram); Assert.assertTrue(((SequenceProgram) holder.get()).getPrograms().get(0) instanceof ForcedRulesProgram); } finally { JournalledJdbcSchema.Factory.INSTANCE.setAutomaticallyAddRules(false); JournalledJdbcRuleManager.removeHook(); } } |
JournalledJdbcSchema extends JdbcSchema { String getVersionField() { return versionField; } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testDefaultVersionField() { options.remove("journalVersionField"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionField(), "version_number"); } |
JournalledJdbcSchema extends JdbcSchema { String getSubsequentVersionField() { return subsequentVersionField; } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testDefaultSubsequentVersionField() { options.remove("journalSubsequentVersionField"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getSubsequentVersionField(), "subsequent_version_number"); } |
JournalledJdbcSchema extends JdbcSchema { String journalNameFor(String virtualName) { return virtualName + journalSuffix; } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testDefaultJournalSuffix() { options.remove("journalSuffix"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.journalNameFor("foo"), "foo_journal"); } |
JournalledJdbcSchema extends JdbcSchema { private static JournalVersionType getVersionType(String name) { for (JournalVersionType v : JournalVersionType.values()) { if (v.name().equalsIgnoreCase(name)) { return v; } } throw new IllegalArgumentException("Unknown version type: " + name); } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testDefaultsToTimestampVersioning() { JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.TIMESTAMP); }
@Test public void testVersionTypeCanBeChanged() { options.put("journalVersionType", "BIGINT"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.BIGINT); }
@Test public void testVersionTypeIsCaseInsensitive() { options.put("journalVersionType", "bigint"); JournalledJdbcSchema schema = makeSchema(); Assert.assertEquals(schema.getVersionType(), JournalVersionType.BIGINT); } |
JournalledJdbcSchema extends JdbcSchema { @Override public Set<String> getTableNames() { return getTableMap(true).keySet(); } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testGetTableNamesReturnsVirtualTables() { JournalledJdbcSchema schema = makeSchema(); Set<String> names = schema.getTableNames(); Assert.assertTrue(names.contains("MY_TABLE")); Assert.assertTrue(names.contains("OTHER_TABLE")); } |
JournalledJdbcSchema extends JdbcSchema { @Override public Table getTable(String name) { return getTableMap(false).get(name); } private JournalledJdbcSchema(
DataSource dataSource,
SqlDialect dialect,
JdbcConvention convention,
String catalog,
String schema,
Map<String, Object> operand
); static JournalledJdbcSchema create(
SchemaPlus parentSchema,
String name,
Map<String, Object> operand
); @Override Table getTable(String name); @Override Set<String> getTableNames(); } | @Test public void testGetTablePassesThroughNonMatchingTables() { JournalledJdbcSchema schema = makeSchema(); Table table = schema.getTable("OTHER_TABLE"); Assert.assertNotNull(table); Assert.assertFalse(table instanceof JournalledJdbcTable); }
@Test public void testGetTableSurvivesNulls() { JournalledJdbcSchema schema = makeSchema(); Table table = schema.getTable("NOT_HERE"); Assert.assertNull(table); }
@Test public void testListsOfKeysAreLoaded() { JournalledJdbcSchema schema = makeSchema(); JournalledJdbcTable journalTable = (JournalledJdbcTable) schema.getTable("MY_TABLE"); Assert.assertEquals(journalTable.getKeyColumnNames(), ImmutableList.of("myKey1", "myKey2")); }
@Test public void testSingleStringKeysAreLoaded() { options.put("journalTables", ImmutableMap.of("MY_TABLE", "foo")); JournalledJdbcSchema schema = makeSchema(); JournalledJdbcTable journalTable = (JournalledJdbcTable) schema.getTable("MY_TABLE"); Assert.assertEquals(journalTable.getKeyColumnNames(), ImmutableList.of("foo")); }
@Test public void testDefaultKeysAreLoadedIfNoSpecificKeysGiven() { options.put("journalTables", Collections.singletonMap("MY_TABLE", null)); JournalledJdbcSchema schema = makeSchema(); JournalledJdbcTable journalTable = (JournalledJdbcTable) schema.getTable("MY_TABLE"); Assert.assertEquals(journalTable.getKeyColumnNames(), ImmutableList.of("def1", "def2")); }
@Test public void testListsOfTablesAreGivenDefaultKeys() { options.put("journalTables", ImmutableList.of("MY_TABLE")); JournalledJdbcSchema schema = makeSchema(); JournalledJdbcTable journalTable = (JournalledJdbcTable) schema.getTable("MY_TABLE"); Assert.assertEquals(journalTable.getKeyColumnNames(), ImmutableList.of("def1", "def2")); } |
BankAccountService { public static Result moveData(BankAccount to, BankAccount from, Money money) { BigDecimal totalAmount = BigDecimal.ZERO; for(BankAccountEvent event : to.getEvents()) { totalAmount = totalAmount.add(event.getMoney().getAmount()); } if (totalAmount.compareTo(money.getAmount()) < 0) { throw new IllegalArgumentException("total money is less than zero!"); } BankAccountEvent decrementEvent = new BankAccountEvent(); decrementEvent.setId(IdGenerator.generateId()); decrementEvent.setFromBankAccountId(from.getId()); decrementEvent.setToBankAccountId(to.getId()); Money negated = new Money(); negated.setCurrency(money.getCurrency()); negated.setAmount(money.getAmount().negate()); decrementEvent.setMoney(negated); decrementEvent.setOccurredAt(ZonedDateTime.now()); BankAccount newFrom = new BankAccount(); List<BankAccountEvent> newFromEvent = Lists.newArrayList(from.getEvents()); newFromEvent.add(decrementEvent); newFrom.setId(from.getId()); newFrom.setEvents(newFromEvent); BankAccountEvent incrementEvent = new BankAccountEvent(); incrementEvent.setId(IdGenerator.generateId()); incrementEvent.setFromBankAccountId(from.getId()); incrementEvent.setToBankAccountId(to.getId()); incrementEvent.setMoney(money); incrementEvent.setOccurredAt(ZonedDateTime.now()); BankAccount newTo = new BankAccount(); List<BankAccountEvent> newToEvent = Lists.newArrayList(to.getEvents()); newToEvent.add(incrementEvent); newTo.setId(to.getId()); newTo.setEvents(newToEvent); Result result = new Result(); result.setFrom(newFrom); result.setTo(newTo); return result; } static Result moveData(BankAccount to, BankAccount from, Money money); } | @Test public void transferTest1() throws Exception { Money baseMoney = new Money(); baseMoney.setCurrency(Currency.getInstance("JPY")); baseMoney.setAmount(BigDecimal.valueOf(10000)); BankAccount bankAccount1 = new BankAccount(); bankAccount1.setId(IdGenerator.generateId()); List<BankAccountEvent> events1 = Lists.newArrayList(); BankAccountEvent incrementEvent1 = new BankAccountEvent(); incrementEvent1.setId(IdGenerator.generateId()); incrementEvent1.setToBankAccountId(bankAccount1.getId()); incrementEvent1.setFromBankAccountId(null); incrementEvent1.setMoney(baseMoney); incrementEvent1.setOccurredAt(ZonedDateTime.now()); events1.add(incrementEvent1); bankAccount1.setEvents(events1); BankAccount bankAccount2 = new BankAccount(); bankAccount2.setId(IdGenerator.generateId()); List<BankAccountEvent> events2 = Lists.newArrayList(); BankAccountEvent incrementEvent2 = new BankAccountEvent(); incrementEvent2.setId(IdGenerator.generateId()); incrementEvent2.setToBankAccountId(bankAccount1.getId()); incrementEvent2.setFromBankAccountId(null); incrementEvent2.setMoney(baseMoney); incrementEvent2.setOccurredAt(ZonedDateTime.now()); events2.add(incrementEvent2); bankAccount2.setEvents(events2); Money totalAmount1 = getBalance(bankAccount1); Money totalAmount2 = getBalance(bankAccount2); System.out.println("bankAccount1 = " + totalAmount1); System.out.println("bankAccount2 = " + totalAmount2); Money data = new Money(); data.setCurrency(bankAccount1.getEvents().get(0).getMoney().getCurrency()); data.setAmount(BigDecimal.valueOf(10000)); BankAccountService.Result result = BankAccountService.moveData( bankAccount1, bankAccount2, data ); Money newTotalAmount1 = getBalance(result.getTo()); Money newTotalAmount2 = getBalance(result.getFrom()); System.out.println("toTotalAmount = " + newTotalAmount1); System.out.println("fromTotalAmount = " + newTotalAmount2); } |
BankAccountService { public static TransferResult transfer(BankAccount to, BankAccount from, Money money) { BankAccount updatedFrom = from.withdrawTo(to, money); BankAccount updatedTo = to.depositFrom(from, money); return TransferResult.of(updatedTo, updatedFrom); } static TransferResult transfer(BankAccount to, BankAccount from, Money money); } | @Test public void transfer1() throws Exception { Money initialMoney = Money.of(10000); BankAccount bankAccount1 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); BankAccount bankAccount2 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); System.out.println("bankAccount1 = " + bankAccount1.getBalance()); System.out.println("bankAccount2 = " + bankAccount2.getBalance()); BankAccountService.TransferResult transferResult = BankAccountService.transfer( bankAccount1, bankAccount2, Money.of(10000) ); System.out.println("to = " + transferResult.getTo().getBalance()); System.out.println("from = " + transferResult.getFrom().getBalance()); }
@Test public void transfer2() throws Exception { Money initialMoney = Money.of(10000); BankAccount bankAccount1 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); BankAccount bankAccount2 = BankAccount.of(IdGenerator.generateId()).depositCash(initialMoney); System.out.println("bankAccount1 = " + bankAccount1.getBalance()); System.out.println("bankAccount2 = " + bankAccount2.getBalance()); try { BankAccountService.transfer(bankAccount1, bankAccount2, Money.of(20000)); fail("No error occurred!!!"); } catch (IllegalArgumentException ignored) { ; } } |
Connection implements io.trane.ndbc.datasource.Connection { @Override public Future<List<Row>> query(final String query) { return run(simpleQueryExchange.apply(query)); } Connection(final Channel channel, final Long connectionId, final Marshallers marshallers,
final Optional<Duration> queryTimeout, final ScheduledExecutorService scheduler,
final Function<String, Exchange<List<Row>>> simpleQueryExchange,
final Function<String, Exchange<Long>> simpleExecuteExchange,
final BiFunction<String, List<Value<?>>, Exchange<List<Row>>> extendedQueryExchange,
final BiFunction<String, List<Value<?>>, Exchange<Fetch>> extendedQueryStreamExchange,
final BiFunction<String, List<Value<?>>, Exchange<Long>> extendedExecuteExchange,
final Supplier<DataSource<PreparedStatement, Row>> dataSourceSupplier); @Override Future<Boolean> isValid(); @Override Future<Void> close(); @Override Future<List<Row>> query(final String query); @Override Future<Long> execute(final String command); @Override final Future<List<Row>> query(final PreparedStatement query); @Override Flow<Row> stream(PreparedStatement query); @Override Future<Long> execute(final PreparedStatement command); @Override Future<Void> beginTransaction(); @Override Future<Void> commit(); @Override Future<Void> rollback(); } | @Test public void query() throws CheckedFutureException { final List<Row> result = new ArrayList<>(); final String query = "query"; final Supplier<Connection> sup = new ConnectionSupplier() { @Override Function<String, Exchange<List<Row>>> simpleQueryExchange() { return q -> { assertEquals(query, q); return Exchange.value(result); }; } }; assertEquals(result, sup.get().query(query).get(timeout)); }
@Test public void queryPreparedStatement() throws CheckedFutureException { final List<Row> result = new ArrayList<>(); final String query = "query"; final Integer set = 123; final PreparedStatement ps = PreparedStatement.create(query).setInteger(set); final Supplier<Connection> sup = new ConnectionSupplier() { @Override BiFunction<String, List<Value<?>>, Exchange<List<Row>>> extendedQueryExchange() { return (q, b) -> { assertEquals(query, q); assertEquals(Arrays.asList(new IntegerValue(set)), b); return Exchange.value(result); }; } }; assertEquals(result, sup.get().query(ps).get(timeout)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.