target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testCreateSSLEnginewithPort() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; int port = 39093; String peerHost = "host1"; SSLEngine aSSLEngine = SSLManager.createSSLEngine(option, custom, peerHost, port); Assert.assertNotNull(aSSLEngine); Assert.assertEquals("host1", aSSLEngine.getPeerHost().toString()); }
|
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLEngine engine = context.createSSLEngine(); engine.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = engine.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); engine.setNeedClientAuth(option.isAuthPeer()); return engine; }
|
SSLManager { public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLEngine engine = context.createSSLEngine(); engine.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = engine.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); engine.setNeedClientAuth(option.isAuthPeer()); return engine; } }
|
SSLManager { public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLEngine engine = context.createSSLEngine(); engine.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = engine.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); engine.setNeedClientAuth(option.isAuthPeer()); return engine; } private SSLManager(); }
|
SSLManager { public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLEngine engine = context.createSSLEngine(); engine.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = engine.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); engine.setNeedClientAuth(option.isAuthPeer()); return engine; } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLEngine engine = context.createSSLEngine(); engine.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = engine.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); engine.setNeedClientAuth(option.isAuthPeer()); return engine; } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLContextException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws NoSuchAlgorithmException { throw new NoSuchAlgorithmException(); } }; try { SSLContext context = SSLManager.createSSLContext(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLContextKeyManagementException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws KeyManagementException { throw new KeyManagementException(); } }; try { SSLContext context = SSLManager.createSSLContext(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLContext createSSLContext(SSLOption option, SSLCustom custom) { try { String keyStoreName = custom.getFullPath(option.getKeyStore()); KeyManager[] keymanager; if (keyStoreName != null && new File(keyStoreName).exists()) { char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); KeyStore keyStore = KeyStoreUtil.createKeyStore(keyStoreName, option.getKeyStoreType(), keyStoreValue); keymanager = KeyStoreUtil.createKeyManagers(keyStore, keyStoreValue); } else { keymanager = null; } String trustStoreName = custom.getFullPath(option.getTrustStore()); TrustManager[] trustManager; if (trustStoreName != null && new File(trustStoreName).exists()) { char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); trustManager = KeyStoreUtil.createTrustManagers(trustStore); } else { trustManager = new TrustManager[] {new TrustAllManager()}; } TrustManager[] wrapped = new TrustManager[trustManager.length]; for (int i = 0; i < trustManager.length; i++) { wrapped[i] = new TrustManagerExt((X509ExtendedTrustManager) trustManager[i], option, custom); } SSLContext context = SSLContext.getInstance("TLS"); context.init(keymanager, wrapped, new SecureRandom()); return context; } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("NoSuchAlgorithmException." + e.getMessage()); } catch (KeyManagementException e) { throw new IllegalArgumentException("KeyManagementException." + e.getMessage()); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLServerSocketException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws UnknownHostException { throw new UnknownHostException(); } }; try { SSLServerSocket context = SSLManager.createSSLServerSocket(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLServerSocketIOException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws IOException { throw new IOException(); } }; try { SSLServerSocket context = SSLManager.createSSLServerSocket(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLServerSocket createSSLServerSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLServerSocketFactory factory = context.getServerSocketFactory(); SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); socket.setNeedClientAuth(option.isAuthPeer()); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLSocketException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws UnknownHostException { throw new UnknownHostException(); } }; try { SSLSocket context = SSLManager.createSSLSocket(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLSocketIOException() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; new MockUp<SSLContext>() { @Mock public final SSLContext getInstance(String type) throws IOException { throw new IOException(); } }; try { SSLSocket context = SSLManager.createSSLSocket(option, custom); Assert.assertNotNull(context); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) { try { SSLContext context = createSSLContext(option, custom); SSLSocketFactory facroty = context.getSocketFactory(); SSLSocket socket = (SSLSocket) facroty.createSocket(); socket.setEnabledProtocols(option.getProtocols().split(",")); String[] supported = socket.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled)); return socket; } catch (UnknownHostException e) { throw new IllegalArgumentException("unkown host"); } catch (IOException e) { throw new IllegalArgumentException("unable create socket"); } } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@Test public void testCreateSSLSocketFactory() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; SSLSocketFactory aSSLSocketFactory = SSLManager.createSSLSocketFactory(option, custom); Assert.assertNotNull(aSSLSocketFactory.getDefaultCipherSuites()[0]); }
|
public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); }
|
SSLManager { public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); } }
|
SSLManager { public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); } private SSLManager(); }
|
SSLManager { public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
SSLManager { public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }
|
@SuppressWarnings("unused") @Test public void testSSLOptionNull() { try { SSLOption option = SSLOption.build(DIR + "/servers.ssl.properties"); } catch (IllegalArgumentException e) { Assert.assertEquals("Bad file name.", e.getMessage()); } }
|
public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); static final String DEFAULT_CIPHERS; }
|
@Test public void testRegisterSchemaException() { new MockUp<RestClientUtil>() { @Mock void put(IpPort ipPort, String uri, RequestParam requestParam, Handler<RestResponse> responseHandler) { } }; InterruptedException e = new InterruptedException(); new MockUp<CountDownLatch>() { @Mock public void await() throws InterruptedException { throw e; } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "register schema msid/schemaId fail.", events.get(0).getMessage()); Assert.assertEquals(e, events.get(0).getThrowableInformation().getThrowable()); } }.run(); }
|
@Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void testBuildException() { new MockUp<File>() { @Mock public String getCanonicalPath() throws IOException { throw new IOException(); } }; try { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); Assert.assertNotNull(option); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); static final String DEFAULT_CIPHERS; }
|
@Test public void testBuildInputStream() { try { URL url = this.getClass().getResource("/server.ssl.properties"); InputStream inputStream = url.openStream(); SSLOption option = SSLOption.build(inputStream); Assert.assertNotNull(option); } catch (Exception e) { Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } }
|
public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); }
|
SSLOption { public static SSLOption build(String optionfile) { File file = new File(optionfile); if (!file.isFile()) { throw new IllegalArgumentException("Bad file name."); } try { SSLOption option = new SSLOption(); option.load(file.getCanonicalPath()); return option; } catch (IOException e) { throw new IllegalArgumentException("Bad file name."); } } String getEngine(); void setEngine(String engine); void setProtocols(String protocols); void setCiphers(String ciphers); void setAuthPeer(boolean authPeer); void setCheckCNHost(boolean checkCNHost); void setCheckCNWhite(boolean checkCNWhite); void setCheckCNWhiteFile(String checkCNWhiteFile); void setAllowRenegociate(boolean allowRenegociate); void setStorePath(String storePath); void setTrustStore(String trustStore); void setTrustStoreType(String trustStoreType); void setTrustStoreValue(String trustStoreValue); void setKeyStore(String keyStore); void setKeyStoreType(String keyStoreType); void setKeyStoreValue(String keyStoreValue); void setCrl(String crl); String getProtocols(); String getCiphers(); boolean isAuthPeer(); boolean isCheckCNHost(); boolean isCheckCNWhite(); String getCheckCNWhiteFile(); boolean isAllowRenegociate(); String getStorePath(); String getTrustStore(); String getTrustStoreType(); String getTrustStoreValue(); String getKeyStore(); String getKeyStoreType(); String getKeyStoreValue(); String getCrl(); static SSLOption build(String optionfile); static SSLOption build(InputStream inputStream); static String getStringProperty(ConcurrentCompositeConfiguration configSource, String defaultValue,
String... keys); static SSLOption buildFromYaml(String tag, ConcurrentCompositeConfiguration configSource); static SSLOption buildFromYaml(String tag); String getSslCustomClass(); void setSslCustomClass(String sslCustomClass); static final String DEFAULT_CIPHERS; }
|
@Test public void testGetCN(@Mocked X500Principal aX500Principal, @Mocked MyX509Certificate myX509Certificate) { new Expectations() { { aX500Principal.getName(); result = "CN=Test1234"; myX509Certificate.getSubjectX500Principal(); result = aX500Principal; } }; MyX509Certificate xxmyX509Certificate = new MyX509Certificate(); Set<String> strExpect = CertificateUtil.getCN(xxmyX509Certificate); Assert.assertEquals(true, strExpect.contains("Test1234")); }
|
public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
@Test public void testGetCNException(@Mocked X500Principal aX500Principal, @Mocked MyX509Certificate myX509Certificate) { new Expectations() { { aX500Principal.getName(); result = "NOCN=Test1234"; myX509Certificate.getSubjectX500Principal(); result = aX500Principal; } }; MyX509Certificate xxmyX509Certificate = new MyX509Certificate(); try { Set<String> strExpect = CertificateUtil.getCN(xxmyX509Certificate); Assert.assertEquals(strExpect.size(), 0); } catch (IllegalArgumentException e) { Assert.assertNotNull(null); } }
|
public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
CertificateUtil { public static Set<String> getCN(X509Certificate cert) { Set<String> names = new HashSet<>(); String subjectDN = cert.getSubjectX500Principal().getName(); String[] pairs = subjectDN.split(","); for (String p : pairs) { String[] kv = p.split("="); if (kv.length == 2 && kv[0].equals("CN")) { names.add(kv[1]); } } try { Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { for (List<?> list : collection) { if (list.size() == 2) { Object key = list.get(0); Object value = list.get(1); if (key instanceof Integer && value instanceof String) { int intKey = ((Integer) key).intValue(); String strValue = (String) value; if (intKey == SUBALTNAME_DNSNAME || intKey == SUBALTNAME_IPADDRESS) { names.add(strValue); } } } } } } catch (CertificateParsingException e) { throw new IllegalArgumentException("can not read AlternativeNames."); } return names; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
@Test public void testFindOwner(@Mocked X500Principal aX500Principal1, @Mocked X500Principal aX500Principal2, @Mocked MyX509Certificate myX509Certificate) { new Expectations() { { aX500Principal1.getName(); result = "Huawei"; } { aX500Principal2.getName(); result = "Huawei"; } { myX509Certificate.getSubjectX500Principal(); result = aX500Principal1; myX509Certificate.getIssuerX500Principal(); result = aX500Principal2; } }; MyX509Certificate myX509Certificate1 = new MyX509Certificate(); MyX509Certificate myX509Certificate2 = new MyX509Certificate(); MyX509Certificate[] xxmyX509Certificate = new MyX509Certificate[2]; xxmyX509Certificate[0] = myX509Certificate1; xxmyX509Certificate[1] = myX509Certificate2; X509Certificate aX509Certificate = CertificateUtil.findOwner(xxmyX509Certificate); Assert.assertNull(aX509Certificate); }
|
public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
@Test public void testFindRootCAException(@Mocked X500Principal aX500Principal1, @Mocked X500Principal aX500Principal2, @Mocked MyX509Certificate myX509Certificate) { new Expectations() { { aX500Principal1.getName(); result = "Huawei1"; } { aX500Principal2.getName(); result = "Huawei3"; } { myX509Certificate.getSubjectX500Principal(); result = aX500Principal1; myX509Certificate.getIssuerX500Principal(); result = aX500Principal2; } }; MyX509Certificate myX509Certificate1 = new MyX509Certificate(); MyX509Certificate myX509Certificate2 = new MyX509Certificate(); MyX509Certificate[] xxmyX509Certificate = new MyX509Certificate[2]; xxmyX509Certificate[0] = myX509Certificate1; xxmyX509Certificate[1] = myX509Certificate2; try { X509Certificate aX509Certificate = CertificateUtil.findOwner(xxmyX509Certificate); Assert.assertNull(aX509Certificate); } catch (IllegalArgumentException e) { Assert.assertEquals("bad certificate chain: no root CA.", e.getMessage()); } }
|
public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
CertificateUtil { public static X509Certificate findOwner(X509Certificate[] cerChain) { X509Certificate[] sorted = sort(cerChain); return sorted[sorted.length - 1]; } private CertificateUtil(); static X509Certificate findOwner(X509Certificate[] cerChain); static Set<String> getCN(X509Certificate cert); }
|
@SuppressWarnings("unused") @Test public void testConstructor() { String keyStoreName = custom.getFullPath(option.getKeyStore()); char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); String trustStoreName = custom.getFullPath(option.getTrustStore()); char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); TrustManager[] trustManager = KeyStoreUtil.createTrustManagers(trustStore); TrustManagerExt trustManagerExt = new TrustManagerExt((X509ExtendedTrustManager) trustManager[0], option, custom); Assert.assertEquals(3, trustManagerExt.getAcceptedIssuers()[0].getVersion()); Assert.assertNotNull(trustManagerExt); }
|
@Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); } }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
@Test public void testCheckClientTrusted(@Mocked CertificateUtil certificateUtil) { MyX509Certificate myX509Certificate1 = new MyX509Certificate(); MyX509Certificate myX509Certificate2 = new MyX509Certificate(); MyX509Certificate[] MyX509CertificateArray = new MyX509Certificate[2]; MyX509CertificateArray[0] = myX509Certificate1; MyX509CertificateArray[1] = myX509Certificate2; new Expectations() { { CertificateUtil.findOwner((X509Certificate[]) any); result = any; CertificateUtil.getCN((X509Certificate) any); result = "10.67.147.115"; } }; MyX509ExtendedTrustManager myX509ExtendedTrustManager = new MyX509ExtendedTrustManager(); TrustManagerExt trustManagerExt = new TrustManagerExt(myX509ExtendedTrustManager, option, custom); Socket socket = null; SSLEngine sslengine = null; boolean validAssert = true; try { trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", socket); trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", sslengine); trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", socket); trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", sslengine); } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); }
|
@Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
@Test public void testCatchException(@Mocked CertificateUtil certificateUtil) { MyX509Certificate myX509Certificate1 = new MyX509Certificate(); MyX509Certificate myX509Certificate2 = new MyX509Certificate(); MyX509Certificate[] MyX509CertificateArray = new MyX509Certificate[2]; MyX509CertificateArray[0] = myX509Certificate1; MyX509CertificateArray[1] = myX509Certificate2; new Expectations() { { CertificateUtil.findOwner((X509Certificate[]) any); result = any; CertificateUtil.getCN((X509Certificate) any); result = "10.67.147.114"; } }; MyX509ExtendedTrustManager myX509ExtendedTrustManager = new MyX509ExtendedTrustManager(); TrustManagerExt trustManagerExt = new TrustManagerExt(myX509ExtendedTrustManager, option, custom); boolean validAssert = true; try { trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks"); } catch (CertificateException e) { Assert.assertEquals("CN does not match IP: e=[10.67.147.114],t=null", e.getMessage()); validAssert = false; } Assert.assertFalse(validAssert); }
|
@Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
TrustManagerExt extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (!option.isAuthPeer()) { return; } checkTrustedCustom(chain, null); trustManager.checkClientTrusted(chain, authType); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }
|
@Test public void testCreateSocketException() { boolean validAssert = true; try { instance.createSocket("host", 8080); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
|
@Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); }
|
SSLSocketFactoryExt extends SSLSocketFactory { @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); } }
|
SSLSocketFactoryExt extends SSLSocketFactory { @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); } SSLSocketFactoryExt(SSLSocketFactory factory, String[] ciphers, String[] protos); }
|
SSLSocketFactoryExt extends SSLSocketFactory { @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); } SSLSocketFactoryExt(SSLSocketFactory factory, String[] ciphers, String[] protos); @Override Socket createSocket(Socket s, String host, int port, boolean autoClose); @Override String[] getDefaultCipherSuites(); @Override String[] getSupportedCipherSuites(); @Override Socket createSocket(String host, int port); @Override Socket createSocket(InetAddress host, int port); @Override Socket createSocket(String host, int port, InetAddress localHost,
int localPort); @Override Socket createSocket(InetAddress address, int port, InetAddress localAddress,
int localPort); }
|
SSLSocketFactoryExt extends SSLSocketFactory { @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); } SSLSocketFactoryExt(SSLSocketFactory factory, String[] ciphers, String[] protos); @Override Socket createSocket(Socket s, String host, int port, boolean autoClose); @Override String[] getDefaultCipherSuites(); @Override String[] getSupportedCipherSuites(); @Override Socket createSocket(String host, int port); @Override Socket createSocket(InetAddress host, int port); @Override Socket createSocket(String host, int port, InetAddress localHost,
int localPort); @Override Socket createSocket(InetAddress address, int port, InetAddress localAddress,
int localPort); }
|
@Test public void testRegisterSchemaErrorResponse() { new MockUp<ServiceRegistryClientImpl>() { @Mock Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) { return restResponse -> { HttpClientResponse response = Mockito.mock(HttpClientResponse.class); Mockito.when(response.statusCode()).thenReturn(400); Mockito.when(response.statusMessage()).thenReturn("client error"); Buffer bodyBuffer = Buffer.buffer(); bodyBuffer.appendString("too big"); ResponseWrapper responseWrapper = new ResponseWrapper(); responseWrapper.response = response; responseWrapper.bodyBuffer = bodyBuffer; holder.value = responseWrapper; }; } }; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { responseHandler.handle(null); } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "Register schema msid/schemaId failed, statusCode: 400, statusMessage: client error, description: too big.", events.get(0).getMessage()); } }.run(); }
|
@Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void testCreateKeyStoreException() { String storename = ""; String storetype = "testType"; char[] storevalue = "Changeme_123".toCharArray(); try { KeyStoreUtil.createKeyStore(storename, storetype, storevalue); } catch (IllegalArgumentException e) { Assert.assertEquals("Bad key store or value.testType not found", e.getMessage()); } }
|
public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void testCreateKeyStoreException2() { String storename = strFilePath + "/ssl/trust.jks"; String storetype = "PKCS12"; char[] storevalue = "Changeme_123".toCharArray(); try { KeyStoreUtil.createKeyStore(storename, storetype, storevalue); } catch (IllegalArgumentException e) { Assert.assertEquals("Bad key store or value.DerInputStream.getLength(): lengthTag=109, too big.", e.getMessage()); } }
|
public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void testCreateCRL() { String crlfile = strFilePath + "/ssl/server.p12"; mockGenerateCRLs(); boolean validAssert = true; try { CRL[] crl = KeyStoreUtil.createCRL(crlfile); Assert.assertNull(crl); } catch (Exception e) { validAssert = false; } Assert.assertTrue(validAssert); }
|
@SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void testCreateCRLException() { String crlfile = strFilePath + "/ssl/server.p12"; boolean validAssert = true; try { new MockUp<CertificateFactory>() { @Mock public final CertificateFactory getInstance(String type) throws CertificateException { throw new CertificateException(); } }; KeyStoreUtil.createCRL(crlfile); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); }
|
@SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void testExceptionFileNotFound() { String crlfile = strFilePath + "/ssl/server.p12"; boolean validAssert = true; try { new MockUp<CertificateFactory>() { @Mock public final CertificateFactory getInstance( String type) throws CertificateException, FileNotFoundException { throw new FileNotFoundException(); } }; KeyStoreUtil.createCRL(crlfile); } catch (Exception e) { validAssert = false; Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } Assert.assertFalse(validAssert); }
|
@SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void testExceptionCRLException() { String crlfile = strFilePath + "/ssl/server.p12"; boolean validAssert = true; try { new MockUp<CertificateFactory>() { @Mock public final CertificateFactory getInstance(String type) throws CertificateException, CRLException { throw new CRLException(); } }; KeyStoreUtil.createCRL(crlfile); } catch (Exception e) { validAssert = false; Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName()); } Assert.assertFalse(validAssert); }
|
@SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
KeyStoreUtil { @SuppressWarnings({"rawtypes", "unchecked"}) public static CRL[] createCRL(String crlfile) { InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlfile); Collection c = cf.generateCRLs(is); CRL[] crls = (CRL[]) c.toArray(new CRL[c.size()]); return crls; } catch (CertificateException e) { throw new IllegalArgumentException("bad cert file."); } catch (FileNotFoundException e) { throw new IllegalArgumentException("crl file not found."); } catch (CRLException e) { throw new IllegalArgumentException("bad crl file."); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }
|
@Test public void parse() throws IOException { URL url = Thread.currentThread().getContextClassLoader().getResource("protobufRoot.proto"); String content = IOUtils.toString(url, StandardCharsets.UTF_8); ProtoParser parser = new ProtoParser(); Proto protoFromContent = parser.parseFromContent(content); Proto protoFromName = parser.parse("protobufRoot.proto"); Assert.assertNotNull(protoFromContent.getMessage("Root")); Assert.assertNotNull(protoFromContent.getMessage("User")); Assert.assertEquals(MoreObjects.toStringHelper(protoFromContent) .omitNullValues() .add("messages", protoFromContent.getMessages()) .toString(), MoreObjects.toStringHelper(protoFromName) .omitNullValues() .add("messages", protoFromName.getMessages()) .toString()); }
|
public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } }
|
ProtoParser { public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } }
|
ProtoParser { public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } }
|
ProtoParser { public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } Proto parseFromContent(String content); Proto parse(String name); }
|
ProtoParser { public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } Proto parseFromContent(String content); Proto parse(String name); }
|
@Test public void generic() { Method method = ReflectUtils.findMethod(GenericSchema.class, "genericMethod"); BeanDescriptor beanDescriptor = beanDescriptorManager .getOrCreateBeanDescriptor(method.getGenericParameterTypes()[0]); Assert.assertEquals(String.class, beanDescriptor.getPropertyDescriptors().get("value").getJavaType().getRawClass()); }
|
public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); BeanDescriptor getOrCreateBeanDescriptor(Type type); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); BeanDescriptor getOrCreateBeanDescriptor(Type type); }
|
@Test public void getOrCreate() { Assert.assertSame(beanDescriptor, beanDescriptorManager.getOrCreateBeanDescriptor(Model.class)); Assert.assertSame(Model.class, beanDescriptor.getJavaType().getRawClass()); }
|
public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); BeanDescriptor getOrCreateBeanDescriptor(Type type); }
|
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); BeanDescriptor getOrCreateBeanDescriptor(Type type); }
|
@Test public void testValidProperty() { String validProperty1 = "0,1,2,10"; String validProperty2 = "0,1, 2 , 10 "; String validProperty3 = "0,1,2,10,"; LatencyDistributionConfig config1 = new LatencyDistributionConfig(validProperty1); LatencyDistributionConfig config2 = new LatencyDistributionConfig(validProperty2); LatencyDistributionConfig config3 = new LatencyDistributionConfig(validProperty3); Assert.assertEquals(4, config1.getScopeConfigs().size()); Assert.assertEquals(4, config2.getScopeConfigs().size()); Assert.assertEquals(4, config3.getScopeConfigs().size()); }
|
public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
@Test public void testRegisterSchemaSuccess() { new MockUp<ServiceRegistryClientImpl>() { @Mock Handler<RestResponse> syncHandlerEx(CountDownLatch countDownLatch, Holder<ResponseWrapper> holder) { return restResponse -> { HttpClientResponse response = Mockito.mock(HttpClientResponse.class); Mockito.when(response.statusCode()).thenReturn(200); ResponseWrapper responseWrapper = new ResponseWrapper(); responseWrapper.response = response; holder.value = responseWrapper; }; } }; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { responseHandler.handle(null); } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.registerSchema("msid", "schemaId", "content"); Assert.assertEquals( "register schema msid/schemaId success.", events.get(0).getMessage()); } }.run(); }
|
@Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean registerSchema(String microserviceId, String schemaId, String schemaContent) { Holder<ResponseWrapper> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); try { CreateSchemaRequest request = new CreateSchemaRequest(); request.setSchema(schemaContent); request.setSummary(RegistryUtils.calcSchemaSummary(schemaContent)); byte[] body = JsonUtils.writeValueAsBytes(request); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.put(ipPort, String.format(Const.REGISTRY_API.MICROSERVICE_SCHEMA, microserviceId, schemaId), new RequestParam().setBody(body), syncHandlerEx(countDownLatch, holder)); countDownLatch.await(); if (holder.value == null) { LOGGER.error("Register schema {}/{} failed.", microserviceId, schemaId); return false; } if (!Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(holder.value.response.statusCode()))) { LOGGER.error("Register schema {}/{} failed, statusCode: {}, statusMessage: {}, description: {}.", microserviceId, schemaId, holder.value.response.statusCode(), holder.value.response.statusMessage(), holder.value.bodyBuffer.toString()); return false; } LOGGER.info("register schema {}/{} success.", microserviceId, schemaId); return true; } catch (Exception e) { LOGGER.error("register schema {}/{} fail.", microserviceId, schemaId, e); } return false; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void testInValidProperty1() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("invalid latency scope, min=2, max=1."); LatencyDistributionConfig latencyDistributionConfig = new LatencyDistributionConfig("2,1,10"); Assert.assertEquals(0, latencyDistributionConfig.getScopeConfigs().size()); }
|
public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
@Test public void testInValidProperty2() { expectedException.expect(NumberFormatException.class); expectedException.expectMessage("For input string: \"a\""); LatencyDistributionConfig latencyDistributionConfig = new LatencyDistributionConfig("a,1,10"); Assert.assertEquals(0, latencyDistributionConfig.getScopeConfigs().size()); }
|
public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }
|
@Test public void getTagKey() { Assert.assertEquals("key", finder.getTagKey()); }
|
@Override public String getTagKey() { return tagKey; }
|
DefaultTagFinder implements TagFinder { @Override public String getTagKey() { return tagKey; } }
|
DefaultTagFinder implements TagFinder { @Override public String getTagKey() { return tagKey; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); }
|
DefaultTagFinder implements TagFinder { @Override public String getTagKey() { return tagKey; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
DefaultTagFinder implements TagFinder { @Override public String getTagKey() { return tagKey; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
@Test public void readSucc() { Tag tag = new BasicTag("key", "value"); List<Tag> tags = Arrays.asList(new BasicTag("t1", "t1v"), tag); Assert.assertSame(tag, finder.find(tags)); }
|
@Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
@Test public void readFail() { List<Tag> tags = Arrays.asList(new BasicTag("t1", "t1v")); Assert.assertNull(finder.find(tags)); }
|
@Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }
|
@Test public void addGroup() { config.addGroup("id1", "tag1.1", "tag1.2"); config.addGroup("id2", "tag2.1", "tag2.2"); Assert.assertThat(groups.keySet(), Matchers.contains("id2", "id1")); Assert.assertThat(groups.get("id1").stream().map(e -> { return e.getTagKey(); }).toArray(), Matchers.arrayContaining("tag1.1", "tag1.2")); Assert.assertThat(groups.get("id2").stream().map(e -> { return e.getTagKey(); }).toArray(), Matchers.arrayContaining("tag2.1", "tag2.2")); }
|
public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); }
|
MeasurementGroupConfig { public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); } }
|
MeasurementGroupConfig { public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); } MeasurementGroupConfig(); MeasurementGroupConfig(String idName, Object... tagNameOrFinders); }
|
MeasurementGroupConfig { public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); } MeasurementGroupConfig(); MeasurementGroupConfig(String idName, Object... tagNameOrFinders); void addGroup(String idName, Object... tagNameOrFinders); List<TagFinder> findTagFinders(String idName); }
|
MeasurementGroupConfig { public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); } MeasurementGroupConfig(); MeasurementGroupConfig(String idName, Object... tagNameOrFinders); void addGroup(String idName, Object... tagNameOrFinders); List<TagFinder> findTagFinders(String idName); }
|
@Test public void from() { timer.record(10, TimeUnit.NANOSECONDS); timer.record(2, TimeUnit.NANOSECONDS); MeasurementGroupConfig config = new MeasurementGroupConfig("id", "g1", "g2", Statistic.count.key()); tree.from(registry.iterator(), config); Assert.assertEquals(2, tree.getChildren().size()); MeasurementNode node = tree.findChild("id", "g1v", "g2v"); Assert.assertEquals(2d, node.findChild(Statistic.count.value()).getMeasurements().get(0).value(), 0); Assert.assertEquals(12d, node.findChild(Statistic.totalTime.value()).getMeasurements().get(0).value(), 0); Assert.assertEquals(0d, tree.findChild("id_notCare").summary(), 0); }
|
public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
@Test public void from_withSkipOnNull() { try { MeasurementGroupConfig config = new MeasurementGroupConfig("id", new DefaultTagFinder("notExist", true)); tree.from(registry.iterator(), config); } catch (Exception e) { Assert.fail("should not throw exception"); } }
|
public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
@Test public void from_failed() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(Matchers .is("tag key \"notExist\" not exist in Measurement(id:g1=g1v:g2=g2v:statistic=count:t3=t3v:t4=t4v,0,0.0)")); MeasurementGroupConfig config = new MeasurementGroupConfig("id", "notExist"); tree.from(registry.iterator(), config); }
|
public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }
|
@Test public void getName() { Assert.assertEquals("name", node.getName()); }
|
public String getName() { return name; }
|
MeasurementNode { public String getName() { return name; } }
|
MeasurementNode { public String getName() { return name; } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public String getName() { return name; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public String getName() { return name; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void syncHandler_failed(@Mocked RequestContext requestContext, @Mocked HttpClientResponse response) { CountDownLatch countDownLatch = new CountDownLatch(1); Class<GetExistenceResponse> cls = GetExistenceResponse.class; Holder<GetExistenceResponse> holder = new Holder<>(); Handler<RestResponse> handler = oClient.syncHandler(countDownLatch, cls, holder); Holder<Handler<Buffer>> bodyHandlerHolder = new Holder<>(); new MockUp<HttpClientResponse>(response) { @Mock HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) { bodyHandlerHolder.value = bodyHandler; return null; } }; new Expectations() { { response.statusCode(); result = 400; response.statusMessage(); result = Status.BAD_REQUEST.getReasonPhrase(); } }; RestResponse event = new RestResponse(requestContext, response); handler.handle(event); Buffer bodyBuffer = Buffer.buffer("{}"); bodyHandlerHolder.value.handle(bodyBuffer); Assert.assertNull(holder.value); }
|
@VisibleForTesting @SuppressWarnings("unchecked") protected <T> Handler<RestResponse> syncHandler(CountDownLatch countDownLatch, Class<T> cls, Holder<T> holder) { return restResponse -> { RequestContext requestContext = restResponse.getRequestContext(); HttpClientResponse response = restResponse.getResponse(); if (response == null) { if (requestContext.getRetryTimes() <= ipPortManager.getMaxRetryTimes()) { retry(requestContext, syncHandler(countDownLatch, cls, holder)); } else { countDownLatch.countDown(); } return; } holder.setStatusCode(response.statusCode()); response.exceptionHandler(e -> { LOGGER.error("error in processing response.", e); countDownLatch.countDown(); }); response.bodyHandler( bodyBuffer -> { if (cls.getName().equals(HttpClientResponse.class.getName())) { holder.value = (T) response; countDownLatch.countDown(); return; } if (cls.equals(String.class)) { holder.setValue((T) bodyBuffer.toString()); countDownLatch.countDown(); return; } if (HttpStatusClass.CLIENT_ERROR.equals(HttpStatusClass.valueOf(response.statusCode()))) { try { Map<String, String> bufferMap = JsonUtils.readValue(bodyBuffer.getBytes(), Map.class); if (bufferMap.containsKey(ERROR_CODE)) { String errorCode = bufferMap.get(ERROR_CODE); if (errorCode.equals(ERR_SERVICE_NOT_EXISTS) || errorCode.equals(ERR_SCHEMA_NOT_EXISTS)) { countDownLatch.countDown(); return; } } } catch (IOException e) { LOGGER.warn("read value failed from buffer {}", bodyBuffer.toString()); } } if (!HttpStatusClass.SUCCESS.equals(HttpStatusClass.valueOf(response.statusCode()))) { LOGGER.warn("get response for {} failed, {}:{}, {}", cls.getName(), response.statusCode(), response.statusMessage(), bodyBuffer.toString()); countDownLatch.countDown(); return; } try { holder.value = JsonUtils.readValue(bodyBuffer.getBytes(), cls); } catch (Exception e) { holder.setStatusCode(0).setThrowable(e); LOGGER.warn("read value failed and response message is {}", bodyBuffer.toString()); } countDownLatch.countDown(); }); }; }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @VisibleForTesting @SuppressWarnings("unchecked") protected <T> Handler<RestResponse> syncHandler(CountDownLatch countDownLatch, Class<T> cls, Holder<T> holder) { return restResponse -> { RequestContext requestContext = restResponse.getRequestContext(); HttpClientResponse response = restResponse.getResponse(); if (response == null) { if (requestContext.getRetryTimes() <= ipPortManager.getMaxRetryTimes()) { retry(requestContext, syncHandler(countDownLatch, cls, holder)); } else { countDownLatch.countDown(); } return; } holder.setStatusCode(response.statusCode()); response.exceptionHandler(e -> { LOGGER.error("error in processing response.", e); countDownLatch.countDown(); }); response.bodyHandler( bodyBuffer -> { if (cls.getName().equals(HttpClientResponse.class.getName())) { holder.value = (T) response; countDownLatch.countDown(); return; } if (cls.equals(String.class)) { holder.setValue((T) bodyBuffer.toString()); countDownLatch.countDown(); return; } if (HttpStatusClass.CLIENT_ERROR.equals(HttpStatusClass.valueOf(response.statusCode()))) { try { Map<String, String> bufferMap = JsonUtils.readValue(bodyBuffer.getBytes(), Map.class); if (bufferMap.containsKey(ERROR_CODE)) { String errorCode = bufferMap.get(ERROR_CODE); if (errorCode.equals(ERR_SERVICE_NOT_EXISTS) || errorCode.equals(ERR_SCHEMA_NOT_EXISTS)) { countDownLatch.countDown(); return; } } } catch (IOException e) { LOGGER.warn("read value failed from buffer {}", bodyBuffer.toString()); } } if (!HttpStatusClass.SUCCESS.equals(HttpStatusClass.valueOf(response.statusCode()))) { LOGGER.warn("get response for {} failed, {}:{}, {}", cls.getName(), response.statusCode(), response.statusMessage(), bodyBuffer.toString()); countDownLatch.countDown(); return; } try { holder.value = JsonUtils.readValue(bodyBuffer.getBytes(), cls); } catch (Exception e) { holder.setStatusCode(0).setThrowable(e); LOGGER.warn("read value failed and response message is {}", bodyBuffer.toString()); } countDownLatch.countDown(); }); }; } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @VisibleForTesting @SuppressWarnings("unchecked") protected <T> Handler<RestResponse> syncHandler(CountDownLatch countDownLatch, Class<T> cls, Holder<T> holder) { return restResponse -> { RequestContext requestContext = restResponse.getRequestContext(); HttpClientResponse response = restResponse.getResponse(); if (response == null) { if (requestContext.getRetryTimes() <= ipPortManager.getMaxRetryTimes()) { retry(requestContext, syncHandler(countDownLatch, cls, holder)); } else { countDownLatch.countDown(); } return; } holder.setStatusCode(response.statusCode()); response.exceptionHandler(e -> { LOGGER.error("error in processing response.", e); countDownLatch.countDown(); }); response.bodyHandler( bodyBuffer -> { if (cls.getName().equals(HttpClientResponse.class.getName())) { holder.value = (T) response; countDownLatch.countDown(); return; } if (cls.equals(String.class)) { holder.setValue((T) bodyBuffer.toString()); countDownLatch.countDown(); return; } if (HttpStatusClass.CLIENT_ERROR.equals(HttpStatusClass.valueOf(response.statusCode()))) { try { Map<String, String> bufferMap = JsonUtils.readValue(bodyBuffer.getBytes(), Map.class); if (bufferMap.containsKey(ERROR_CODE)) { String errorCode = bufferMap.get(ERROR_CODE); if (errorCode.equals(ERR_SERVICE_NOT_EXISTS) || errorCode.equals(ERR_SCHEMA_NOT_EXISTS)) { countDownLatch.countDown(); return; } } } catch (IOException e) { LOGGER.warn("read value failed from buffer {}", bodyBuffer.toString()); } } if (!HttpStatusClass.SUCCESS.equals(HttpStatusClass.valueOf(response.statusCode()))) { LOGGER.warn("get response for {} failed, {}:{}, {}", cls.getName(), response.statusCode(), response.statusMessage(), bodyBuffer.toString()); countDownLatch.countDown(); return; } try { holder.value = JsonUtils.readValue(bodyBuffer.getBytes(), cls); } catch (Exception e) { holder.setStatusCode(0).setThrowable(e); LOGGER.warn("read value failed and response message is {}", bodyBuffer.toString()); } countDownLatch.countDown(); }); }; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @VisibleForTesting @SuppressWarnings("unchecked") protected <T> Handler<RestResponse> syncHandler(CountDownLatch countDownLatch, Class<T> cls, Holder<T> holder) { return restResponse -> { RequestContext requestContext = restResponse.getRequestContext(); HttpClientResponse response = restResponse.getResponse(); if (response == null) { if (requestContext.getRetryTimes() <= ipPortManager.getMaxRetryTimes()) { retry(requestContext, syncHandler(countDownLatch, cls, holder)); } else { countDownLatch.countDown(); } return; } holder.setStatusCode(response.statusCode()); response.exceptionHandler(e -> { LOGGER.error("error in processing response.", e); countDownLatch.countDown(); }); response.bodyHandler( bodyBuffer -> { if (cls.getName().equals(HttpClientResponse.class.getName())) { holder.value = (T) response; countDownLatch.countDown(); return; } if (cls.equals(String.class)) { holder.setValue((T) bodyBuffer.toString()); countDownLatch.countDown(); return; } if (HttpStatusClass.CLIENT_ERROR.equals(HttpStatusClass.valueOf(response.statusCode()))) { try { Map<String, String> bufferMap = JsonUtils.readValue(bodyBuffer.getBytes(), Map.class); if (bufferMap.containsKey(ERROR_CODE)) { String errorCode = bufferMap.get(ERROR_CODE); if (errorCode.equals(ERR_SERVICE_NOT_EXISTS) || errorCode.equals(ERR_SCHEMA_NOT_EXISTS)) { countDownLatch.countDown(); return; } } } catch (IOException e) { LOGGER.warn("read value failed from buffer {}", bodyBuffer.toString()); } } if (!HttpStatusClass.SUCCESS.equals(HttpStatusClass.valueOf(response.statusCode()))) { LOGGER.warn("get response for {} failed, {}:{}, {}", cls.getName(), response.statusCode(), response.statusMessage(), bodyBuffer.toString()); countDownLatch.countDown(); return; } try { holder.value = JsonUtils.readValue(bodyBuffer.getBytes(), cls); } catch (Exception e) { holder.setStatusCode(0).setThrowable(e); LOGGER.warn("read value failed and response message is {}", bodyBuffer.toString()); } countDownLatch.countDown(); }); }; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @VisibleForTesting @SuppressWarnings("unchecked") protected <T> Handler<RestResponse> syncHandler(CountDownLatch countDownLatch, Class<T> cls, Holder<T> holder) { return restResponse -> { RequestContext requestContext = restResponse.getRequestContext(); HttpClientResponse response = restResponse.getResponse(); if (response == null) { if (requestContext.getRetryTimes() <= ipPortManager.getMaxRetryTimes()) { retry(requestContext, syncHandler(countDownLatch, cls, holder)); } else { countDownLatch.countDown(); } return; } holder.setStatusCode(response.statusCode()); response.exceptionHandler(e -> { LOGGER.error("error in processing response.", e); countDownLatch.countDown(); }); response.bodyHandler( bodyBuffer -> { if (cls.getName().equals(HttpClientResponse.class.getName())) { holder.value = (T) response; countDownLatch.countDown(); return; } if (cls.equals(String.class)) { holder.setValue((T) bodyBuffer.toString()); countDownLatch.countDown(); return; } if (HttpStatusClass.CLIENT_ERROR.equals(HttpStatusClass.valueOf(response.statusCode()))) { try { Map<String, String> bufferMap = JsonUtils.readValue(bodyBuffer.getBytes(), Map.class); if (bufferMap.containsKey(ERROR_CODE)) { String errorCode = bufferMap.get(ERROR_CODE); if (errorCode.equals(ERR_SERVICE_NOT_EXISTS) || errorCode.equals(ERR_SCHEMA_NOT_EXISTS)) { countDownLatch.countDown(); return; } } } catch (IOException e) { LOGGER.warn("read value failed from buffer {}", bodyBuffer.toString()); } } if (!HttpStatusClass.SUCCESS.equals(HttpStatusClass.valueOf(response.statusCode()))) { LOGGER.warn("get response for {} failed, {}:{}, {}", cls.getName(), response.statusCode(), response.statusMessage(), bodyBuffer.toString()); countDownLatch.countDown(); return; } try { holder.value = JsonUtils.readValue(bodyBuffer.getBytes(), cls); } catch (Exception e) { holder.setStatusCode(0).setThrowable(e); LOGGER.warn("read value failed and response message is {}", bodyBuffer.toString()); } countDownLatch.countDown(); }); }; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void getChildren() { Map<String, MeasurementNode> children = new HashMap<>(); node = new MeasurementNode("name", children); Assert.assertSame(children, node.getChildren()); }
|
public Map<String, MeasurementNode> getChildren() { return children; }
|
MeasurementNode { public Map<String, MeasurementNode> getChildren() { return children; } }
|
MeasurementNode { public Map<String, MeasurementNode> getChildren() { return children; } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public Map<String, MeasurementNode> getChildren() { return children; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public Map<String, MeasurementNode> getChildren() { return children; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void findChild_noChildren() { Assert.assertNull(node.findChild("child")); }
|
public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); }
|
MeasurementNode { public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); } }
|
MeasurementNode { public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void addChild(@Mocked Measurement measurement) { MeasurementNode c1 = node.addChild("c1", measurement); MeasurementNode c2 = node.addChild("c2", measurement); Assert.assertSame(c1, node.findChild("c1")); Assert.assertSame(c2, node.findChild("c2")); }
|
public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; }
|
MeasurementNode { public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; } }
|
MeasurementNode { public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void getMeasurements(@Mocked Measurement measurement) { node.addMeasurement(measurement); Assert.assertThat(node.getMeasurements(), Matchers.contains(measurement)); }
|
public List<Measurement> getMeasurements() { return measurements; }
|
MeasurementNode { public List<Measurement> getMeasurements() { return measurements; } }
|
MeasurementNode { public List<Measurement> getMeasurements() { return measurements; } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public List<Measurement> getMeasurements() { return measurements; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public List<Measurement> getMeasurements() { return measurements; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void summary(@Mocked Measurement measurement) { new Expectations() { { measurement.value(); result = 10; } }; node.addMeasurement(measurement); node.addMeasurement(measurement); Assert.assertEquals(20, node.summary(), 0); }
|
public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; }
|
MeasurementNode { public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; } }
|
MeasurementNode { public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; } MeasurementNode(String name, Map<String, MeasurementNode> children); }
|
MeasurementNode { public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
MeasurementNode { public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }
|
@Test public void loadMetricsInitializers() { List<MetricsInitializer> initList = new ArrayList<>(); MetricsInitializer metricsInitializer = new MetricsInitializer() { @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { initList.add(this); } }; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(MetricsInitializer.class); result = Arrays.asList(metricsInitializer, metricsInitializer); } }; bootstrap.start(globalRegistry, eventBus); bootstrap.shutdown(); Assert.assertThat(initList, Matchers.contains(metricsInitializer, metricsInitializer)); }
|
protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); }
|
MetricsBootstrap { protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); } }
|
MetricsBootstrap { protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); } }
|
MetricsBootstrap { protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
MetricsBootstrap { protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
@Test public void pollMeters(@Mocked Registry registry, @Mocked Meter meter, @Mocked Measurement measurement, @Mocked ScheduledExecutorService executor) { List<Meter> meters = Arrays.asList(meter); globalRegistry.add(registry); new Expectations(Executors.class) { { Executors.newScheduledThreadPool(1, (ThreadFactory) any); result = executor; registry.iterator(); result = meters.iterator(); meter.measure(); result = Arrays.asList(measurement); } }; bootstrap.start(globalRegistry, eventBus); PolledEvent result = new PolledEvent(null, null); eventBus.register(new Object() { @Subscribe public void onEvent(PolledEvent event) { result.setMeters(event.getMeters()); result.setMeasurements(event.getMeasurements()); } }); bootstrap.pollMeters(); bootstrap.shutdown(); Assert.assertEquals(meters, result.getMeters()); Assert.assertThat(result.getMeasurements(), Matchers.contains(measurement)); }
|
public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } }
|
MetricsBootstrap { public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } } }
|
MetricsBootstrap { public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } } }
|
MetricsBootstrap { public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
MetricsBootstrap { public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
@Test public void shutdown(@Mocked ScheduledExecutorService scheduledExecutorService) { List<MetricsInitializer> destroyList = new ArrayList<>(); MetricsInitializer initializer1 = new MetricsInitializer() { @Override public int getOrder() { return 1; } @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { } @Override public void destroy() { destroyList.add(this); } }; MetricsInitializer initializer2 = new MetricsInitializer() { @Override public int getOrder() { return 2; } @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { } @Override public void destroy() { destroyList.add(this); } }; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(MetricsInitializer.class); result = Arrays.asList(initializer1, initializer2); } }; Deencapsulation.setField(bootstrap, "executorService", scheduledExecutorService); bootstrap.shutdown(); Assert.assertThat(destroyList, Matchers.contains(initializer2, initializer1)); }
|
public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
@Test public void shutdown_notStart() { Assert.assertNull(Deencapsulation.getField(bootstrap, "executorService")); bootstrap.shutdown(); }
|
public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }
|
@Test public void unknown() { Assert.assertThat(resolver.replace("prefix${xxx}suffix", parameters), Matchers.contains("prefix${xxx}suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void isSchemaExist() { String microserviceId = "msId"; String schemaId = "schemaId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetExistenceResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); holder.value = new GetExistenceResponse(); } }; Assert.assertFalse(oClient.isSchemaExist(microserviceId, schemaId)); }
|
@Override public boolean isSchemaExist(String microserviceId, String schemaId) { Holder<GetExistenceResponse> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema") .addQueryParam("serviceId", microserviceId) .addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder)); try { countDownLatch.await(); } catch (Exception e) { LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e); } return holder.value != null && schemaId.equals(holder.value.getSchemaId()); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean isSchemaExist(String microserviceId, String schemaId) { Holder<GetExistenceResponse> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema") .addQueryParam("serviceId", microserviceId) .addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder)); try { countDownLatch.await(); } catch (Exception e) { LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e); } return holder.value != null && schemaId.equals(holder.value.getSchemaId()); } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean isSchemaExist(String microserviceId, String schemaId) { Holder<GetExistenceResponse> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema") .addQueryParam("serviceId", microserviceId) .addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder)); try { countDownLatch.await(); } catch (Exception e) { LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e); } return holder.value != null && schemaId.equals(holder.value.getSchemaId()); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean isSchemaExist(String microserviceId, String schemaId) { Holder<GetExistenceResponse> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema") .addQueryParam("serviceId", microserviceId) .addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder)); try { countDownLatch.await(); } catch (Exception e) { LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e); } return holder.value != null && schemaId.equals(holder.value.getSchemaId()); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public boolean isSchemaExist(String microserviceId, String schemaId) { Holder<GetExistenceResponse> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_EXISTENCE, new RequestParam().addQueryParam("type", "schema") .addQueryParam("serviceId", microserviceId) .addQueryParam("schemaId", schemaId), syncHandler(countDownLatch, GetExistenceResponse.class, holder)); try { countDownLatch.await(); } catch (Exception e) { LOGGER.error("query schema exist {}/{} fail", microserviceId, schemaId, e); } return holder.value != null && schemaId.equals(holder.value.getSchemaId()); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void empty() { Assert.assertThat(resolver.replace("prefix${}suffix", parameters), Matchers.contains("prefix${}suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void notComplete() { Assert.assertThat(resolver.replace("prefix${suffix", parameters), Matchers.contains("prefix${suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void normal() { Assert.assertThat(resolver.replace("prefix.${key}.suffix", parameters), Matchers.contains("prefix.value.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void disable() { Assert.assertThat(resolver.replace("prefix.\\${key}.suffix", parameters), Matchers.contains("prefix.${key}.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void varOfVar() { Assert.assertThat(resolver.replace("prefix.${varOfVar}.suffix", parameters), Matchers.contains("prefix.value.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void list() { Assert.assertThat(resolver.replace("prefix.${low-list}.suffix", parameters), Matchers.contains("prefix.low-1.suffix", "prefix.low-2.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void multi_list() { Assert.assertThat(resolver.replace("prefix.${low-list}.${middle-list}.${high-list}.suffix", parameters), Matchers.contains( "prefix.low-1.middle-1.high-1.suffix", "prefix.low-1.middle-1.high-2.suffix", "prefix.low-1.middle-2.high-1.suffix", "prefix.low-1.middle-2.high-2.suffix", "prefix.low-2.middle-1.high-1.suffix", "prefix.low-2.middle-1.high-2.suffix", "prefix.low-2.middle-2.high-1.suffix", "prefix.low-2.middle-2.high-2.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void nested() { Assert.assertThat(resolver.replace("prefix.${${priority}-list}.suffix", parameters), Matchers.contains("prefix.low-1.suffix", "prefix.low-2.suffix")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void mixed() { Assert.assertThat(resolver.replace("prefix.${${priority}-list}.${key}.${high-list}.suffix ${xxx}", parameters), Matchers.contains( "prefix.low-1.value.high-1.suffix ${xxx}", "prefix.low-2.value.high-1.suffix ${xxx}", "prefix.low-1.value.high-2.suffix ${xxx}", "prefix.low-2.value.high-2.suffix ${xxx}")); }
|
public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
PlaceholderResolver { public List<String> replace(String str, Map<String, Object> parameters) { List<Row> finalRows = replaceToRows(str, parameters); List<String> replaced = new ArrayList<>(); for (Row row : finalRows) { resolve(row, replaced); } for (int idx = 0; idx < replaced.size(); idx++) { String row = replaced.get(idx); replaced.set(idx, row.replace("\\$", "$")); } return replaced; } String replaceFirst(String str); String replaceFirst(String str, Map<String, Object> parameters); List<String> replace(String str, Map<String, Object> parameters); }
|
@Test public void testLong() { PriorityProperty<Long> config = priorityPropertyManager.createPriorityProperty(Long.class, -1L, -2L, keys); Assert.assertEquals(-2L, (long) config.getValue()); ArchaiusUtils.setProperty(low, 1L); Assert.assertEquals(1L, (long) config.getValue()); ArchaiusUtils.setProperty(middle, 2L); Assert.assertEquals(2L, (long) config.getValue()); ArchaiusUtils.setProperty(high, 3L); Assert.assertEquals(3L, (long) config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(3L, (long) config.getValue()); ArchaiusUtils.setProperty(middle, 2L); ArchaiusUtils.setProperty(high, null); Assert.assertEquals(2L, (long) config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(1L, (long) config.getValue()); ArchaiusUtils.setProperty(low, null); Assert.assertEquals(-2L, (long) config.getValue()); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void getAggregatedMicroservice() { String microserviceId = "msId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetServiceResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); holder.value = Json .decodeValue( "{\"service\":{\"serviceId\":\"serviceId\",\"framework\":null" + ",\"registerBy\":null,\"environment\":null,\"appId\":\"appId\",\"serviceName\":null," + "\"alias\":null,\"version\":null,\"description\":null,\"level\":null,\"schemas\":[]," + "\"paths\":[],\"status\":\"UP\",\"properties\":{},\"intance\":null}}", GetServiceResponse.class); RequestParam requestParam = requestContext.getParams(); Assert.assertEquals("global=true", requestParam.getQueryParams()); } }; Microservice aggregatedMicroservice = oClient.getAggregatedMicroservice(microserviceId); Assert.assertEquals("serviceId", aggregatedMicroservice.getServiceId()); Assert.assertEquals("appId", aggregatedMicroservice.getAppId()); }
|
@Override public Microservice getAggregatedMicroservice(String microserviceId) { return doGetMicroservice(microserviceId, true); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Microservice getAggregatedMicroservice(String microserviceId) { return doGetMicroservice(microserviceId, true); } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Microservice getAggregatedMicroservice(String microserviceId) { return doGetMicroservice(microserviceId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Microservice getAggregatedMicroservice(String microserviceId) { return doGetMicroservice(microserviceId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Microservice getAggregatedMicroservice(String microserviceId) { return doGetMicroservice(microserviceId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void onBeforeProducerProvider_metrics_endpoint_enabled_by_default() { final MetricsBootListener listener = new MetricsBootListener(); final List<ProducerMeta> producerMetas = new ArrayList<>(); final BootEvent event = new BootEvent(); final ProducerMeta producerMeta = new ProducerMeta(); final SCBEngine scbEngine = new SCBEngine() { final public ProducerProviderManager producerProviderManager = new ProducerProviderManager(this) { @Override public void addProducerMeta(String schemaId, Object instance) { producerMeta.setSchemaId(schemaId); producerMeta.setInstance(instance); producerMetas.add(producerMeta); } }; @Override public ProducerProviderManager getProducerProviderManager() { return producerProviderManager; } }; event.setScbEngine(scbEngine); listener.onBeforeProducerProvider(event); Assert.assertThat(producerMetas, Matchers.contains(producerMeta)); Assert.assertThat(producerMeta.getSchemaId(), Matchers.equalTo("metricsEndpoint")); Assert.assertThat(producerMeta.getInstance(), Matchers.instanceOf(MetricsRestPublisher.class)); }
|
@Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); }
|
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } }
|
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } }
|
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } MetricsBootstrap getMetricsBootstrap(); SlowInvocationLogger getSlowInvocationLogger(); @Override void onBeforeProducerProvider(BootEvent event); @Override void onAfterRegistry(BootEvent event); @Override void onBeforeClose(BootEvent event); }
|
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } MetricsBootstrap getMetricsBootstrap(); SlowInvocationLogger getSlowInvocationLogger(); @Override void onBeforeProducerProvider(BootEvent event); @Override void onAfterRegistry(BootEvent event); @Override void onBeforeClose(BootEvent event); }
|
@Test public void testInt() { PriorityProperty<Integer> config = priorityPropertyManager.createPriorityProperty(Integer.class, -1, -2, keys); Assert.assertEquals(-2L, (int) config.getValue()); ArchaiusUtils.setProperty(low, 1); Assert.assertEquals(1, (int) config.getValue()); ArchaiusUtils.setProperty(middle, 2); Assert.assertEquals(2, (int) config.getValue()); ArchaiusUtils.setProperty(high, 3); Assert.assertEquals(3, (int) config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(3, (int) config.getValue()); ArchaiusUtils.setProperty(middle, 2); ArchaiusUtils.setProperty(high, null); Assert.assertEquals(2, (int) config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(1, (int) config.getValue()); ArchaiusUtils.setProperty(low, null); Assert.assertEquals(-2, (int) config.getValue()); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void testString() { PriorityProperty<String> config = priorityPropertyManager.createPriorityProperty(String.class, null, "def", keys); Assert.assertEquals("def", config.getValue()); ArchaiusUtils.setProperty(low, 1); Assert.assertEquals("1", config.getValue()); ArchaiusUtils.setProperty(middle, 2); Assert.assertEquals("2", config.getValue()); ArchaiusUtils.setProperty(high, 3); Assert.assertEquals("3", config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals("3", config.getValue()); ArchaiusUtils.setProperty(middle, 2); ArchaiusUtils.setProperty(high, null); Assert.assertEquals("2", config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals("1", config.getValue()); ArchaiusUtils.setProperty(low, null); Assert.assertEquals("def", config.getValue()); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void testBoolean() { PriorityProperty<Boolean> config = priorityPropertyManager.createPriorityProperty(Boolean.class, null, false, keys); Assert.assertFalse(config.getValue()); ArchaiusUtils.setProperty(low, true); Assert.assertTrue(config.getValue()); ArchaiusUtils.setProperty(middle, false); Assert.assertFalse(config.getValue()); ArchaiusUtils.setProperty(high, true); Assert.assertTrue(config.getValue()); ArchaiusUtils.setProperty(middle, false); Assert.assertTrue(config.getValue()); ArchaiusUtils.setProperty(middle, false); ArchaiusUtils.setProperty(high, null); Assert.assertFalse(config.getValue()); ArchaiusUtils.setProperty(middle, null); Assert.assertTrue(config.getValue()); ArchaiusUtils.setProperty(low, null); Assert.assertFalse(config.getValue()); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void testDouble() { PriorityProperty<Double> config = priorityPropertyManager.createPriorityProperty(Double.class, null, -2.0, keys); Assert.assertEquals(-2, config.getValue(), 0); ArchaiusUtils.setProperty(low, 1); Assert.assertEquals(1, config.getValue(), 0); ArchaiusUtils.setProperty(middle, 2); Assert.assertEquals(2, config.getValue(), 0); ArchaiusUtils.setProperty(high, 3); Assert.assertEquals(3, config.getValue(), 0); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(3, config.getValue(), 0); ArchaiusUtils.setProperty(middle, 2); ArchaiusUtils.setProperty(high, null); Assert.assertEquals(2, config.getValue(), 0); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(1, config.getValue(), 0); ArchaiusUtils.setProperty(low, null); Assert.assertEquals(-2, config.getValue(), 0); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void testFloat() { PriorityProperty<Float> config = priorityPropertyManager.createPriorityProperty(Float.class, null, -2.0f, keys); Assert.assertEquals(-2, config.getValue(), 0); ArchaiusUtils.setProperty(low, 1); Assert.assertEquals(1, config.getValue(), 0); ArchaiusUtils.setProperty(middle, 2); Assert.assertEquals(2, config.getValue(), 0); ArchaiusUtils.setProperty(high, 3); Assert.assertEquals(3, config.getValue(), 0); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(3, config.getValue(), 0); ArchaiusUtils.setProperty(middle, 2); ArchaiusUtils.setProperty(high, null); Assert.assertEquals(2, config.getValue(), 0); ArchaiusUtils.setProperty(middle, null); Assert.assertEquals(1, config.getValue(), 0); ArchaiusUtils.setProperty(low, null); Assert.assertEquals(-2, config.getValue(), 0); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void globalRefresh() { PriorityProperty<String> property = priorityPropertyManager.createPriorityProperty(String.class, null, null, keys); Assert.assertNull(property.getValue()); ConcurrentCompositeConfiguration config = (ConcurrentCompositeConfiguration) DynamicPropertyFactory .getBackingConfigurationSource(); config.addConfiguration(new MapConfiguration(Collections.singletonMap(high, "high-value"))); Assert.assertEquals("high-value", property.getValue()); }
|
public T getValue() { return finalValue; }
|
PriorityProperty { public T getValue() { return finalValue; } }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
PriorityProperty { public T getValue() { return finalValue; } @SuppressWarnings("unchecked") PriorityProperty(Type type, T invalidValue, T defaultValue, String... priorityKeys); String[] getPriorityKeys(); T getDefaultValue(); DynamicProperty[] getProperties(); T getValue(); void setCallback(BiConsumer<T, Object> callback, Object target); }
|
@Test public void testAddConfig() { Map<String, Object> config = new HashMap<>(); config.put("service_description.name", "service_name_test"); ConfigUtil.setConfigs(config); ConfigUtil.addConfig("service_description.version", "1.0.2"); ConfigUtil.addConfig("cse.test.enabled", true); ConfigUtil.addConfig("cse.test.num", 10); AbstractConfiguration configuration = ConfigUtil.createDynamicConfig(); Assert.assertEquals(configuration.getString("service_description.name"), "service_name_test"); Assert.assertTrue(configuration.getBoolean("cse.test.enabled")); Assert.assertEquals(configuration.getInt("cse.test.num"), 10); }
|
public static void addConfig(String key, Object value) { localConfig.put(key, value); }
|
ConfigUtil { public static void addConfig(String key, Object value) { localConfig.put(key, value); } }
|
ConfigUtil { public static void addConfig(String key, Object value) { localConfig.put(key, value); } private ConfigUtil(); }
|
ConfigUtil { public static void addConfig(String key, Object value) { localConfig.put(key, value); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static void addConfig(String key, Object value) { localConfig.put(key, value); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void testCreateDynamicConfigHasConfigCenter() { AbstractConfiguration dynamicConfig = ConfigUtil.createDynamicConfig(); Assert.assertEquals(DynamicWatchedConfiguration.class, ((ConcurrentCompositeConfiguration) dynamicConfig).getConfiguration(0).getClass()); }
|
public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; }
|
ConfigUtil { public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; } }
|
ConfigUtil { public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; } private ConfigUtil(); }
|
ConfigUtil { public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void testGetPropertyInvalidConfig() { Assert.assertNull(ConfigUtil.getProperty(null, "any")); Assert.assertNull(ConfigUtil.getProperty(new Object(), "any")); }
|
public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void duplicateServiceCombConfigToCseListValue() { List<String> list = Arrays.asList("a", "b"); AbstractConfiguration config = new DynamicConfiguration(); config.addProperty("cse.list", list); Deencapsulation.invoke(ConfigUtil.class, "duplicateCseConfigToServicecomb", config); Object result = config.getProperty("servicecomb.list"); assertThat(result, instanceOf(List.class)); assertThat(result, equalTo(list)); }
|
public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void getAggregatedSchema() { String microserviceId = "msId"; String schemaId = "schemaId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetSchemaResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); holder.value = Json .decodeValue( "{ \"schema\": \"schema\", \"schemaId\":\"metricsEndpoint\",\"summary\":\"c1188d709631a9038874f9efc6eb894f\"}", GetSchemaResponse.class); RequestParam requestParam = requestContext.getParams(); Assert.assertEquals("global=true", requestParam.getQueryParams()); } }; LoadingCache<String, Map<String, String>> oldCache = Deencapsulation.getField(oClient, "schemaCache"); LoadingCache<String, Map<String, String>> newCache = CacheBuilder.newBuilder() .expireAfterAccess(60, TimeUnit.SECONDS).build(new CacheLoader<String, Map<String, String>>() { public Map<String, String> load(String key) { Map<String, String> schemas = new HashMap<>(); return schemas; } }); Deencapsulation.setField(oClient, "schemaCache", newCache); String str = oClient.getAggregatedSchema(microserviceId, schemaId); Assert.assertEquals("schema", str); Deencapsulation.setField(oClient, "schemaCache", oldCache); }
|
@Override public String getAggregatedSchema(String microserviceId, String schemaId) { return doGetSchema(microserviceId, schemaId, true); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public String getAggregatedSchema(String microserviceId, String schemaId) { return doGetSchema(microserviceId, schemaId, true); } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public String getAggregatedSchema(String microserviceId, String schemaId) { return doGetSchema(microserviceId, schemaId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public String getAggregatedSchema(String microserviceId, String schemaId) { return doGetSchema(microserviceId, schemaId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public String getAggregatedSchema(String microserviceId, String schemaId) { return doGetSchema(microserviceId, schemaId, true); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void testConvertEnvVariable() { String someProperty = "cse_service_registry_address"; AbstractConfiguration config = new DynamicConfiguration(); config.addProperty(someProperty, "testing"); AbstractConfiguration result = ConfigUtil.convertEnvVariable(config); assertThat(result.getString("cse.service.registry.address"), equalTo("testing")); assertThat(result.getString("cse_service_registry_address"), equalTo("testing")); }
|
public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; }
|
ConfigUtil { public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; } }
|
ConfigUtil { public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; } private ConfigUtil(); }
|
ConfigUtil { public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void destroyConfigCenterConfigurationSource() { AtomicInteger count = new AtomicInteger(); ConfigCenterConfigurationSource source = new MockUp<ConfigCenterConfigurationSource>() { @Mock void destroy() { count.incrementAndGet(); } }.getMockInstance(); new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class); result = Arrays.asList(source, source); } }; ConfigUtil.destroyConfigCenterConfigurationSource(); Assert.assertEquals(2, count.get()); }
|
public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); }
|
ConfigUtil { public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); } }
|
ConfigUtil { public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); } private ConfigUtil(); }
|
ConfigUtil { public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
ConfigUtil { public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }
|
@Test public void loadFromSPI(@Mocked DiscoveryFilter f1, @Mocked DiscoveryFilter f2) { Class<? extends DiscoveryFilter> cls = DiscoveryFilter.class; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(cls); result = Arrays.asList(f1, f2); } }; discoveryTree.loadFromSPI(cls); Assert.assertThat(filters, Matchers.contains(f1, f2)); }
|
public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); }
|
DiscoveryTree { public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); } }
|
DiscoveryTree { public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); } }
|
DiscoveryTree { public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void sort(@Mocked DiscoveryFilter f1, @Mocked DiscoveryFilter f2, @Mocked DiscoveryFilter f3) { new Expectations() { { f1.getOrder(); result = -1; f1.enabled(); result = true; f2.getOrder(); result = 0; f2.enabled(); result = true; f3.getOrder(); result = 0; f3.enabled(); result = false; } }; discoveryTree.addFilter(f3); discoveryTree.addFilter(f2); discoveryTree.addFilter(f1); discoveryTree.sort(); Assert.assertThat(filters, Matchers.contains(f1, f2)); }
|
public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } }
|
DiscoveryTree { public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } } }
|
DiscoveryTree { public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } } }
|
DiscoveryTree { public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isMatch_existingNull() { Assert.assertFalse(discoveryTree.isMatch(null, null)); }
|
protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isMatch_yes() { parent.cacheVersion(1); Assert.assertTrue(discoveryTree.isMatch(new DiscoveryTreeNode().cacheVersion(1), parent)); }
|
protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isMatch_no() { parent.cacheVersion(0); Assert.assertFalse(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(1), parent)); }
|
protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isExpired_existingNull() { Assert.assertTrue(discoveryTree.isExpired(null, null)); }
|
protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isExpired_yes() { parent.cacheVersion(1); Assert.assertTrue(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(0), parent)); }
|
protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void isExpired_no() { parent.cacheVersion(0); Assert.assertFalse(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(0), parent)); }
|
protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void getSchemas() { String microserviceId = "msId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetSchemasResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); GetSchemasResponse schemasResp = Json.decodeValue( "{\"schema\":[{\"schemaId\":\"metricsEndpoint\",\"summary\":\"c1188d709631a9038874f9efc6eb894f\"},{\"schemaId\":\"comment\",\"summary\":\"bfa81d625cfbd3a57f38745323e16824\"}," + "{\"schemaId\":\"healthEndpoint\",\"summary\":\"96a0aaaaa454cfa0c716e70c0017fe27\"}]}", GetSchemasResponse.class); holder.statusCode = 200; holder.value = schemasResp; } }; Holder<List<GetSchemaResponse>> schemasHolder = oClient.getSchemas(microserviceId); List<GetSchemaResponse> schemaResponses = schemasHolder.getValue(); Assert.assertEquals(200, schemasHolder.getStatusCode()); Assert.assertEquals(3, schemaResponses.size()); Assert.assertEquals("bfa81d625cfbd3a57f38745323e16824", schemaResponses.get(1).getSummary()); }
|
@Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void easyDiscovery(@Mocked InstanceCacheManager instanceCacheManager) { new Expectations(DiscoveryManager.class) { { DiscoveryManager.INSTANCE.getInstanceCacheManager(); result = instanceCacheManager; instanceCacheManager.getOrCreateVersionedCache(anyString, anyString, anyString); result = parent; } }; result = discoveryTree.discovery(context, null, null, null); Assert.assertEquals(parent.name(), result.name()); Assert.assertEquals(parent.cacheVersion(), result.cacheVersion()); }
|
public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void avoidConcurrentProblem() { Deencapsulation.setField(discoveryTree, "root", parent.cacheVersion(1)); Assert.assertTrue(parent.children().isEmpty()); discoveryTree.discovery(context, new VersionedCache().cacheVersion(0).name("input")); Assert.assertTrue(parent.children().isEmpty()); }
|
public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void getOrCreateRoot_match() { Deencapsulation.setField(discoveryTree, "root", parent); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(parent); Assert.assertSame(parent, root); }
|
protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void getOrCreateRoot_expired() { Deencapsulation.setField(discoveryTree, "root", parent); VersionedCache inputCache = new VersionedCache().cacheVersion(parent.cacheVersion() + 1); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(inputCache); Assert.assertEquals(inputCache.cacheVersion(), root.cacheVersion()); Assert.assertSame(Deencapsulation.getField(discoveryTree, "root"), root); }
|
protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void getOrCreateRoot_tempRoot() { Deencapsulation.setField(discoveryTree, "root", parent); VersionedCache inputCache = new VersionedCache().cacheVersion(parent.cacheVersion() - 1); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(inputCache); Assert.assertEquals(inputCache.cacheVersion(), root.cacheVersion()); Assert.assertNotSame(Deencapsulation.getField(discoveryTree, "root"), root); }
|
protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }
|
@Test public void childrenInited() { Assert.assertFalse(node.childrenInited()); node.childrenInited(true); Assert.assertTrue(node.childrenInited()); }
|
public boolean childrenInited() { return childrenInited; }
|
DiscoveryTreeNode extends VersionedCache { public boolean childrenInited() { return childrenInited; } }
|
DiscoveryTreeNode extends VersionedCache { public boolean childrenInited() { return childrenInited; } }
|
DiscoveryTreeNode extends VersionedCache { public boolean childrenInited() { return childrenInited; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { public boolean childrenInited() { return childrenInited; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
@Test public void level() { node.level(1); Assert.assertEquals(1, node.level()); }
|
public int level() { return level; }
|
DiscoveryTreeNode extends VersionedCache { public int level() { return level; } }
|
DiscoveryTreeNode extends VersionedCache { public int level() { return level; } }
|
DiscoveryTreeNode extends VersionedCache { public int level() { return level; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { public int level() { return level; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
@Test public void attribute() { node.attribute("k1", "v1"); Assert.assertEquals("v1", node.attribute("k1")); }
|
@SuppressWarnings("unchecked") public <T> T attribute(String key) { return (T) attributes.get(key); }
|
DiscoveryTreeNode extends VersionedCache { @SuppressWarnings("unchecked") public <T> T attribute(String key) { return (T) attributes.get(key); } }
|
DiscoveryTreeNode extends VersionedCache { @SuppressWarnings("unchecked") public <T> T attribute(String key) { return (T) attributes.get(key); } }
|
DiscoveryTreeNode extends VersionedCache { @SuppressWarnings("unchecked") public <T> T attribute(String key) { return (T) attributes.get(key); } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { @SuppressWarnings("unchecked") public <T> T attribute(String key) { return (T) attributes.get(key); } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
@Test public void children() { Map<String, DiscoveryTreeNode> children = new HashMap<>(); node.children(children); Assert.assertSame(children, node.children()); }
|
public Map<String, DiscoveryTreeNode> children() { return children; }
|
DiscoveryTreeNode extends VersionedCache { public Map<String, DiscoveryTreeNode> children() { return children; } }
|
DiscoveryTreeNode extends VersionedCache { public Map<String, DiscoveryTreeNode> children() { return children; } }
|
DiscoveryTreeNode extends VersionedCache { public Map<String, DiscoveryTreeNode> children() { return children; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { public Map<String, DiscoveryTreeNode> children() { return children; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
@Test public void child() { DiscoveryTreeNode child = new DiscoveryTreeNode().name("child"); node.child(child.name(), child); Assert.assertSame(child, node.child(child.name())); }
|
public DiscoveryTreeNode child(String childName) { return children.get(childName); }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode child(String childName) { return children.get(childName); } }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode child(String childName) { return children.get(childName); } }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode child(String childName) { return children.get(childName); } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode child(String childName) { return children.get(childName); } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
@Test public void getSchemasForNew() { String microserviceId = "msId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetSchemasResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); GetSchemasResponse schemasResp = Json.decodeValue( "{\"schemas\":[{\"schemaId\":\"metricsEndpoint\",\"summary\":\"c1188d709631a9038874f9efc6eb894f\"},{\"schemaId\":\"comment\",\"summary\":\"bfa81d625cfbd3a57f38745323e16824\"}," + "{\"schemaId\":\"healthEndpoint\",\"summary\":\"96a0aaaaa454cfa0c716e70c0017fe27\"}]}", GetSchemasResponse.class); holder.statusCode = 200; holder.value = schemasResp; } }; Holder<List<GetSchemaResponse>> schemasHolder = oClient.getSchemas(microserviceId); List<GetSchemaResponse> schemas = schemasHolder.getValue(); Assert.assertEquals(200, schemasHolder.getStatusCode()); Assert.assertEquals(3, schemas.size()); Assert.assertEquals("bfa81d625cfbd3a57f38745323e16824", schemas.get(1).getSummary()); }
|
@Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback,
AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName,
String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName,
String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId,
Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId,
MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
|
@Test public void fromCache() { Object data = new Object(); VersionedCache other = new VersionedCache().cacheVersion(1).name("cache").data(data); node.fromCache(other); Assert.assertEquals(1, node.cacheVersion()); Assert.assertEquals("cache", node.name()); Assert.assertSame(data, node.data()); }
|
public DiscoveryTreeNode fromCache(VersionedCache other) { this.cacheVersion = other.cacheVersion(); this.name = other.name(); this.data(other.data()); return this; }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode fromCache(VersionedCache other) { this.cacheVersion = other.cacheVersion(); this.name = other.name(); this.data(other.data()); return this; } }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode fromCache(VersionedCache other) { this.cacheVersion = other.cacheVersion(); this.name = other.name(); this.data(other.data()); return this; } }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode fromCache(VersionedCache other) { this.cacheVersion = other.cacheVersion(); this.name = other.name(); this.data(other.data()); return this; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
DiscoveryTreeNode extends VersionedCache { public DiscoveryTreeNode fromCache(VersionedCache other) { this.cacheVersion = other.cacheVersion(); this.name = other.name(); this.data(other.data()); return this; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.