hexsha
stringlengths
40
40
repo
stringlengths
4
114
path
stringlengths
6
369
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
123
original_docstring
stringlengths
8
49.2k
docstring
stringlengths
5
8.63k
docstring_tokens
sequence
code
stringlengths
25
988k
code_tokens
sequence
short_docstring
stringlengths
0
6.18k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
846796937f88033996d0f3e3f319dbb400d0bc7f
deduper/raml-java-tools
raml-to-pojo/src/main/java/org/raml/ramltopojo/Scalars.java
[ "Apache-2.0" ]
Java
Scalars
/** * Created. There, you have it. */
Created. There, you have it.
[ "Created", ".", "There", "you", "have", "it", "." ]
public class Scalars { public static TypeName classToTypeName(Class scalar) { if (scalar.isPrimitive()) { switch (scalar.getSimpleName()) { case "int": return TypeName.INT; case "boolean": return TypeName.BOOLEAN; case "double": return TypeName.DOUBLE; case "float": return TypeName.FLOAT; case "byte": return TypeName.BYTE; case "char": return TypeName.CHAR; case "short": return TypeName.SHORT; case "long": return TypeName.LONG; case "void": return TypeName.VOID; // ? default: throw new GenerationException("can't handle type: " + scalar); } } else { return ClassName.get(scalar); } } }
[ "public", "class", "Scalars", "{", "public", "static", "TypeName", "classToTypeName", "(", "Class", "scalar", ")", "{", "if", "(", "scalar", ".", "isPrimitive", "(", ")", ")", "{", "switch", "(", "scalar", ".", "getSimpleName", "(", ")", ")", "{", "case", "\"", "int", "\"", ":", "return", "TypeName", ".", "INT", ";", "case", "\"", "boolean", "\"", ":", "return", "TypeName", ".", "BOOLEAN", ";", "case", "\"", "double", "\"", ":", "return", "TypeName", ".", "DOUBLE", ";", "case", "\"", "float", "\"", ":", "return", "TypeName", ".", "FLOAT", ";", "case", "\"", "byte", "\"", ":", "return", "TypeName", ".", "BYTE", ";", "case", "\"", "char", "\"", ":", "return", "TypeName", ".", "CHAR", ";", "case", "\"", "short", "\"", ":", "return", "TypeName", ".", "SHORT", ";", "case", "\"", "long", "\"", ":", "return", "TypeName", ".", "LONG", ";", "case", "\"", "void", "\"", ":", "return", "TypeName", ".", "VOID", ";", "default", ":", "throw", "new", "GenerationException", "(", "\"", "can't handle type: ", "\"", "+", "scalar", ")", ";", "}", "}", "else", "{", "return", "ClassName", ".", "get", "(", "scalar", ")", ";", "}", "}", "}" ]
Created.
[ "Created", "." ]
[ "// ?" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
846898fd7e65186049c53f8961fe7761bd3d6257
MessiMercy/MessiCrawler
src/main/java/com/downloader/certificate/SSLTrustManager.java
[ "Apache-2.0" ]
Java
SSLTrustManager
/** * Created by Administrator on 2016/11/7. */
Created by Administrator on 2016/11/7.
[ "Created", "by", "Administrator", "on", "2016", "/", "11", "/", "7", "." ]
public class SSLTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager, HostnameVerifier { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } @Override public boolean verify(String urlHostName, SSLSession session) { //允许所有主机 return true; } /** * 客户端使用 */ public static HttpURLConnection connectTrustAllServer(String strUrl) throws Exception { return connectTrustAllServer(strUrl, null); } /** * 客户端使用 * * @param strUrl 要访问的地址 * @param proxy 需要经过的代理 * @return * @throws Exception */ public static HttpURLConnection connectTrustAllServer(String strUrl, Proxy proxy) throws Exception { javax.net.ssl.TrustManager[] trustCertsmanager = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLTrustManager(); trustCertsmanager[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext .getInstance("TLS"); sc.init(null, trustCertsmanager, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc .getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((HostnameVerifier) tm); URL url = new URL(strUrl); HttpURLConnection urlConn = null; if (proxy == null) { urlConn = (HttpURLConnection) url.openConnection(); } else { urlConn = (HttpURLConnection) url.openConnection(proxy); } urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return urlConn; } /** * 用于双向认证,客户端使用 * * @param strUrl * @param proxy * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static HttpURLConnection connectProxyTrustCA(String strUrl, Proxy proxy) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslsession) { return true; } }); String clientKeyStoreFile = "D:/JDK8Home/tianwt/sslClientKeys"; String clientKeyStorePwd = "123456"; String catServerKeyPwd = "123456"; String serverTrustKeyStoreFile = "D:/JDK8Home/tianwt/sslClientTrust"; String serverTrustKeyStorePwd = "123456"; KeyStore serverKeyStore = KeyStore.getInstance("JKS"); serverKeyStore.load(new FileInputStream(clientKeyStoreFile), clientKeyStorePwd.toCharArray()); KeyStore serverTrustKeyStore = KeyStore.getInstance("JKS"); serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(serverKeyStore, catServerKeyPwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(serverTrustKeyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL(strUrl); HttpURLConnection httpURLConnection = null; if (proxy == null) { httpURLConnection = (HttpURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(proxy); } httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return httpURLConnection; } /** * 用于单向认证,客户端使用 * <p> * server侧只需要自己的keystore文件,不需要truststore文件 * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。 * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false) * * @param strUrl * @param proxy * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static HttpURLConnection connectProxyTrustCA2(String strUrl, Proxy proxy) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslsession) { return true; } }); String serverTrustKeyStoreFile = "D:/JDK8Home/tianwt/sslClientTrust"; String serverTrustKeyStorePwd = "123456"; KeyStore serverTrustKeyStore = KeyStore.getInstance("JKS"); serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(serverTrustKeyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL url = new URL(strUrl); HttpURLConnection httpURLConnection = null; if (proxy == null) { httpURLConnection = (HttpURLConnection) url.openConnection(); } else { httpURLConnection = (HttpURLConnection) url.openConnection(proxy); } httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"); return httpURLConnection; } /** * 用于双向认证 * * @param socketClient 是否产生socket * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public SSLSocket createTlsConnect(Socket socketClient) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { String protocol = "TLS"; String serverKey = "D:/JDK8Home/tianwt/sslServerKeys"; String serverTrust = "D:/JDK8Home/tianwt/sslServerTrust"; String serverKeyPwd = "123456"; //私钥密码 String serverTrustPwd = "123456"; //信任证书密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKey), serverKeyPwd.toCharArray()); KeyStore tks = KeyStore.getInstance("JKS"); tks.load(new FileInputStream(serverTrust), serverTrustPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(tks); SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(km.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); //第一项是用来做服务器验证的 SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket clientSSLSocket = (SSLSocket) sslSocketFactory.createSocket(socketClient, socketClient.getInetAddress().getHostAddress(), socketClient.getPort(), true); clientSSLSocket.setNeedClientAuth(false); clientSSLSocket.setUseClientMode(false); return clientSSLSocket; } /** * 用于单向认证 * server侧只需要自己的keystore文件,不需要truststore文件 * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。 * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false) * * @param socketClient * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public static SSLSocket createTlsConnect2(Socket socketClient) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException { String protocol = "TLS"; String serverKey = "D:/JDK8Home/tianwt/sslServerKeys"; String serverKeyPwd = "123456"; //私钥密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKey), serverKeyPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(km.getKeyManagers(), null, new SecureRandom()); //第一项是用来做服务器验证的 SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket clientSSLSocket = (SSLSocket) sslSocketFactory.createSocket(socketClient, socketClient.getInetAddress().getHostAddress(), socketClient.getPort(), true); clientSSLSocket.setNeedClientAuth(false); clientSSLSocket.setUseClientMode(false); return clientSSLSocket; } /** * 将普通的socket转为sslsocket,客户端和服务端均可使用 * <p> * 服务端使用的时候是把普通的socket转为sslsocket,并且作为服务器套接字(注意:指的不是ServerSocket,当然ServerSocket的本质也是普通socket) * * @param remoteHost * @param isClient * @return */ public static SSLSocket getTlsTrustAllSocket(Socket remoteHost, boolean isClient) { SSLSocket remoteSSLSocket = null; SSLContext context = SSLTrustManager.getTrustAllSSLContext(isClient); try { remoteSSLSocket = (SSLSocket) context.getSocketFactory().createSocket(remoteHost, remoteHost.getInetAddress().getHostName(), remoteHost.getPort(), true); remoteSSLSocket.setTcpNoDelay(true); remoteSSLSocket.setSoTimeout(5000); remoteSSLSocket.setNeedClientAuth(false); //这里设置为true时会强制握手 remoteSSLSocket.setUseClientMode(isClient); //注意服务器和客户的角色选择 } catch (IOException e) { e.printStackTrace(); } return remoteSSLSocket; } /** * 用于客户端,通过所有证书验证 * * @param isClient 是否生成客户端SSLContext,否则生成服务端SSLContext * @return */ public static SSLContext getTrustAllSSLContext(boolean isClient) { String protocol = "TLS"; javax.net.ssl.SSLContext sc = null; try { javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new SSLTrustManager(); trustAllCerts[0] = tm; sc = javax.net.ssl.SSLContext .getInstance(protocol); if (isClient) { sc.init(null, trustAllCerts, null); //作为客户端使用 } else { String serverKeyPath = "D:/JDK8Home/tianwt/sslServerKeys"; String serverKeyPwd = "123456"; //私钥密码 String serverKeyStorePwd = "123456"; // keystore存储密码 KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(serverKeyPath), serverKeyPwd.toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keyStore, serverKeyStorePwd.toCharArray()); KeyManager[] keyManagers = km.getKeyManagers(); keyManagers = Arrays.copyOf(keyManagers, keyManagers.length + 1); sc.init(keyManagers, null, new SecureRandom()); } } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sc; } }
[ "public", "class", "SSLTrustManager", "implements", "javax", ".", "net", ".", "ssl", ".", "TrustManager", ",", "javax", ".", "net", ".", "ssl", ".", "X509TrustManager", ",", "HostnameVerifier", "{", "public", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "getAcceptedIssuers", "(", ")", "{", "return", "new", "X509Certificate", "[", "]", "{", "}", ";", "}", "public", "boolean", "isServerTrusted", "(", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "certs", ")", "{", "return", "true", ";", "}", "public", "boolean", "isClientTrusted", "(", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "certs", ")", "{", "return", "true", ";", "}", "public", "void", "checkServerTrusted", "(", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "certs", ",", "String", "authType", ")", "throws", "java", ".", "security", ".", "cert", ".", "CertificateException", "{", "return", ";", "}", "public", "void", "checkClientTrusted", "(", "java", ".", "security", ".", "cert", ".", "X509Certificate", "[", "]", "certs", ",", "String", "authType", ")", "throws", "java", ".", "security", ".", "cert", ".", "CertificateException", "{", "return", ";", "}", "@", "Override", "public", "boolean", "verify", "(", "String", "urlHostName", ",", "SSLSession", "session", ")", "{", "return", "true", ";", "}", "/**\n * 客户端使用\n */", "public", "static", "HttpURLConnection", "connectTrustAllServer", "(", "String", "strUrl", ")", "throws", "Exception", "{", "return", "connectTrustAllServer", "(", "strUrl", ",", "null", ")", ";", "}", "/**\n * 客户端使用\n *\n * @param strUrl 要访问的地址\n * @param proxy 需要经过的代理\n * @return\n * @throws Exception\n */", "public", "static", "HttpURLConnection", "connectTrustAllServer", "(", "String", "strUrl", ",", "Proxy", "proxy", ")", "throws", "Exception", "{", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "[", "]", "trustCertsmanager", "=", "new", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "[", "1", "]", ";", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "tm", "=", "new", "SSLTrustManager", "(", ")", ";", "trustCertsmanager", "[", "0", "]", "=", "tm", ";", "javax", ".", "net", ".", "ssl", ".", "SSLContext", "sc", "=", "javax", ".", "net", ".", "ssl", ".", "SSLContext", ".", "getInstance", "(", "\"", "TLS", "\"", ")", ";", "sc", ".", "init", "(", "null", ",", "trustCertsmanager", ",", "null", ")", ";", "javax", ".", "net", ".", "ssl", ".", "HttpsURLConnection", ".", "setDefaultSSLSocketFactory", "(", "sc", ".", "getSocketFactory", "(", ")", ")", ";", "HttpsURLConnection", ".", "setDefaultHostnameVerifier", "(", "(", "HostnameVerifier", ")", "tm", ")", ";", "URL", "url", "=", "new", "URL", "(", "strUrl", ")", ";", "HttpURLConnection", "urlConn", "=", "null", ";", "if", "(", "proxy", "==", "null", ")", "{", "urlConn", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "}", "else", "{", "urlConn", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", "proxy", ")", ";", "}", "urlConn", ".", "setRequestProperty", "(", "\"", "User-Agent", "\"", ",", "\"", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36", "\"", ")", ";", "return", "urlConn", ";", "}", "/**\n * 用于双向认证,客户端使用\n *\n * @param strUrl\n * @param proxy\n * @return\n * @throws KeyStoreException\n * @throws NoSuchAlgorithmException\n * @throws CertificateException\n * @throws FileNotFoundException\n * @throws IOException\n * @throws UnrecoverableKeyException\n * @throws KeyManagementException\n */", "public", "static", "HttpURLConnection", "connectProxyTrustCA", "(", "String", "strUrl", ",", "Proxy", "proxy", ")", "throws", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", ",", "FileNotFoundException", ",", "IOException", ",", "UnrecoverableKeyException", ",", "KeyManagementException", "{", "HttpsURLConnection", ".", "setDefaultHostnameVerifier", "(", "new", "HostnameVerifier", "(", ")", "{", "@", "Override", "public", "boolean", "verify", "(", "String", "s", ",", "SSLSession", "sslsession", ")", "{", "return", "true", ";", "}", "}", ")", ";", "String", "clientKeyStoreFile", "=", "\"", "D:/JDK8Home/tianwt/sslClientKeys", "\"", ";", "String", "clientKeyStorePwd", "=", "\"", "123456", "\"", ";", "String", "catServerKeyPwd", "=", "\"", "123456", "\"", ";", "String", "serverTrustKeyStoreFile", "=", "\"", "D:/JDK8Home/tianwt/sslClientTrust", "\"", ";", "String", "serverTrustKeyStorePwd", "=", "\"", "123456", "\"", ";", "KeyStore", "serverKeyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "serverKeyStore", ".", "load", "(", "new", "FileInputStream", "(", "clientKeyStoreFile", ")", ",", "clientKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "KeyStore", "serverTrustKeyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "serverTrustKeyStore", ".", "load", "(", "new", "FileInputStream", "(", "serverTrustKeyStoreFile", ")", ",", "serverTrustKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "KeyManagerFactory", "kmf", "=", "KeyManagerFactory", ".", "getInstance", "(", "KeyManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "kmf", ".", "init", "(", "serverKeyStore", ",", "catServerKeyPwd", ".", "toCharArray", "(", ")", ")", ";", "TrustManagerFactory", "tmf", "=", "TrustManagerFactory", ".", "getInstance", "(", "TrustManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "tmf", ".", "init", "(", "serverTrustKeyStore", ")", ";", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "\"", "TLS", "\"", ")", ";", "sslContext", ".", "init", "(", "kmf", ".", "getKeyManagers", "(", ")", ",", "tmf", ".", "getTrustManagers", "(", ")", ",", "new", "SecureRandom", "(", ")", ")", ";", "HttpsURLConnection", ".", "setDefaultSSLSocketFactory", "(", "sslContext", ".", "getSocketFactory", "(", ")", ")", ";", "URL", "url", "=", "new", "URL", "(", "strUrl", ")", ";", "HttpURLConnection", "httpURLConnection", "=", "null", ";", "if", "(", "proxy", "==", "null", ")", "{", "httpURLConnection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "}", "else", "{", "httpURLConnection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", "proxy", ")", ";", "}", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "User-Agent", "\"", ",", "\"", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36", "\"", ")", ";", "return", "httpURLConnection", ";", "}", "/**\n * 用于单向认证,客户端使用\n * <p>\n * server侧只需要自己的keystore文件,不需要truststore文件\n * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。\n * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false)\n *\n * @param strUrl\n * @param proxy\n * @return\n * @throws KeyStoreException\n * @throws NoSuchAlgorithmException\n * @throws CertificateException\n * @throws FileNotFoundException\n * @throws IOException\n * @throws UnrecoverableKeyException\n * @throws KeyManagementException\n */", "public", "static", "HttpURLConnection", "connectProxyTrustCA2", "(", "String", "strUrl", ",", "Proxy", "proxy", ")", "throws", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", ",", "FileNotFoundException", ",", "IOException", ",", "UnrecoverableKeyException", ",", "KeyManagementException", "{", "HttpsURLConnection", ".", "setDefaultHostnameVerifier", "(", "new", "HostnameVerifier", "(", ")", "{", "@", "Override", "public", "boolean", "verify", "(", "String", "s", ",", "SSLSession", "sslsession", ")", "{", "return", "true", ";", "}", "}", ")", ";", "String", "serverTrustKeyStoreFile", "=", "\"", "D:/JDK8Home/tianwt/sslClientTrust", "\"", ";", "String", "serverTrustKeyStorePwd", "=", "\"", "123456", "\"", ";", "KeyStore", "serverTrustKeyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "serverTrustKeyStore", ".", "load", "(", "new", "FileInputStream", "(", "serverTrustKeyStoreFile", ")", ",", "serverTrustKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "TrustManagerFactory", "tmf", "=", "TrustManagerFactory", ".", "getInstance", "(", "TrustManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "tmf", ".", "init", "(", "serverTrustKeyStore", ")", ";", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "\"", "TLS", "\"", ")", ";", "sslContext", ".", "init", "(", "null", ",", "tmf", ".", "getTrustManagers", "(", ")", ",", "null", ")", ";", "HttpsURLConnection", ".", "setDefaultSSLSocketFactory", "(", "sslContext", ".", "getSocketFactory", "(", ")", ")", ";", "URL", "url", "=", "new", "URL", "(", "strUrl", ")", ";", "HttpURLConnection", "httpURLConnection", "=", "null", ";", "if", "(", "proxy", "==", "null", ")", "{", "httpURLConnection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "}", "else", "{", "httpURLConnection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", "proxy", ")", ";", "}", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "User-Agent", "\"", ",", "\"", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36", "\"", ")", ";", "return", "httpURLConnection", ";", "}", "/**\n * 用于双向认证\n *\n * @param socketClient 是否产生socket\n * @return\n * @throws KeyStoreException\n * @throws NoSuchAlgorithmException\n * @throws CertificateException\n * @throws FileNotFoundException\n * @throws IOException\n * @throws UnrecoverableKeyException\n * @throws KeyManagementException\n */", "public", "SSLSocket", "createTlsConnect", "(", "Socket", "socketClient", ")", "throws", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", ",", "FileNotFoundException", ",", "IOException", ",", "UnrecoverableKeyException", ",", "KeyManagementException", "{", "String", "protocol", "=", "\"", "TLS", "\"", ";", "String", "serverKey", "=", "\"", "D:/JDK8Home/tianwt/sslServerKeys", "\"", ";", "String", "serverTrust", "=", "\"", "D:/JDK8Home/tianwt/sslServerTrust", "\"", ";", "String", "serverKeyPwd", "=", "\"", "123456", "\"", ";", "String", "serverTrustPwd", "=", "\"", "123456", "\"", ";", "String", "serverKeyStorePwd", "=", "\"", "123456", "\"", ";", "KeyStore", "keyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "keyStore", ".", "load", "(", "new", "FileInputStream", "(", "serverKey", ")", ",", "serverKeyPwd", ".", "toCharArray", "(", ")", ")", ";", "KeyStore", "tks", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "tks", ".", "load", "(", "new", "FileInputStream", "(", "serverTrust", ")", ",", "serverTrustPwd", ".", "toCharArray", "(", ")", ")", ";", "KeyManagerFactory", "km", "=", "KeyManagerFactory", ".", "getInstance", "(", "KeyManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "km", ".", "init", "(", "keyStore", ",", "serverKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "TrustManagerFactory", "tmf", "=", "TrustManagerFactory", ".", "getInstance", "(", "TrustManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "tmf", ".", "init", "(", "tks", ")", ";", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "protocol", ")", ";", "sslContext", ".", "init", "(", "km", ".", "getKeyManagers", "(", ")", ",", "tmf", ".", "getTrustManagers", "(", ")", ",", "new", "SecureRandom", "(", ")", ")", ";", "SSLSocketFactory", "sslSocketFactory", "=", "sslContext", ".", "getSocketFactory", "(", ")", ";", "SSLSocket", "clientSSLSocket", "=", "(", "SSLSocket", ")", "sslSocketFactory", ".", "createSocket", "(", "socketClient", ",", "socketClient", ".", "getInetAddress", "(", ")", ".", "getHostAddress", "(", ")", ",", "socketClient", ".", "getPort", "(", ")", ",", "true", ")", ";", "clientSSLSocket", ".", "setNeedClientAuth", "(", "false", ")", ";", "clientSSLSocket", ".", "setUseClientMode", "(", "false", ")", ";", "return", "clientSSLSocket", ";", "}", "/**\n * 用于单向认证\n * server侧只需要自己的keystore文件,不需要truststore文件\n * client侧不需要自己的keystore文件,只需要truststore文件(其中包含server的公钥)。\n * 此外server侧需要在创建SSLServerSocket之后设定不需要客户端证书:setNeedClientAuth(false)\n *\n * @param socketClient\n * @return\n * @throws KeyStoreException\n * @throws NoSuchAlgorithmException\n * @throws CertificateException\n * @throws FileNotFoundException\n * @throws IOException\n * @throws UnrecoverableKeyException\n * @throws KeyManagementException\n */", "public", "static", "SSLSocket", "createTlsConnect2", "(", "Socket", "socketClient", ")", "throws", "KeyStoreException", ",", "NoSuchAlgorithmException", ",", "CertificateException", ",", "FileNotFoundException", ",", "IOException", ",", "UnrecoverableKeyException", ",", "KeyManagementException", "{", "String", "protocol", "=", "\"", "TLS", "\"", ";", "String", "serverKey", "=", "\"", "D:/JDK8Home/tianwt/sslServerKeys", "\"", ";", "String", "serverKeyPwd", "=", "\"", "123456", "\"", ";", "String", "serverKeyStorePwd", "=", "\"", "123456", "\"", ";", "KeyStore", "keyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "keyStore", ".", "load", "(", "new", "FileInputStream", "(", "serverKey", ")", ",", "serverKeyPwd", ".", "toCharArray", "(", ")", ")", ";", "KeyManagerFactory", "km", "=", "KeyManagerFactory", ".", "getInstance", "(", "KeyManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "km", ".", "init", "(", "keyStore", ",", "serverKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "protocol", ")", ";", "sslContext", ".", "init", "(", "km", ".", "getKeyManagers", "(", ")", ",", "null", ",", "new", "SecureRandom", "(", ")", ")", ";", "SSLSocketFactory", "sslSocketFactory", "=", "sslContext", ".", "getSocketFactory", "(", ")", ";", "SSLSocket", "clientSSLSocket", "=", "(", "SSLSocket", ")", "sslSocketFactory", ".", "createSocket", "(", "socketClient", ",", "socketClient", ".", "getInetAddress", "(", ")", ".", "getHostAddress", "(", ")", ",", "socketClient", ".", "getPort", "(", ")", ",", "true", ")", ";", "clientSSLSocket", ".", "setNeedClientAuth", "(", "false", ")", ";", "clientSSLSocket", ".", "setUseClientMode", "(", "false", ")", ";", "return", "clientSSLSocket", ";", "}", "/**\n * 将普通的socket转为sslsocket,客户端和服务端均可使用\n * <p>\n * 服务端使用的时候是把普通的socket转为sslsocket,并且作为服务器套接字(注意:指的不是ServerSocket,当然ServerSocket的本质也是普通socket)\n *\n * @param remoteHost\n * @param isClient\n * @return\n */", "public", "static", "SSLSocket", "getTlsTrustAllSocket", "(", "Socket", "remoteHost", ",", "boolean", "isClient", ")", "{", "SSLSocket", "remoteSSLSocket", "=", "null", ";", "SSLContext", "context", "=", "SSLTrustManager", ".", "getTrustAllSSLContext", "(", "isClient", ")", ";", "try", "{", "remoteSSLSocket", "=", "(", "SSLSocket", ")", "context", ".", "getSocketFactory", "(", ")", ".", "createSocket", "(", "remoteHost", ",", "remoteHost", ".", "getInetAddress", "(", ")", ".", "getHostName", "(", ")", ",", "remoteHost", ".", "getPort", "(", ")", ",", "true", ")", ";", "remoteSSLSocket", ".", "setTcpNoDelay", "(", "true", ")", ";", "remoteSSLSocket", ".", "setSoTimeout", "(", "5000", ")", ";", "remoteSSLSocket", ".", "setNeedClientAuth", "(", "false", ")", ";", "remoteSSLSocket", ".", "setUseClientMode", "(", "isClient", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "remoteSSLSocket", ";", "}", "/**\n * 用于客户端,通过所有证书验证\n *\n * @param isClient 是否生成客户端SSLContext,否则生成服务端SSLContext\n * @return\n */", "public", "static", "SSLContext", "getTrustAllSSLContext", "(", "boolean", "isClient", ")", "{", "String", "protocol", "=", "\"", "TLS", "\"", ";", "javax", ".", "net", ".", "ssl", ".", "SSLContext", "sc", "=", "null", ";", "try", "{", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "[", "]", "trustAllCerts", "=", "new", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "[", "1", "]", ";", "javax", ".", "net", ".", "ssl", ".", "TrustManager", "tm", "=", "new", "SSLTrustManager", "(", ")", ";", "trustAllCerts", "[", "0", "]", "=", "tm", ";", "sc", "=", "javax", ".", "net", ".", "ssl", ".", "SSLContext", ".", "getInstance", "(", "protocol", ")", ";", "if", "(", "isClient", ")", "{", "sc", ".", "init", "(", "null", ",", "trustAllCerts", ",", "null", ")", ";", "}", "else", "{", "String", "serverKeyPath", "=", "\"", "D:/JDK8Home/tianwt/sslServerKeys", "\"", ";", "String", "serverKeyPwd", "=", "\"", "123456", "\"", ";", "String", "serverKeyStorePwd", "=", "\"", "123456", "\"", ";", "KeyStore", "keyStore", "=", "KeyStore", ".", "getInstance", "(", "\"", "JKS", "\"", ")", ";", "keyStore", ".", "load", "(", "new", "FileInputStream", "(", "serverKeyPath", ")", ",", "serverKeyPwd", ".", "toCharArray", "(", ")", ")", ";", "KeyManagerFactory", "km", "=", "KeyManagerFactory", ".", "getInstance", "(", "KeyManagerFactory", ".", "getDefaultAlgorithm", "(", ")", ")", ";", "km", ".", "init", "(", "keyStore", ",", "serverKeyStorePwd", ".", "toCharArray", "(", ")", ")", ";", "KeyManager", "[", "]", "keyManagers", "=", "km", ".", "getKeyManagers", "(", ")", ";", "keyManagers", "=", "Arrays", ".", "copyOf", "(", "keyManagers", ",", "keyManagers", ".", "length", "+", "1", ")", ";", "sc", ".", "init", "(", "keyManagers", ",", "null", ",", "new", "SecureRandom", "(", ")", ")", ";", "}", "}", "catch", "(", "KeyManagementException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "UnrecoverableKeyException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "KeyStoreException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "CertificateException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "FileNotFoundException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "sc", ";", "}", "}" ]
Created by Administrator on 2016/11/7.
[ "Created", "by", "Administrator", "on", "2016", "/", "11", "/", "7", "." ]
[ "//允许所有主机", "//私钥密码", "//信任证书密码", "// keystore存储密码", "//第一项是用来做服务器验证的", "//私钥密码", "// keystore存储密码", "//第一项是用来做服务器验证的", "//这里设置为true时会强制握手", "//注意服务器和客户的角色选择", "//作为客户端使用", "//私钥密码", "// keystore存储密码" ]
[ { "param": "javax.net.ssl.TrustManager,\n javax.net.ssl.X509TrustManager, HostnameVerifier", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "javax.net.ssl.TrustManager,\n javax.net.ssl.X509TrustManager, HostnameVerifier", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
846bdd0840926d408231ee9659132b7e225fee5b
nap56/Master1
COMP/TP2/src/Code3aGenerator.java
[ "MIT" ]
Java
Code3aGenerator
/** * This class implements all the methods for 3a code generation (NOTE: this * class must be coded by the student; the methods indicated here can be seen as * a suggestion, but are not actually necessary). * * @author MLB * */
This class implements all the methods for 3a code generation (NOTE: this class must be coded by the student; the methods indicated here can be seen as a suggestion, but are not actually necessary). @author MLB
[ "This", "class", "implements", "all", "the", "methods", "for", "3a", "code", "generation", "(", "NOTE", ":", "this", "class", "must", "be", "coded", "by", "the", "student", ";", "the", "methods", "indicated", "here", "can", "be", "seen", "as", "a", "suggestion", "but", "are", "not", "actually", "necessary", ")", ".", "@author", "MLB" ]
public class Code3aGenerator { // Constructor not needed private Code3aGenerator() { } /** * Generates the 3a statement: VAR t */ public static Code3a genVar(Operand3a t) { Inst3a i = new Inst3a(Inst3a.TAC.VAR, t, null, null); return new Code3a(i); } /** * Generate code for a binary operation * * @param op * must be a code op: Inst3a.TAC.XXX */ public static Code3a genUnaryOp(Inst3a.TAC op, Operand3a temp, ExpAttribute exp1) { Code3a cod = exp1.code; cod.append(genVar(temp)); cod.append(new Inst3a(op, temp, exp1.place, null)); return cod; } /** * Generate code for a binary operation * * @param op * must be a code op: Inst3a.TAC.XXX */ public static Code3a genBinOp(Inst3a.TAC op, Operand3a temp, ExpAttribute exp1, ExpAttribute exp2) { Code3a cod = exp1.code; cod.append(exp2.code); cod.append(genVar(temp)); cod.append(new Inst3a(op, temp, exp1.place, exp2.place)); return cod; } /** * Generate code for affectation */ public static Code3a genAff(Operand3a var, ExpAttribute exp) { Code3a cod = new Code3a(); cod.append(exp.code); cod.append(new Inst3a(Inst3a.TAC.COPY, var, exp.place, null)); return cod; } /** * Generate code for return */ public static Code3a genReturn(ExpAttribute exp) { Code3a code = new Code3a(); // Do the return code.append(exp.code); code.append(new Inst3a(Inst3a.TAC.RETURN, exp.place, null, null)); return code; } /** * Generate code for IF ..... THEN */ public static Code3a genIF(ExpAttribute exp, Code3a code1) { LabelSymbol end = SymbDistrib.newLabel(); Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.IFZ, exp.place, end, null)); code.append(code1); code.append(new Inst3a(Inst3a.TAC.LABEL, end, null, null)); return code; } /** * Generate code for IF ..... THEN ...... ELSE */ public static Code3a genIFELSE(ExpAttribute exp, Code3a code1, Code3a code2) { LabelSymbol elSe = SymbDistrib.newLabel(); LabelSymbol end = SymbDistrib.newLabel(); Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.IFZ, exp.place, elSe, null)); code.append(code1); code.append(new Inst3a(Inst3a.TAC.GOTO, end, null, null)); code.append(new Inst3a(Inst3a.TAC.LABEL, elSe, null, null)); code.append(code2); code.append(new Inst3a(Inst3a.TAC.LABEL, end, null, null)); return code; } /** * Generate code for WHILE ..... DO ...... DONE */ public static Code3a genWHILE(ExpAttribute exp, Code3a code1) { LabelSymbol repeat = SymbDistrib.newLabel(); LabelSymbol end = SymbDistrib.newLabel(); Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.LABEL, repeat, null, null)); code.append(new Inst3a(Inst3a.TAC.IFZ, exp.place, end, null)); code.append(code1); code.append(new Inst3a(Inst3a.TAC.GOTO, repeat, null, null)); code.append(new Inst3a(Inst3a.TAC.LABEL, end, null, null)); return code; } /** * Generate code for PrintSting */ public static Code3a genPrintString(String msg) { Code3a code = new Code3a(); Data3a data = new Data3a(msg); code.appendData(data); code.append(new Inst3a(Inst3a.TAC.ARG, data.getLabel(), null, null)); code.append(new Inst3a(Inst3a.TAC.CALL, null, SymbDistrib.builtinPrintS, null)); return code; } /** * Generate code for PrintInteger */ public static Code3a genPrintInteger(ExpAttribute exp) { Code3a code = new Code3a(); code.append(exp.code); code.append(new Inst3a(Inst3a.TAC.ARG, exp.place, null, null)); code.append(new Inst3a(Inst3a.TAC.CALL, null, SymbDistrib.builtinPrintN, null)); return code; } /** * Generate code for Read Integer */ public static Code3a genReadInteger(VarSymbol var) { Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.CALL, var, SymbDistrib.builtinRead, null)); return code; } /** * Generate code for a variable declaration */ public static Code3a genVarDeclaration(VarSymbol var) { Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.VAR, (Operand3a)var, null, null)); return code; } /** * Generate code for a function declaration */ public static Code3a genFunction(FunctionSymbol functionSymbol, Code3a paramsCode, Code3a statementCode) { Code3a code = new Code3a(); // Generate the label (label [functionName]) code.append(new Inst3a(Inst3a.TAC.LABEL, functionSymbol, null, null)); // Generate the beginfunc instruction (beginfunc) code.append(new Inst3a(Inst3a.TAC.BEGINFUNC, null, null, null)); // Put the params codes then code.append(paramsCode); // Put the statement codes then code.append(statementCode); // And in the end, the end of funtion code code.append(new Inst3a(Inst3a.TAC.ENDFUNC, null, null, null)); // And return the code generated return code; } /** * Generate code for everytime we have to append two codes */ public static Code3a concatenateCodes(Code3a c1, Code3a c2) { Code3a code = new Code3a(); code.append(c1); code.append(c2); // Null verification already done into append() return code; } /** * Generate code for Instruction */ public static Code3a genInstruction(Code3a c) { Code3a code = new Code3a(); code.append(c); return code; } /** * Generate code for a function call */ public static ExpAttribute genFunctionCall(String funcName, FunctionType f, Code3a c) { // Generate a new place VarSymbol resultFunction = SymbDistrib.newTemp(); // Create the ExpAttribute ExpAttribute exp = new ExpAttribute(f.getReturnType(), c, resultFunction); // Then call the function exp.code.append(new Inst3a(Inst3a.TAC.CALL, resultFunction, new LabelSymbol(funcName), null)); // In the end, return this ExpAttribute return exp; } /** * Generate code for a procedure call */ public static Code3a genProcedureCall(String funcName, Code3a c) { // Then call the function Code3a code = new Code3a(); code.append(c); // First, the arguments passed code.append(new Inst3a(Inst3a.TAC.CALL, null, new LabelSymbol(funcName), null)); // In the end, return this code return code; } /** * Generate code for a argument call */ public static Code3a genArg(ExpAttribute e) { Code3a code = e.code; code.append(new Inst3a(Inst3a.TAC.ARG, e.place, null, null)); return code; } /** * Generates the 3a statement: ARRAY */ public static Code3a genArrayElem(Operand3a t , ExpAttribute e) { Code3a code = new Code3a(); code.append(new Inst3a(Inst3a.TAC.VARTAB, t,e.place , null)); return code; } /** * Generates the 3a statement: Affectation of ARRAY */ public static Code3a genAffarray(Code3a c, ExpAttribute e) { Code3a code = new Code3a(); List<Inst3a> l = c.getCode(); Inst3a i = l.get(0); code.append(new Inst3a(i.getOp(), i.getA(), i.getB(), e.place)); return code; } }
[ "public", "class", "Code3aGenerator", "{", "private", "Code3aGenerator", "(", ")", "{", "}", "/**\n\t * Generates the 3a statement: VAR t\n\t */", "public", "static", "Code3a", "genVar", "(", "Operand3a", "t", ")", "{", "Inst3a", "i", "=", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "VAR", ",", "t", ",", "null", ",", "null", ")", ";", "return", "new", "Code3a", "(", "i", ")", ";", "}", "/**\n\t * Generate code for a binary operation\n\t *\n\t * @param op\n\t *\t\t\tmust be a code op: Inst3a.TAC.XXX\n\t */", "public", "static", "Code3a", "genUnaryOp", "(", "Inst3a", ".", "TAC", "op", ",", "Operand3a", "temp", ",", "ExpAttribute", "exp1", ")", "{", "Code3a", "cod", "=", "exp1", ".", "code", ";", "cod", ".", "append", "(", "genVar", "(", "temp", ")", ")", ";", "cod", ".", "append", "(", "new", "Inst3a", "(", "op", ",", "temp", ",", "exp1", ".", "place", ",", "null", ")", ")", ";", "return", "cod", ";", "}", "/**\n\t * Generate code for a binary operation\n\t *\n\t * @param op\n\t *\t\t\tmust be a code op: Inst3a.TAC.XXX\n\t */", "public", "static", "Code3a", "genBinOp", "(", "Inst3a", ".", "TAC", "op", ",", "Operand3a", "temp", ",", "ExpAttribute", "exp1", ",", "ExpAttribute", "exp2", ")", "{", "Code3a", "cod", "=", "exp1", ".", "code", ";", "cod", ".", "append", "(", "exp2", ".", "code", ")", ";", "cod", ".", "append", "(", "genVar", "(", "temp", ")", ")", ";", "cod", ".", "append", "(", "new", "Inst3a", "(", "op", ",", "temp", ",", "exp1", ".", "place", ",", "exp2", ".", "place", ")", ")", ";", "return", "cod", ";", "}", "/**\n\t * Generate code for affectation\n\t */", "public", "static", "Code3a", "genAff", "(", "Operand3a", "var", ",", "ExpAttribute", "exp", ")", "{", "Code3a", "cod", "=", "new", "Code3a", "(", ")", ";", "cod", ".", "append", "(", "exp", ".", "code", ")", ";", "cod", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "COPY", ",", "var", ",", "exp", ".", "place", ",", "null", ")", ")", ";", "return", "cod", ";", "}", "/**\n\t * Generate code for return\n\t */", "public", "static", "Code3a", "genReturn", "(", "ExpAttribute", "exp", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "exp", ".", "code", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "RETURN", ",", "exp", ".", "place", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for IF ..... THEN\n\t */", "public", "static", "Code3a", "genIF", "(", "ExpAttribute", "exp", ",", "Code3a", "code1", ")", "{", "LabelSymbol", "end", "=", "SymbDistrib", ".", "newLabel", "(", ")", ";", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "IFZ", ",", "exp", ".", "place", ",", "end", ",", "null", ")", ")", ";", "code", ".", "append", "(", "code1", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "end", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for IF ..... THEN ...... ELSE\n\t */", "public", "static", "Code3a", "genIFELSE", "(", "ExpAttribute", "exp", ",", "Code3a", "code1", ",", "Code3a", "code2", ")", "{", "LabelSymbol", "elSe", "=", "SymbDistrib", ".", "newLabel", "(", ")", ";", "LabelSymbol", "end", "=", "SymbDistrib", ".", "newLabel", "(", ")", ";", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "IFZ", ",", "exp", ".", "place", ",", "elSe", ",", "null", ")", ")", ";", "code", ".", "append", "(", "code1", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "GOTO", ",", "end", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "elSe", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "code2", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "end", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for WHILE ..... DO ...... DONE\n\t */", "public", "static", "Code3a", "genWHILE", "(", "ExpAttribute", "exp", ",", "Code3a", "code1", ")", "{", "LabelSymbol", "repeat", "=", "SymbDistrib", ".", "newLabel", "(", ")", ";", "LabelSymbol", "end", "=", "SymbDistrib", ".", "newLabel", "(", ")", ";", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "repeat", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "IFZ", ",", "exp", ".", "place", ",", "end", ",", "null", ")", ")", ";", "code", ".", "append", "(", "code1", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "GOTO", ",", "repeat", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "end", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for PrintSting\n\t */", "public", "static", "Code3a", "genPrintString", "(", "String", "msg", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "Data3a", "data", "=", "new", "Data3a", "(", "msg", ")", ";", "code", ".", "appendData", "(", "data", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "ARG", ",", "data", ".", "getLabel", "(", ")", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "CALL", ",", "null", ",", "SymbDistrib", ".", "builtinPrintS", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for PrintInteger\n\t */", "public", "static", "Code3a", "genPrintInteger", "(", "ExpAttribute", "exp", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "exp", ".", "code", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "ARG", ",", "exp", ".", "place", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "CALL", ",", "null", ",", "SymbDistrib", ".", "builtinPrintN", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for Read Integer\n\t */", "public", "static", "Code3a", "genReadInteger", "(", "VarSymbol", "var", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "CALL", ",", "var", ",", "SymbDistrib", ".", "builtinRead", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for a variable declaration\n\t */", "public", "static", "Code3a", "genVarDeclaration", "(", "VarSymbol", "var", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "VAR", ",", "(", "Operand3a", ")", "var", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for a function declaration\n\t */", "public", "static", "Code3a", "genFunction", "(", "FunctionSymbol", "functionSymbol", ",", "Code3a", "paramsCode", ",", "Code3a", "statementCode", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "LABEL", ",", "functionSymbol", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "BEGINFUNC", ",", "null", ",", "null", ",", "null", ")", ")", ";", "code", ".", "append", "(", "paramsCode", ")", ";", "code", ".", "append", "(", "statementCode", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "ENDFUNC", ",", "null", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for everytime we have to append two codes\n\t */", "public", "static", "Code3a", "concatenateCodes", "(", "Code3a", "c1", ",", "Code3a", "c2", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "c1", ")", ";", "code", ".", "append", "(", "c2", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for Instruction\n\t */", "public", "static", "Code3a", "genInstruction", "(", "Code3a", "c", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "c", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for a function call\n\t */", "public", "static", "ExpAttribute", "genFunctionCall", "(", "String", "funcName", ",", "FunctionType", "f", ",", "Code3a", "c", ")", "{", "VarSymbol", "resultFunction", "=", "SymbDistrib", ".", "newTemp", "(", ")", ";", "ExpAttribute", "exp", "=", "new", "ExpAttribute", "(", "f", ".", "getReturnType", "(", ")", ",", "c", ",", "resultFunction", ")", ";", "exp", ".", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "CALL", ",", "resultFunction", ",", "new", "LabelSymbol", "(", "funcName", ")", ",", "null", ")", ")", ";", "return", "exp", ";", "}", "/**\n\t * Generate code for a procedure call\n\t */", "public", "static", "Code3a", "genProcedureCall", "(", "String", "funcName", ",", "Code3a", "c", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "c", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "CALL", ",", "null", ",", "new", "LabelSymbol", "(", "funcName", ")", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generate code for a argument call\n\t */", "public", "static", "Code3a", "genArg", "(", "ExpAttribute", "e", ")", "{", "Code3a", "code", "=", "e", ".", "code", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "ARG", ",", "e", ".", "place", ",", "null", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generates the 3a statement: ARRAY\n\t */", "public", "static", "Code3a", "genArrayElem", "(", "Operand3a", "t", ",", "ExpAttribute", "e", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "Inst3a", ".", "TAC", ".", "VARTAB", ",", "t", ",", "e", ".", "place", ",", "null", ")", ")", ";", "return", "code", ";", "}", "/**\n\t * Generates the 3a statement: Affectation of ARRAY\n\t */", "public", "static", "Code3a", "genAffarray", "(", "Code3a", "c", ",", "ExpAttribute", "e", ")", "{", "Code3a", "code", "=", "new", "Code3a", "(", ")", ";", "List", "<", "Inst3a", ">", "l", "=", "c", ".", "getCode", "(", ")", ";", "Inst3a", "i", "=", "l", ".", "get", "(", "0", ")", ";", "code", ".", "append", "(", "new", "Inst3a", "(", "i", ".", "getOp", "(", ")", ",", "i", ".", "getA", "(", ")", ",", "i", ".", "getB", "(", ")", ",", "e", ".", "place", ")", ")", ";", "return", "code", ";", "}", "}" ]
This class implements all the methods for 3a code generation (NOTE: this class must be coded by the student; the methods indicated here can be seen as a suggestion, but are not actually necessary).
[ "This", "class", "implements", "all", "the", "methods", "for", "3a", "code", "generation", "(", "NOTE", ":", "this", "class", "must", "be", "coded", "by", "the", "student", ";", "the", "methods", "indicated", "here", "can", "be", "seen", "as", "a", "suggestion", "but", "are", "not", "actually", "necessary", ")", "." ]
[ "// Constructor not needed", "// Do the return", "// Generate the label (label [functionName])", "// Generate the beginfunc instruction (beginfunc)", "// Put the params codes then", "// Put the statement codes then", "// And in the end, the end of funtion code", "// And return the code generated", "// Null verification already done into append()", "// Generate a new place", "// Create the ExpAttribute", "// Then call the function", "// In the end, return this ExpAttribute", "// Then call the function", "// First, the arguments passed", "// In the end, return this code" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
846d4e723e64c06bde7ffd0045093c8e440f0897
RollingSoftware/L2J_HighFive_Hardcore
l2j_datapack/dist/game/data/scripts/quests/Q00643_RiseAndFallOfTheElrokiTribe/Q00643_RiseAndFallOfTheElrokiTribe.java
[ "MIT" ]
Java
Q00643_RiseAndFallOfTheElrokiTribe
/** * Rise and Fall of the Elroki Tribe (643) * @author Adry_85 */
Rise and Fall of the Elroki Tribe (643) @author Adry_85
[ "Rise", "and", "Fall", "of", "the", "Elroki", "Tribe", "(", "643", ")", "@author", "Adry_85" ]
public class Q00643_RiseAndFallOfTheElrokiTribe extends Quest { // NPCs private static final int SINGSING = 32106; private static final int KARAKAWEI = 32117; // Item private static final int BONES_OF_A_PLAINS_DINOSAUR = 8776; // Misc private static final int MIN_LEVEL = 75; private static final int CHANCE_MOBS1 = 116; private static final int CHANCE_MOBS2 = 360; private static final int CHANCE_DEINO = 558; private boolean isFirstTalk = true; // Rewards private static final int[] PIECE = { 8712, // Sirra's Blade Edge 8713, // Sword of Ipos Blade 8714, // Barakiel's Axe Piece 8715, // Behemoth's Tuning Fork Piece 8716, // Naga Storm Piece 8717, // Tiphon's Spear Edge 8718, // Shyeed's Bow Shaft 8719, // Sobekk's Hurricane Edge 8720, // Themis' Tongue Piece 8721, // Cabrio's Hand Head 8722, // Daimon Crystal Fragment }; // Mobs private static final int[] MOBS1 = { 22200, // Ornithomimus 22201, // Ornithomimus 22202, // Ornithomimus 22204, // Deinonychus 22205, // Deinonychus 22208, // Pachycephalosaurus 22209, // Pachycephalosaurus 22210, // Pachycephalosaurus 22211, // Wild Strider 22212, // Wild Strider 22213, // Wild Strider 22219, // Ornithomimus 22220, // Deinonychus 22221, // Pachycephalosaurus 22222, // Wild Strider 22224, // Ornithomimus 22225, // Deinonychus 22226, // Pachycephalosaurus 22227, // Wild Strider }; private static final int[] MOBS2 = { 22742, // Ornithomimus 22743, // Deinonychus 22744, // Ornithomimus 22745, // Deinonychus }; private static final int DEINONYCHUS = 22203; public Q00643_RiseAndFallOfTheElrokiTribe() { super(643, Q00643_RiseAndFallOfTheElrokiTribe.class.getSimpleName(), "Rise and Fall of the Elroki Tribe"); addStartNpc(SINGSING); addTalkId(SINGSING, KARAKAWEI); addKillId(MOBS1); addKillId(MOBS2); addKillId(DEINONYCHUS); registerQuestItems(BONES_OF_A_PLAINS_DINOSAUR); } @Override public String onAdvEvent(String event, L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, false); if (st == null) { return null; } String htmltext = null; switch (event) { case "32106-02.htm": case "32106-04.htm": case "32106-05.html": case "32106-10.html": case "32106-13.html": case "32117-02.html": case "32117-06.html": case "32117-07.html": { htmltext = event; break; } case "quest_accept": { if (player.getLevel() >= MIN_LEVEL) { st.startQuest(); htmltext = "32106-03.html"; } else { htmltext = "32106-07.html"; } break; } case "32106-09.html": { st.giveAdena(1374 * st.getQuestItemsCount(BONES_OF_A_PLAINS_DINOSAUR), true); st.takeItems(BONES_OF_A_PLAINS_DINOSAUR, -1); htmltext = event; break; } case "exit": { if (!st.hasQuestItems(BONES_OF_A_PLAINS_DINOSAUR)) { htmltext = "32106-11.html"; } else { st.giveAdena(1374 * st.getQuestItemsCount(BONES_OF_A_PLAINS_DINOSAUR), true); htmltext = "32106-12.html"; } st.exitQuest(true, true); break; } case "exchange": { if (st.getQuestItemsCount(BONES_OF_A_PLAINS_DINOSAUR) < 300) { htmltext = "32117-04.html"; } else { st.rewardItems(PIECE[getRandom(PIECE.length)], 5); st.takeItems(BONES_OF_A_PLAINS_DINOSAUR, 300); st.playSound(Sound.ITEMSOUND_QUEST_MIDDLE); htmltext = "32117-05.html"; } break; } } return htmltext; } @Override public String onKill(L2Npc npc, L2PcInstance player, boolean isSummon) { final L2PcInstance partyMember = getRandomPartyMember(player, 1); if (partyMember == null) { return super.onKill(npc, player, isSummon); } final QuestState st = getQuestState(partyMember, false); int npcId = npc.getId(); if (Util.contains(MOBS1, npcId)) { float chance = (CHANCE_MOBS1 * Config.RATE_QUEST_DROP); if (getRandom(1000) < chance) { st.rewardItems(BONES_OF_A_PLAINS_DINOSAUR, 2); } else { st.rewardItems(BONES_OF_A_PLAINS_DINOSAUR, 1); } st.playSound(Sound.ITEMSOUND_QUEST_ITEMGET); } if (Util.contains(MOBS2, npcId)) { float chance = (CHANCE_MOBS2 * Config.RATE_QUEST_DROP); if (getRandom(1000) < chance) { st.rewardItems(BONES_OF_A_PLAINS_DINOSAUR, 1); st.playSound(Sound.ITEMSOUND_QUEST_ITEMGET); } } if (npcId == DEINONYCHUS) { float chance = (CHANCE_DEINO * Config.RATE_QUEST_DROP); if (getRandom(1000) < chance) { st.rewardItems(BONES_OF_A_PLAINS_DINOSAUR, 1); st.playSound(Sound.ITEMSOUND_QUEST_ITEMGET); } } return super.onKill(npc, player, isSummon); } @Override public String onTalk(L2Npc npc, L2PcInstance player) { final QuestState st = getQuestState(player, true); String htmltext = getNoQuestMsg(player); if (st == null) { return htmltext; } switch (st.getState()) { case State.CREATED: { htmltext = (player.getLevel() >= MIN_LEVEL) ? "32106-01.htm" : "32106-06.html"; break; } case State.STARTED: { if (npc.getId() == SINGSING) { htmltext = (st.hasQuestItems(BONES_OF_A_PLAINS_DINOSAUR)) ? "32106-08.html" : "32106-14.html"; } else if (npc.getId() == KARAKAWEI) { if (isFirstTalk) { isFirstTalk = false; htmltext = "32117-01.html"; } else { htmltext = "32117-03.html"; } } break; } } return htmltext; } }
[ "public", "class", "Q00643_RiseAndFallOfTheElrokiTribe", "extends", "Quest", "{", "private", "static", "final", "int", "SINGSING", "=", "32106", ";", "private", "static", "final", "int", "KARAKAWEI", "=", "32117", ";", "private", "static", "final", "int", "BONES_OF_A_PLAINS_DINOSAUR", "=", "8776", ";", "private", "static", "final", "int", "MIN_LEVEL", "=", "75", ";", "private", "static", "final", "int", "CHANCE_MOBS1", "=", "116", ";", "private", "static", "final", "int", "CHANCE_MOBS2", "=", "360", ";", "private", "static", "final", "int", "CHANCE_DEINO", "=", "558", ";", "private", "boolean", "isFirstTalk", "=", "true", ";", "private", "static", "final", "int", "[", "]", "PIECE", "=", "{", "8712", ",", "8713", ",", "8714", ",", "8715", ",", "8716", ",", "8717", ",", "8718", ",", "8719", ",", "8720", ",", "8721", ",", "8722", ",", "}", ";", "private", "static", "final", "int", "[", "]", "MOBS1", "=", "{", "22200", ",", "22201", ",", "22202", ",", "22204", ",", "22205", ",", "22208", ",", "22209", ",", "22210", ",", "22211", ",", "22212", ",", "22213", ",", "22219", ",", "22220", ",", "22221", ",", "22222", ",", "22224", ",", "22225", ",", "22226", ",", "22227", ",", "}", ";", "private", "static", "final", "int", "[", "]", "MOBS2", "=", "{", "22742", ",", "22743", ",", "22744", ",", "22745", ",", "}", ";", "private", "static", "final", "int", "DEINONYCHUS", "=", "22203", ";", "public", "Q00643_RiseAndFallOfTheElrokiTribe", "(", ")", "{", "super", "(", "643", ",", "Q00643_RiseAndFallOfTheElrokiTribe", ".", "class", ".", "getSimpleName", "(", ")", ",", "\"", "Rise and Fall of the Elroki Tribe", "\"", ")", ";", "addStartNpc", "(", "SINGSING", ")", ";", "addTalkId", "(", "SINGSING", ",", "KARAKAWEI", ")", ";", "addKillId", "(", "MOBS1", ")", ";", "addKillId", "(", "MOBS2", ")", ";", "addKillId", "(", "DEINONYCHUS", ")", ";", "registerQuestItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", ";", "}", "@", "Override", "public", "String", "onAdvEvent", "(", "String", "event", ",", "L2Npc", "npc", ",", "L2PcInstance", "player", ")", "{", "final", "QuestState", "st", "=", "getQuestState", "(", "player", ",", "false", ")", ";", "if", "(", "st", "==", "null", ")", "{", "return", "null", ";", "}", "String", "htmltext", "=", "null", ";", "switch", "(", "event", ")", "{", "case", "\"", "32106-02.htm", "\"", ":", "case", "\"", "32106-04.htm", "\"", ":", "case", "\"", "32106-05.html", "\"", ":", "case", "\"", "32106-10.html", "\"", ":", "case", "\"", "32106-13.html", "\"", ":", "case", "\"", "32117-02.html", "\"", ":", "case", "\"", "32117-06.html", "\"", ":", "case", "\"", "32117-07.html", "\"", ":", "{", "htmltext", "=", "event", ";", "break", ";", "}", "case", "\"", "quest_accept", "\"", ":", "{", "if", "(", "player", ".", "getLevel", "(", ")", ">=", "MIN_LEVEL", ")", "{", "st", ".", "startQuest", "(", ")", ";", "htmltext", "=", "\"", "32106-03.html", "\"", ";", "}", "else", "{", "htmltext", "=", "\"", "32106-07.html", "\"", ";", "}", "break", ";", "}", "case", "\"", "32106-09.html", "\"", ":", "{", "st", ".", "giveAdena", "(", "1374", "*", "st", ".", "getQuestItemsCount", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", ",", "true", ")", ";", "st", ".", "takeItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "-", "1", ")", ";", "htmltext", "=", "event", ";", "break", ";", "}", "case", "\"", "exit", "\"", ":", "{", "if", "(", "!", "st", ".", "hasQuestItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", ")", "{", "htmltext", "=", "\"", "32106-11.html", "\"", ";", "}", "else", "{", "st", ".", "giveAdena", "(", "1374", "*", "st", ".", "getQuestItemsCount", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", ",", "true", ")", ";", "htmltext", "=", "\"", "32106-12.html", "\"", ";", "}", "st", ".", "exitQuest", "(", "true", ",", "true", ")", ";", "break", ";", "}", "case", "\"", "exchange", "\"", ":", "{", "if", "(", "st", ".", "getQuestItemsCount", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", "<", "300", ")", "{", "htmltext", "=", "\"", "32117-04.html", "\"", ";", "}", "else", "{", "st", ".", "rewardItems", "(", "PIECE", "[", "getRandom", "(", "PIECE", ".", "length", ")", "]", ",", "5", ")", ";", "st", ".", "takeItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "300", ")", ";", "st", ".", "playSound", "(", "Sound", ".", "ITEMSOUND_QUEST_MIDDLE", ")", ";", "htmltext", "=", "\"", "32117-05.html", "\"", ";", "}", "break", ";", "}", "}", "return", "htmltext", ";", "}", "@", "Override", "public", "String", "onKill", "(", "L2Npc", "npc", ",", "L2PcInstance", "player", ",", "boolean", "isSummon", ")", "{", "final", "L2PcInstance", "partyMember", "=", "getRandomPartyMember", "(", "player", ",", "1", ")", ";", "if", "(", "partyMember", "==", "null", ")", "{", "return", "super", ".", "onKill", "(", "npc", ",", "player", ",", "isSummon", ")", ";", "}", "final", "QuestState", "st", "=", "getQuestState", "(", "partyMember", ",", "false", ")", ";", "int", "npcId", "=", "npc", ".", "getId", "(", ")", ";", "if", "(", "Util", ".", "contains", "(", "MOBS1", ",", "npcId", ")", ")", "{", "float", "chance", "=", "(", "CHANCE_MOBS1", "*", "Config", ".", "RATE_QUEST_DROP", ")", ";", "if", "(", "getRandom", "(", "1000", ")", "<", "chance", ")", "{", "st", ".", "rewardItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "2", ")", ";", "}", "else", "{", "st", ".", "rewardItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "1", ")", ";", "}", "st", ".", "playSound", "(", "Sound", ".", "ITEMSOUND_QUEST_ITEMGET", ")", ";", "}", "if", "(", "Util", ".", "contains", "(", "MOBS2", ",", "npcId", ")", ")", "{", "float", "chance", "=", "(", "CHANCE_MOBS2", "*", "Config", ".", "RATE_QUEST_DROP", ")", ";", "if", "(", "getRandom", "(", "1000", ")", "<", "chance", ")", "{", "st", ".", "rewardItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "1", ")", ";", "st", ".", "playSound", "(", "Sound", ".", "ITEMSOUND_QUEST_ITEMGET", ")", ";", "}", "}", "if", "(", "npcId", "==", "DEINONYCHUS", ")", "{", "float", "chance", "=", "(", "CHANCE_DEINO", "*", "Config", ".", "RATE_QUEST_DROP", ")", ";", "if", "(", "getRandom", "(", "1000", ")", "<", "chance", ")", "{", "st", ".", "rewardItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ",", "1", ")", ";", "st", ".", "playSound", "(", "Sound", ".", "ITEMSOUND_QUEST_ITEMGET", ")", ";", "}", "}", "return", "super", ".", "onKill", "(", "npc", ",", "player", ",", "isSummon", ")", ";", "}", "@", "Override", "public", "String", "onTalk", "(", "L2Npc", "npc", ",", "L2PcInstance", "player", ")", "{", "final", "QuestState", "st", "=", "getQuestState", "(", "player", ",", "true", ")", ";", "String", "htmltext", "=", "getNoQuestMsg", "(", "player", ")", ";", "if", "(", "st", "==", "null", ")", "{", "return", "htmltext", ";", "}", "switch", "(", "st", ".", "getState", "(", ")", ")", "{", "case", "State", ".", "CREATED", ":", "{", "htmltext", "=", "(", "player", ".", "getLevel", "(", ")", ">=", "MIN_LEVEL", ")", "?", "\"", "32106-01.htm", "\"", ":", "\"", "32106-06.html", "\"", ";", "break", ";", "}", "case", "State", ".", "STARTED", ":", "{", "if", "(", "npc", ".", "getId", "(", ")", "==", "SINGSING", ")", "{", "htmltext", "=", "(", "st", ".", "hasQuestItems", "(", "BONES_OF_A_PLAINS_DINOSAUR", ")", ")", "?", "\"", "32106-08.html", "\"", ":", "\"", "32106-14.html", "\"", ";", "}", "else", "if", "(", "npc", ".", "getId", "(", ")", "==", "KARAKAWEI", ")", "{", "if", "(", "isFirstTalk", ")", "{", "isFirstTalk", "=", "false", ";", "htmltext", "=", "\"", "32117-01.html", "\"", ";", "}", "else", "{", "htmltext", "=", "\"", "32117-03.html", "\"", ";", "}", "}", "break", ";", "}", "}", "return", "htmltext", ";", "}", "}" ]
Rise and Fall of the Elroki Tribe (643) @author Adry_85
[ "Rise", "and", "Fall", "of", "the", "Elroki", "Tribe", "(", "643", ")", "@author", "Adry_85" ]
[ "// NPCs", "// Item", "// Misc", "// Rewards", "// Sirra's Blade Edge", "// Sword of Ipos Blade", "// Barakiel's Axe Piece", "// Behemoth's Tuning Fork Piece", "// Naga Storm Piece", "// Tiphon's Spear Edge", "// Shyeed's Bow Shaft", "// Sobekk's Hurricane Edge", "// Themis' Tongue Piece", "// Cabrio's Hand Head", "// Daimon Crystal Fragment", "// Mobs", "// Ornithomimus", "// Ornithomimus", "// Ornithomimus", "// Deinonychus", "// Deinonychus", "// Pachycephalosaurus", "// Pachycephalosaurus", "// Pachycephalosaurus", "// Wild Strider", "// Wild Strider", "// Wild Strider", "// Ornithomimus", "// Deinonychus", "// Pachycephalosaurus", "// Wild Strider", "// Ornithomimus", "// Deinonychus", "// Pachycephalosaurus", "// Wild Strider", "// Ornithomimus", "// Deinonychus", "// Ornithomimus", "// Deinonychus" ]
[ { "param": "Quest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Quest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8472c887af709b98297bc27ac091fdca256e6421
rnarla123/aliyun-openapi-java-sdk
aliyun-java-sdk-datav-outer/src/main/java/com/aliyuncs/datav_outer/model/v20190402/BatchCreateScreensByTemplatesRequest.java
[ "Apache-2.0" ]
Java
BatchCreateScreensByTemplatesRequest
/** * @author auto create * @version */
@author auto create @version
[ "@author", "auto", "create", "@version" ]
public class BatchCreateScreensByTemplatesRequest extends RpcAcsRequest<BatchCreateScreensByTemplatesResponse> { private String product; private List<Screens> screenss; private String domain; private String version; public BatchCreateScreensByTemplatesRequest() { super("datav-outer", "2019-04-02", "BatchCreateScreensByTemplates", "datav"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getProduct() { return this.product; } public void setProduct(String product) { this.product = product; if(product != null){ putBodyParameter("Product", product); } } public List<Screens> getScreenss() { return this.screenss; } public void setScreenss(List<Screens> screenss) { this.screenss = screenss; if (screenss != null) { for (int depth1 = 0; depth1 < screenss.size(); depth1++) { putBodyParameter("Screens." + (depth1 + 1) + ".DataSourceJSON" , screenss.get(depth1).getDataSourceJSON()); if (screenss.get(depth1).getDataSources() != null) { for (int depth2 = 0; depth2 < screenss.get(depth1).getDataSources().size(); depth2++) { putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Name" , screenss.get(depth1).getDataSources().get(depth2).getName()); putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Type" , screenss.get(depth1).getDataSources().get(depth2).getType()); putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Config" , screenss.get(depth1).getDataSources().get(depth2).getConfig()); } } putBodyParameter("Screens." + (depth1 + 1) + ".Name" , screenss.get(depth1).getName()); putBodyParameter("Screens." + (depth1 + 1) + ".Association" , screenss.get(depth1).getAssociation()); putBodyParameter("Screens." + (depth1 + 1) + ".TemplateId" , screenss.get(depth1).getTemplateId()); putBodyParameter("Screens." + (depth1 + 1) + ".ProjectId" , screenss.get(depth1).getProjectId()); putBodyParameter("Screens." + (depth1 + 1) + ".WorkspaceId" , screenss.get(depth1).getWorkspaceId()); } } } public String getDomain() { return this.domain; } public void setDomain(String domain) { this.domain = domain; if(domain != null){ putBodyParameter("Domain", domain); } } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; if(version != null){ putBodyParameter("Version", version); } } public static class Screens { private String dataSourceJSON; private List<DataSource> dataSources; private String name; private String association; private Integer templateId; private Integer projectId; private Integer workspaceId; public String getDataSourceJSON() { return this.dataSourceJSON; } public void setDataSourceJSON(String dataSourceJSON) { this.dataSourceJSON = dataSourceJSON; } public List<DataSource> getDataSources() { return this.dataSources; } public void setDataSources(List<DataSource> dataSources) { this.dataSources = dataSources; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getAssociation() { return this.association; } public void setAssociation(String association) { this.association = association; } public Integer getTemplateId() { return this.templateId; } public void setTemplateId(Integer templateId) { this.templateId = templateId; } public Integer getProjectId() { return this.projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getWorkspaceId() { return this.workspaceId; } public void setWorkspaceId(Integer workspaceId) { this.workspaceId = workspaceId; } public static class DataSource { private String name; private String type; private String config; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public String getConfig() { return this.config; } public void setConfig(String config) { this.config = config; } } } @Override public Class<BatchCreateScreensByTemplatesResponse> getResponseClass() { return BatchCreateScreensByTemplatesResponse.class; } }
[ "public", "class", "BatchCreateScreensByTemplatesRequest", "extends", "RpcAcsRequest", "<", "BatchCreateScreensByTemplatesResponse", ">", "{", "private", "String", "product", ";", "private", "List", "<", "Screens", ">", "screenss", ";", "private", "String", "domain", ";", "private", "String", "version", ";", "public", "BatchCreateScreensByTemplatesRequest", "(", ")", "{", "super", "(", "\"", "datav-outer", "\"", ",", "\"", "2019-04-02", "\"", ",", "\"", "BatchCreateScreensByTemplates", "\"", ",", "\"", "datav", "\"", ")", ";", "setMethod", "(", "MethodType", ".", "POST", ")", ";", "try", "{", "com", ".", "aliyuncs", ".", "AcsRequest", ".", "class", ".", "getDeclaredField", "(", "\"", "productEndpointMap", "\"", ")", ".", "set", "(", "this", ",", "Endpoint", ".", "endpointMap", ")", ";", "com", ".", "aliyuncs", ".", "AcsRequest", ".", "class", ".", "getDeclaredField", "(", "\"", "productEndpointRegional", "\"", ")", ".", "set", "(", "this", ",", "Endpoint", ".", "endpointRegionalType", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "public", "String", "getProduct", "(", ")", "{", "return", "this", ".", "product", ";", "}", "public", "void", "setProduct", "(", "String", "product", ")", "{", "this", ".", "product", "=", "product", ";", "if", "(", "product", "!=", "null", ")", "{", "putBodyParameter", "(", "\"", "Product", "\"", ",", "product", ")", ";", "}", "}", "public", "List", "<", "Screens", ">", "getScreenss", "(", ")", "{", "return", "this", ".", "screenss", ";", "}", "public", "void", "setScreenss", "(", "List", "<", "Screens", ">", "screenss", ")", "{", "this", ".", "screenss", "=", "screenss", ";", "if", "(", "screenss", "!=", "null", ")", "{", "for", "(", "int", "depth1", "=", "0", ";", "depth1", "<", "screenss", ".", "size", "(", ")", ";", "depth1", "++", ")", "{", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".DataSourceJSON", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSourceJSON", "(", ")", ")", ";", "if", "(", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSources", "(", ")", "!=", "null", ")", "{", "for", "(", "int", "depth2", "=", "0", ";", "depth2", "<", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSources", "(", ")", ".", "size", "(", ")", ";", "depth2", "++", ")", "{", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".DataSource.", "\"", "+", "(", "depth2", "+", "1", ")", "+", "\"", ".Name", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSources", "(", ")", ".", "get", "(", "depth2", ")", ".", "getName", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".DataSource.", "\"", "+", "(", "depth2", "+", "1", ")", "+", "\"", ".Type", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSources", "(", ")", ".", "get", "(", "depth2", ")", ".", "getType", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".DataSource.", "\"", "+", "(", "depth2", "+", "1", ")", "+", "\"", ".Config", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getDataSources", "(", ")", ".", "get", "(", "depth2", ")", ".", "getConfig", "(", ")", ")", ";", "}", "}", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".Name", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getName", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".Association", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getAssociation", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".TemplateId", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getTemplateId", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".ProjectId", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getProjectId", "(", ")", ")", ";", "putBodyParameter", "(", "\"", "Screens.", "\"", "+", "(", "depth1", "+", "1", ")", "+", "\"", ".WorkspaceId", "\"", ",", "screenss", ".", "get", "(", "depth1", ")", ".", "getWorkspaceId", "(", ")", ")", ";", "}", "}", "}", "public", "String", "getDomain", "(", ")", "{", "return", "this", ".", "domain", ";", "}", "public", "void", "setDomain", "(", "String", "domain", ")", "{", "this", ".", "domain", "=", "domain", ";", "if", "(", "domain", "!=", "null", ")", "{", "putBodyParameter", "(", "\"", "Domain", "\"", ",", "domain", ")", ";", "}", "}", "public", "String", "getVersion", "(", ")", "{", "return", "this", ".", "version", ";", "}", "public", "void", "setVersion", "(", "String", "version", ")", "{", "this", ".", "version", "=", "version", ";", "if", "(", "version", "!=", "null", ")", "{", "putBodyParameter", "(", "\"", "Version", "\"", ",", "version", ")", ";", "}", "}", "public", "static", "class", "Screens", "{", "private", "String", "dataSourceJSON", ";", "private", "List", "<", "DataSource", ">", "dataSources", ";", "private", "String", "name", ";", "private", "String", "association", ";", "private", "Integer", "templateId", ";", "private", "Integer", "projectId", ";", "private", "Integer", "workspaceId", ";", "public", "String", "getDataSourceJSON", "(", ")", "{", "return", "this", ".", "dataSourceJSON", ";", "}", "public", "void", "setDataSourceJSON", "(", "String", "dataSourceJSON", ")", "{", "this", ".", "dataSourceJSON", "=", "dataSourceJSON", ";", "}", "public", "List", "<", "DataSource", ">", "getDataSources", "(", ")", "{", "return", "this", ".", "dataSources", ";", "}", "public", "void", "setDataSources", "(", "List", "<", "DataSource", ">", "dataSources", ")", "{", "this", ".", "dataSources", "=", "dataSources", ";", "}", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "name", ";", "}", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "public", "String", "getAssociation", "(", ")", "{", "return", "this", ".", "association", ";", "}", "public", "void", "setAssociation", "(", "String", "association", ")", "{", "this", ".", "association", "=", "association", ";", "}", "public", "Integer", "getTemplateId", "(", ")", "{", "return", "this", ".", "templateId", ";", "}", "public", "void", "setTemplateId", "(", "Integer", "templateId", ")", "{", "this", ".", "templateId", "=", "templateId", ";", "}", "public", "Integer", "getProjectId", "(", ")", "{", "return", "this", ".", "projectId", ";", "}", "public", "void", "setProjectId", "(", "Integer", "projectId", ")", "{", "this", ".", "projectId", "=", "projectId", ";", "}", "public", "Integer", "getWorkspaceId", "(", ")", "{", "return", "this", ".", "workspaceId", ";", "}", "public", "void", "setWorkspaceId", "(", "Integer", "workspaceId", ")", "{", "this", ".", "workspaceId", "=", "workspaceId", ";", "}", "public", "static", "class", "DataSource", "{", "private", "String", "name", ";", "private", "String", "type", ";", "private", "String", "config", ";", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "name", ";", "}", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "public", "String", "getType", "(", ")", "{", "return", "this", ".", "type", ";", "}", "public", "void", "setType", "(", "String", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "public", "String", "getConfig", "(", ")", "{", "return", "this", ".", "config", ";", "}", "public", "void", "setConfig", "(", "String", "config", ")", "{", "this", ".", "config", "=", "config", ";", "}", "}", "}", "@", "Override", "public", "Class", "<", "BatchCreateScreensByTemplatesResponse", ">", "getResponseClass", "(", ")", "{", "return", "BatchCreateScreensByTemplatesResponse", ".", "class", ";", "}", "}" ]
@author auto create @version
[ "@author", "auto", "create", "@version" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8473e1382ff80f9641d68f714fe4cf11b1e3f082
9410ger/thingsboard
common/data/src/main/java/org/thingsboard/server/common/data/finca/Finca.java
[ "ECL-2.0", "Apache-2.0" ]
Java
Finca
/** * * @author German Lopez */
@author German Lopez
[ "@author", "German", "Lopez" ]
@EqualsAndHashCode(callSuper = true) public class Finca extends SearchTextBasedWithAdditionalInfo<FincaId> implements HasName { //private static final long serialVersionUID = 2807343040519543363L; private TenantId tenantId; private CustomerId customerId; private String name; private String type; private String details; public Finca(){ super(); } public Finca(FincaId id){ super(id); } public Finca(Finca finca){ this.tenantId=finca.getTenantId(); this.customerId=finca.getCustomerId(); this.name=finca.getName(); this.type=finca.getType(); this.details=finca.getDetails(); } @Override public String getSearchText() { return getName(); } @Override public String getName() { return this.name; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Finca [tenantId="); builder.append(tenantId); builder.append(", customerId="); builder.append(customerId); builder.append(", name="); builder.append(name); builder.append(", type="); builder.append(type); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append(" , details="); builder.append(details); builder.append("]"); return builder.toString(); } /** * @return the tenantId */ public TenantId getTenantId() { return tenantId; } /** * @param tenantId the tenantId to set */ public void setTenantId(TenantId tenantId) { this.tenantId = tenantId; } /** * @return the customerId */ public CustomerId getCustomerId() { return customerId; } /** * @param customerId the customerId to set */ public void setCustomerId(CustomerId customerId) { this.customerId = customerId; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the details */ public String getDetails() { return details; } /** * @param details the details to set */ public void setDetails(String details) { this.details = details; } }
[ "@", "EqualsAndHashCode", "(", "callSuper", "=", "true", ")", "public", "class", "Finca", "extends", "SearchTextBasedWithAdditionalInfo", "<", "FincaId", ">", "implements", "HasName", "{", "private", "TenantId", "tenantId", ";", "private", "CustomerId", "customerId", ";", "private", "String", "name", ";", "private", "String", "type", ";", "private", "String", "details", ";", "public", "Finca", "(", ")", "{", "super", "(", ")", ";", "}", "public", "Finca", "(", "FincaId", "id", ")", "{", "super", "(", "id", ")", ";", "}", "public", "Finca", "(", "Finca", "finca", ")", "{", "this", ".", "tenantId", "=", "finca", ".", "getTenantId", "(", ")", ";", "this", ".", "customerId", "=", "finca", ".", "getCustomerId", "(", ")", ";", "this", ".", "name", "=", "finca", ".", "getName", "(", ")", ";", "this", ".", "type", "=", "finca", ".", "getType", "(", ")", ";", "this", ".", "details", "=", "finca", ".", "getDetails", "(", ")", ";", "}", "@", "Override", "public", "String", "getSearchText", "(", ")", "{", "return", "getName", "(", ")", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "this", ".", "name", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"", "Finca [tenantId=", "\"", ")", ";", "builder", ".", "append", "(", "tenantId", ")", ";", "builder", ".", "append", "(", "\"", ", customerId=", "\"", ")", ";", "builder", ".", "append", "(", "customerId", ")", ";", "builder", ".", "append", "(", "\"", ", name=", "\"", ")", ";", "builder", ".", "append", "(", "name", ")", ";", "builder", ".", "append", "(", "\"", ", type=", "\"", ")", ";", "builder", ".", "append", "(", "type", ")", ";", "builder", ".", "append", "(", "\"", ", additionalInfo=", "\"", ")", ";", "builder", ".", "append", "(", "getAdditionalInfo", "(", ")", ")", ";", "builder", ".", "append", "(", "\"", ", createdTime=", "\"", ")", ";", "builder", ".", "append", "(", "createdTime", ")", ";", "builder", ".", "append", "(", "\"", ", id=", "\"", ")", ";", "builder", ".", "append", "(", "id", ")", ";", "builder", ".", "append", "(", "\"", " , details=", "\"", ")", ";", "builder", ".", "append", "(", "details", ")", ";", "builder", ".", "append", "(", "\"", "]", "\"", ")", ";", "return", "builder", ".", "toString", "(", ")", ";", "}", "/**\n * @return the tenantId\n */", "public", "TenantId", "getTenantId", "(", ")", "{", "return", "tenantId", ";", "}", "/**\n * @param tenantId the tenantId to set\n */", "public", "void", "setTenantId", "(", "TenantId", "tenantId", ")", "{", "this", ".", "tenantId", "=", "tenantId", ";", "}", "/**\n * @return the customerId\n */", "public", "CustomerId", "getCustomerId", "(", ")", "{", "return", "customerId", ";", "}", "/**\n * @param customerId the customerId to set\n */", "public", "void", "setCustomerId", "(", "CustomerId", "customerId", ")", "{", "this", ".", "customerId", "=", "customerId", ";", "}", "/**\n * @param name the name to set\n */", "public", "void", "setName", "(", "String", "name", ")", "{", "this", ".", "name", "=", "name", ";", "}", "/**\n * @return the type\n */", "public", "String", "getType", "(", ")", "{", "return", "type", ";", "}", "/**\n * @param type the type to set\n */", "public", "void", "setType", "(", "String", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "/**\n * @return the details\n */", "public", "String", "getDetails", "(", ")", "{", "return", "details", ";", "}", "/**\n * @param details the details to set\n */", "public", "void", "setDetails", "(", "String", "details", ")", "{", "this", ".", "details", "=", "details", ";", "}", "}" ]
@author German Lopez
[ "@author", "German", "Lopez" ]
[ "//private static final long serialVersionUID = 2807343040519543363L;" ]
[ { "param": "HasName", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HasName", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
847d2cbc6541981973224709e17f8f806704d4e5
bobloblog/weather-app
src/Setup.java
[ "MIT" ]
Java
Setup
/** * This class should be called to start the Weather program. It sets up the frame and checks for updates. * @author Locomotion15 * */
This class should be called to start the Weather program. It sets up the frame and checks for updates. @author Locomotion15
[ "This", "class", "should", "be", "called", "to", "start", "the", "Weather", "program", ".", "It", "sets", "up", "the", "frame", "and", "checks", "for", "updates", ".", "@author", "Locomotion15" ]
public class Setup { private static final String NEWLINE = System.getProperty("line.separator"), fileSeparator = System.getProperty("file.separator");//cross-platform compatibility private static JFrame f; private static int version = 0; private static boolean soundMuted = false; private static String lastSearch = null; /** * The main method will start the Weather program. This program does not process any arguments. * @param args None will be processed. */ public static void main(String[] args) { new TestDriver(); SwingUtilities.invokeLater(new Runnable()//Standard for Swing programs { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { new Thread(new Runnable(){public void run()//Creates a thread to decrease latency { try{update();} catch(Exception e){nonFatalError("Unable to fetch update information.\nErrLn: Setup 51\nDesc: General issue");} }}).start(); f = new JFrame("Weather"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}//Java look-and-feel sucks catch (Exception e) {}//Non-fatal with no ill-effects. No need to bother the user. f.setSize(600, 335);//600x335 f.setResizable(false); f.setLocationRelativeTo(null);//Centers it f.setIconImage(Toolkit.getDefaultToolkit().getImage("resources\\images\\icon.png")); f.setVisible(true); if(lastSearch == null) new WindowManager(f, version);//See WindowManager else new WindowManager(f, version, soundMuted, lastSearch);//See WindowManager } private static void update() throws Exception { try//Finds the version of the running program stored in the Resources/Data.txt file { BufferedReader in; in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("resources\\Data.txt")))); version = Integer.parseInt(in.readLine()); soundMuted = Boolean.parseBoolean(in.readLine()); lastSearch = in.readLine(); in.close(); }catch(Exception e){nonFatalError("Unable to read version information.\nErrLn: Setup 80\nDesc: Error reading \"Data.txt\"");} try//Compares the running version number to the update version number stored online { URL tempUpdateAddress = new URL("https://sites.google.com/site/locomotion15/update.txt");//Forever where the update instructions will be located BufferedReader in; in = new BufferedReader( new InputStreamReader( tempUpdateAddress.openStream())); if(version >= Integer.parseInt(in.readLine()))//The first line is ALWAYS the version number. Closes here if up to date. { in.close(); return; } in.close(); } catch(Exception e){nonFatalError("Unable to fetch version information.\nErrLn: Setup 99\nDesc: Error connecting to \"update.txt\"");} if(JOptionPane.showConfirmDialog(f, "An update is available. Would you like to download and install it now?", "Update Available", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != 0) return; try{Runtime.getRuntime().exec(" java -jar " + "Update.jar " + version + ""); System.exit(0);}//Runs the Update program (See WeatherUpdate project). catch(Exception e){nonFatalError("The update was unable to initiate.\nErrLn: Setup 105\nDesc: Error executing \"Update.jar\"");} } private static void nonFatalError(String errorMessage) { JOptionPane.showMessageDialog(f, errorMessage, "Non-fatal Error", JOptionPane.ERROR_MESSAGE); } private static void fatalError(String errorMessage) { JOptionPane.showMessageDialog(f, errorMessage + "\nThe program will now terminante.", "Fatal Error!", JOptionPane.ERROR_MESSAGE); gracefulClose(); } private static void gracefulClose() { System.out.println("Closing now..."); File file = new File("resources\\data.txt"); try//Writes the info file { PrintWriter writer = new PrintWriter(new FileWriter(file, false)); writer.write(version + NEWLINE); writer.write(soundMuted + NEWLINE); writer.write(lastSearch); writer.close(); }catch(Exception e){} f.dispose(); System.exit(0); //calling the method is a must } }
[ "public", "class", "Setup", "{", "private", "static", "final", "String", "NEWLINE", "=", "System", ".", "getProperty", "(", "\"", "line.separator", "\"", ")", ",", "fileSeparator", "=", "System", ".", "getProperty", "(", "\"", "file.separator", "\"", ")", ";", "private", "static", "JFrame", "f", ";", "private", "static", "int", "version", "=", "0", ";", "private", "static", "boolean", "soundMuted", "=", "false", ";", "private", "static", "String", "lastSearch", "=", "null", ";", "/**\n\t * The main method will start the Weather program. This program does not process any arguments.\n\t * @param args None will be processed.\n\t */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "new", "TestDriver", "(", ")", ";", "SwingUtilities", ".", "invokeLater", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "createAndShowGUI", "(", ")", ";", "}", "}", ")", ";", "}", "private", "static", "void", "createAndShowGUI", "(", ")", "{", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "try", "{", "update", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "nonFatalError", "(", "\"", "Unable to fetch update information.", "\\n", "ErrLn: Setup 51", "\\n", "Desc: General issue", "\"", ")", ";", "}", "}", "}", ")", ".", "start", "(", ")", ";", "f", "=", "new", "JFrame", "(", "\"", "Weather", "\"", ")", ";", "f", ".", "setDefaultCloseOperation", "(", "JFrame", ".", "EXIT_ON_CLOSE", ")", ";", "try", "{", "UIManager", ".", "setLookAndFeel", "(", "UIManager", ".", "getSystemLookAndFeelClassName", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "f", ".", "setSize", "(", "600", ",", "335", ")", ";", "f", ".", "setResizable", "(", "false", ")", ";", "f", ".", "setLocationRelativeTo", "(", "null", ")", ";", "f", ".", "setIconImage", "(", "Toolkit", ".", "getDefaultToolkit", "(", ")", ".", "getImage", "(", "\"", "resources", "\\\\", "images", "\\\\", "icon.png", "\"", ")", ")", ";", "f", ".", "setVisible", "(", "true", ")", ";", "if", "(", "lastSearch", "==", "null", ")", "new", "WindowManager", "(", "f", ",", "version", ")", ";", "else", "new", "WindowManager", "(", "f", ",", "version", ",", "soundMuted", ",", "lastSearch", ")", ";", "}", "private", "static", "void", "update", "(", ")", "throws", "Exception", "{", "try", "{", "BufferedReader", "in", ";", "in", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "new", "File", "(", "\"", "resources", "\\\\", "Data.txt", "\"", ")", ")", ")", ")", ";", "version", "=", "Integer", ".", "parseInt", "(", "in", ".", "readLine", "(", ")", ")", ";", "soundMuted", "=", "Boolean", ".", "parseBoolean", "(", "in", ".", "readLine", "(", ")", ")", ";", "lastSearch", "=", "in", ".", "readLine", "(", ")", ";", "in", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "nonFatalError", "(", "\"", "Unable to read version information.", "\\n", "ErrLn: Setup 80", "\\n", "Desc: Error reading ", "\\\"", "Data.txt", "\\\"", "\"", ")", ";", "}", "try", "{", "URL", "tempUpdateAddress", "=", "new", "URL", "(", "\"", "https://sites.google.com/site/locomotion15/update.txt", "\"", ")", ";", "BufferedReader", "in", ";", "in", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "tempUpdateAddress", ".", "openStream", "(", ")", ")", ")", ";", "if", "(", "version", ">=", "Integer", ".", "parseInt", "(", "in", ".", "readLine", "(", ")", ")", ")", "{", "in", ".", "close", "(", ")", ";", "return", ";", "}", "in", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "nonFatalError", "(", "\"", "Unable to fetch version information.", "\\n", "ErrLn: Setup 99", "\\n", "Desc: Error connecting to ", "\\\"", "update.txt", "\\\"", "\"", ")", ";", "}", "if", "(", "JOptionPane", ".", "showConfirmDialog", "(", "f", ",", "\"", "An update is available. Would you like to download and install it now?", "\"", ",", "\"", "Update Available", "\"", ",", "JOptionPane", ".", "YES_NO_OPTION", ",", "JOptionPane", ".", "QUESTION_MESSAGE", ")", "!=", "0", ")", "return", ";", "try", "{", "Runtime", ".", "getRuntime", "(", ")", ".", "exec", "(", "\"", " java -jar ", "\"", "+", "\"", "Update.jar ", "\"", "+", "version", "+", "\"", "\"", ")", ";", "System", ".", "exit", "(", "0", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "nonFatalError", "(", "\"", "The update was unable to initiate.", "\\n", "ErrLn: Setup 105", "\\n", "Desc: Error executing ", "\\\"", "Update.jar", "\\\"", "\"", ")", ";", "}", "}", "private", "static", "void", "nonFatalError", "(", "String", "errorMessage", ")", "{", "JOptionPane", ".", "showMessageDialog", "(", "f", ",", "errorMessage", ",", "\"", "Non-fatal Error", "\"", ",", "JOptionPane", ".", "ERROR_MESSAGE", ")", ";", "}", "private", "static", "void", "fatalError", "(", "String", "errorMessage", ")", "{", "JOptionPane", ".", "showMessageDialog", "(", "f", ",", "errorMessage", "+", "\"", "\\n", "The program will now terminante.", "\"", ",", "\"", "Fatal Error!", "\"", ",", "JOptionPane", ".", "ERROR_MESSAGE", ")", ";", "gracefulClose", "(", ")", ";", "}", "private", "static", "void", "gracefulClose", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Closing now...", "\"", ")", ";", "File", "file", "=", "new", "File", "(", "\"", "resources", "\\\\", "data.txt", "\"", ")", ";", "try", "{", "PrintWriter", "writer", "=", "new", "PrintWriter", "(", "new", "FileWriter", "(", "file", ",", "false", ")", ")", ";", "writer", ".", "write", "(", "version", "+", "NEWLINE", ")", ";", "writer", ".", "write", "(", "soundMuted", "+", "NEWLINE", ")", ";", "writer", ".", "write", "(", "lastSearch", ")", ";", "writer", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "f", ".", "dispose", "(", ")", ";", "System", ".", "exit", "(", "0", ")", ";", "}", "}" ]
This class should be called to start the Weather program.
[ "This", "class", "should", "be", "called", "to", "start", "the", "Weather", "program", "." ]
[ "//cross-platform compatibility", "//Standard for Swing programs", "//Creates a thread to decrease latency", "//Java look-and-feel sucks", "//Non-fatal with no ill-effects. No need to bother the user.", "//600x335", "//Centers it", "//See WindowManager", "//See WindowManager", "//Finds the version of the running program stored in the Resources/Data.txt file", "//Compares the running version number to the update version number stored online", "//Forever where the update instructions will be located", "//The first line is ALWAYS the version number. Closes here if up to date.", "//Runs the Update program (See WeatherUpdate project).", "//Writes the info file", "//calling the method is a must" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8480ba0c2eceb00025e3396d44d90dfb4d92f247
Knoblul/eos-vstu-bot
src/main/java/knoblul/eosvstubot/utils/swing/DialogUtils.java
[ "Apache-2.0" ]
Java
DialogUtils
/** * <br><br>Module: eos-vstu-bot * <br>Created: 22.04.2020 0:51 * @author Knoblul */
Module: eos-vstu-bot Created: 22.04.2020 0:51 @author Knoblul
[ "Module", ":", "eos", "-", "vstu", "-", "bot", "Created", ":", "22", ".", "04", ".", "2020", "0", ":", "51", "@author", "Knoblul" ]
public class DialogUtils { /** * Показывает простой диалог о предупреждении. * Вызывать можно из любого потока, так как создание диалога * в любом случае будет происходить в AWT event dispatching thread. * @param message текст предупреждения */ public static void showWarning(String message) { SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(BotMainWindow.instance, message, "Внимание", JOptionPane.WARNING_MESSAGE) ); } /** * Показывает простой диалог с сообщением об ошибке. * Вызывать можно из любого потока, так как создание диалога * в любом случае будет происходить в AWT event dispatching thread. * @param message текст ошибки * @param t исключение * @param doLogError писать ли в консоль то, что выводится в сообщении */ public static void showError(String message, Throwable t, boolean doLogError) { // какой то старый снипплет свинг диалога с ошибкой, // украл из старго проекта if (doLogError) { Log.error(t, message); } JDialog dialog = new JDialog(BotMainWindow.instance, "Ошибка", true); dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); dialog.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.weightx = 1; gbc.insets.set(10, 10, 10, 10); dialog.add(new JLabel(message), gbc); dialog.setSize(500, 400); dialog.setLocationRelativeTo(null); gbc.weightx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1; gbc.weighty = 1; gbc.insets.set(0, 10, 0, 10); JTextArea ta = new JTextArea(); ta.setFont(new Font("Consolas", Font.PLAIN, 12)); ta.setText(Throwables.getStackTraceAsString(t)); ta.setCaretPosition(0); JScrollPane jscp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jscp.setMaximumSize(new Dimension(400, 500)); dialog.add(jscp, gbc); JButton ok = new JButton("Ок"); ok.addActionListener(e -> dialog.setVisible(false)); gbc.fill = GridBagConstraints.NONE; gbc.anchor = GridBagConstraints.CENTER; gbc.insets.set(10, 10, 10, 10); gbc.gridy = 2; gbc.weightx = 0; gbc.weighty = 0; dialog.add(ok, gbc); SwingUtilities.invokeLater(() -> dialog.setVisible(true)); } /** * Показывает простой диалог о подтверждении. * Вызывать можно из любого потока, так как создание диалога * в любом случае будет происходить в AWT event dispatching thread. * @param message текст подтверждения * @return <code>true</code>, если была нажата кнопка ДА. */ public static boolean showConfirmation(String message) { return JOptionPane.showConfirmDialog(BotMainWindow.instance, message, "Подтвердите", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } }
[ "public", "class", "DialogUtils", "{", "/**\n\t * Показывает простой диалог о предупреждении.\n\t * Вызывать можно из любого потока, так как создание диалога\n\t * в любом случае будет происходить в AWT event dispatching thread.\n\t * @param message текст предупреждения\n\t */", "public", "static", "void", "showWarning", "(", "String", "message", ")", "{", "SwingUtilities", ".", "invokeLater", "(", "(", ")", "->", "JOptionPane", ".", "showMessageDialog", "(", "BotMainWindow", ".", "instance", ",", "message", ",", "\"", "Внимание\", JOpti", "o", "n", "ane.WARNING", "_", "MESSAGE)", "", ")", ";", "}", "/**\n\t * Показывает простой диалог с сообщением об ошибке.\n\t * Вызывать можно из любого потока, так как создание диалога\n\t * в любом случае будет происходить в AWT event dispatching thread.\n\t * @param message текст ошибки\n\t * @param t исключение\n\t * @param doLogError писать ли в консоль то, что выводится в сообщении\n\t */", "public", "static", "void", "showError", "(", "String", "message", ",", "Throwable", "t", ",", "boolean", "doLogError", ")", "{", "if", "(", "doLogError", ")", "{", "Log", ".", "error", "(", "t", ",", "message", ")", ";", "}", "JDialog", "dialog", "=", "new", "JDialog", "(", "BotMainWindow", ".", "instance", ",", "\"", "Ошибка\", tru", "e", ")", "", "", "", "dialog", ".", "setDefaultCloseOperation", "(", "JDialog", ".", "HIDE_ON_CLOSE", ")", ";", "dialog", ".", "setLayout", "(", "new", "GridBagLayout", "(", ")", ")", ";", "GridBagConstraints", "gbc", "=", "new", "GridBagConstraints", "(", ")", ";", "gbc", ".", "gridx", "=", "0", ";", "gbc", ".", "gridy", "=", "0", ";", "gbc", ".", "anchor", "=", "GridBagConstraints", ".", "WEST", ";", "gbc", ".", "weightx", "=", "1", ";", "gbc", ".", "insets", ".", "set", "(", "10", ",", "10", ",", "10", ",", "10", ")", ";", "dialog", ".", "add", "(", "new", "JLabel", "(", "message", ")", ",", "gbc", ")", ";", "dialog", ".", "setSize", "(", "500", ",", "400", ")", ";", "dialog", ".", "setLocationRelativeTo", "(", "null", ")", ";", "gbc", ".", "weightx", "=", "0", ";", "gbc", ".", "gridy", "=", "1", ";", "gbc", ".", "fill", "=", "GridBagConstraints", ".", "BOTH", ";", "gbc", ".", "weightx", "=", "1", ";", "gbc", ".", "weighty", "=", "1", ";", "gbc", ".", "insets", ".", "set", "(", "0", ",", "10", ",", "0", ",", "10", ")", ";", "JTextArea", "ta", "=", "new", "JTextArea", "(", ")", ";", "ta", ".", "setFont", "(", "new", "Font", "(", "\"", "Consolas", "\"", ",", "Font", ".", "PLAIN", ",", "12", ")", ")", ";", "ta", ".", "setText", "(", "Throwables", ".", "getStackTraceAsString", "(", "t", ")", ")", ";", "ta", ".", "setCaretPosition", "(", "0", ")", ";", "JScrollPane", "jscp", "=", "new", "JScrollPane", "(", "ta", ",", "JScrollPane", ".", "VERTICAL_SCROLLBAR_AS_NEEDED", ",", "JScrollPane", ".", "HORIZONTAL_SCROLLBAR_AS_NEEDED", ")", ";", "jscp", ".", "setMaximumSize", "(", "new", "Dimension", "(", "400", ",", "500", ")", ")", ";", "dialog", ".", "add", "(", "jscp", ",", "gbc", ")", ";", "JButton", "ok", "=", "new", "JButton", "(", "\"", "Ок\")", ";", "", "", "ok", ".", "addActionListener", "(", "e", "->", "dialog", ".", "setVisible", "(", "false", ")", ")", ";", "gbc", ".", "fill", "=", "GridBagConstraints", ".", "NONE", ";", "gbc", ".", "anchor", "=", "GridBagConstraints", ".", "CENTER", ";", "gbc", ".", "insets", ".", "set", "(", "10", ",", "10", ",", "10", ",", "10", ")", ";", "gbc", ".", "gridy", "=", "2", ";", "gbc", ".", "weightx", "=", "0", ";", "gbc", ".", "weighty", "=", "0", ";", "dialog", ".", "add", "(", "ok", ",", "gbc", ")", ";", "SwingUtilities", ".", "invokeLater", "(", "(", ")", "->", "dialog", ".", "setVisible", "(", "true", ")", ")", ";", "}", "/**\n\t * Показывает простой диалог о подтверждении.\n\t * Вызывать можно из любого потока, так как создание диалога\n\t * в любом случае будет происходить в AWT event dispatching thread.\n\t * @param message текст подтверждения\n\t * @return <code>true</code>, если была нажата кнопка ДА.\n\t */", "public", "static", "boolean", "showConfirmation", "(", "String", "message", ")", "{", "return", "JOptionPane", ".", "showConfirmDialog", "(", "BotMainWindow", ".", "instance", ",", "message", ",", "\"", "Подтвердите\",", "", "", "JOptionPane", ".", "YES_NO_OPTION", ")", "==", "JOptionPane", ".", "YES_OPTION", ";", "}", "}" ]
<br><br>Module: eos-vstu-bot <br>Created: 22.04.2020 0:51 @author Knoblul
[ "<br", ">", "<br", ">", "Module", ":", "eos", "-", "vstu", "-", "bot", "<br", ">", "Created", ":", "22", ".", "04", ".", "2020", "0", ":", "51", "@author", "Knoblul" ]
[ "// какой то старый снипплет свинг диалога с ошибкой,", "// украл из старго проекта" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
848ce4fa01eccc808d70143522549df360628fd0
HungNguyenBao/react-native-detect-navbar-android
android/src/main/java/com/rndetectnavbarandroid/RNDetectNavbarAndroidModule.java
[ "MIT" ]
Java
RNDetectNavbarAndroidModule
/** * {@link NativeModule} that allows changing the appearance of the menu bar. */
NativeModule that allows changing the appearance of the menu bar.
[ "NativeModule", "that", "allows", "changing", "the", "appearance", "of", "the", "menu", "bar", "." ]
public class RNDetectNavbarAndroidModule extends ReactContextBaseJavaModule { ReactApplicationContext reactContext; public RNDetectNavbarAndroidModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNDetectNavbarAndroid"; } @ReactMethod public void hasSoftKeys(final Promise promise) { promise.resolve(hasImmersive()); } private static boolean hasImmersive; private static boolean cached = false; @SuppressLint ("NewApi") private boolean hasImmersive() { Resources resources = reactContext.getResources(); int resourceId = resources.getIdentifier("config_navBarInteractionMode", "integer", "android"); if (resourceId > 0) { return resources.getInteger(resourceId) < 2; } return true; } }
[ "public", "class", "RNDetectNavbarAndroidModule", "extends", "ReactContextBaseJavaModule", "{", "ReactApplicationContext", "reactContext", ";", "public", "RNDetectNavbarAndroidModule", "(", "ReactApplicationContext", "reactContext", ")", "{", "super", "(", "reactContext", ")", ";", "this", ".", "reactContext", "=", "reactContext", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "\"", "RNDetectNavbarAndroid", "\"", ";", "}", "@", "ReactMethod", "public", "void", "hasSoftKeys", "(", "final", "Promise", "promise", ")", "{", "promise", ".", "resolve", "(", "hasImmersive", "(", ")", ")", ";", "}", "private", "static", "boolean", "hasImmersive", ";", "private", "static", "boolean", "cached", "=", "false", ";", "@", "SuppressLint", "(", "\"", "NewApi", "\"", ")", "private", "boolean", "hasImmersive", "(", ")", "{", "Resources", "resources", "=", "reactContext", ".", "getResources", "(", ")", ";", "int", "resourceId", "=", "resources", ".", "getIdentifier", "(", "\"", "config_navBarInteractionMode", "\"", ",", "\"", "integer", "\"", ",", "\"", "android", "\"", ")", ";", "if", "(", "resourceId", ">", "0", ")", "{", "return", "resources", ".", "getInteger", "(", "resourceId", ")", "<", "2", ";", "}", "return", "true", ";", "}", "}" ]
{@link NativeModule} that allows changing the appearance of the menu bar.
[ "{", "@link", "NativeModule", "}", "that", "allows", "changing", "the", "appearance", "of", "the", "menu", "bar", "." ]
[]
[ { "param": "ReactContextBaseJavaModule", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ReactContextBaseJavaModule", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
849740b8c5ef42d095eaead20e22d3f9055c94dd
JLLeitschuh/searchisko
api/src/main/java/org/searchisko/api/model/StatsConfiguration.java
[ "Apache-2.0" ]
Java
StatsConfiguration
/** * Configuration for statistics client * * @author Libor Krzyzanek * @author Vlastimil Elias (velias at redhat dot com) */
Configuration for statistics client @author Libor Krzyzanek @author Vlastimil Elias (velias at redhat dot com)
[ "Configuration", "for", "statistics", "client", "@author", "Libor", "Krzyzanek", "@author", "Vlastimil", "Elias", "(", "velias", "at", "redhat", "dot", "com", ")" ]
@Named @ApplicationScoped @Singleton @Startup @Lock(LockType.READ) public class StatsConfiguration { public static final String FILE = "/stats_client_configuration.properties"; protected boolean enabled; protected boolean useSearchCluster; protected boolean async; protected Properties settingsProps = null; /** * Default constructor. */ public StatsConfiguration() { } /** * Constructor. * * @param enabled to set */ public StatsConfiguration(boolean enabled) { super(); this.enabled = enabled; this.async = true; } /** * Constructor. * * @param enabled to set * @param useSearchCluster to set * @param async to set */ public StatsConfiguration(boolean enabled, boolean useSearchCluster, boolean async) { super(); this.enabled = enabled; this.useSearchCluster = useSearchCluster; this.async = async; } public boolean enabled() { return this.enabled; } public boolean isUseSearchCluster() { return useSearchCluster; } public boolean isAsync() { return async; } public void setAsync(boolean async) { this.async = async; } public Properties getSettingsProps() { return settingsProps; } @PostConstruct public void init() throws IOException { settingsProps = SearchUtils.loadProperties(FILE); enabled = Boolean.parseBoolean(settingsProps.getProperty("stats.enabled", "true")); useSearchCluster = Boolean.parseBoolean(settingsProps.getProperty("stats.useSearchCluster", "true")); async = Boolean.parseBoolean(settingsProps.getProperty("stats.async", "true")); } }
[ "@", "Named", "@", "ApplicationScoped", "@", "Singleton", "@", "Startup", "@", "Lock", "(", "LockType", ".", "READ", ")", "public", "class", "StatsConfiguration", "{", "public", "static", "final", "String", "FILE", "=", "\"", "/stats_client_configuration.properties", "\"", ";", "protected", "boolean", "enabled", ";", "protected", "boolean", "useSearchCluster", ";", "protected", "boolean", "async", ";", "protected", "Properties", "settingsProps", "=", "null", ";", "/**\n\t * Default constructor.\n\t */", "public", "StatsConfiguration", "(", ")", "{", "}", "/**\n\t * Constructor.\n\t *\n\t * @param enabled to set\n\t */", "public", "StatsConfiguration", "(", "boolean", "enabled", ")", "{", "super", "(", ")", ";", "this", ".", "enabled", "=", "enabled", ";", "this", ".", "async", "=", "true", ";", "}", "/**\n\t * Constructor.\n\t *\n\t * @param enabled to set\n\t * @param useSearchCluster to set\n\t * @param async to set\n\t */", "public", "StatsConfiguration", "(", "boolean", "enabled", ",", "boolean", "useSearchCluster", ",", "boolean", "async", ")", "{", "super", "(", ")", ";", "this", ".", "enabled", "=", "enabled", ";", "this", ".", "useSearchCluster", "=", "useSearchCluster", ";", "this", ".", "async", "=", "async", ";", "}", "public", "boolean", "enabled", "(", ")", "{", "return", "this", ".", "enabled", ";", "}", "public", "boolean", "isUseSearchCluster", "(", ")", "{", "return", "useSearchCluster", ";", "}", "public", "boolean", "isAsync", "(", ")", "{", "return", "async", ";", "}", "public", "void", "setAsync", "(", "boolean", "async", ")", "{", "this", ".", "async", "=", "async", ";", "}", "public", "Properties", "getSettingsProps", "(", ")", "{", "return", "settingsProps", ";", "}", "@", "PostConstruct", "public", "void", "init", "(", ")", "throws", "IOException", "{", "settingsProps", "=", "SearchUtils", ".", "loadProperties", "(", "FILE", ")", ";", "enabled", "=", "Boolean", ".", "parseBoolean", "(", "settingsProps", ".", "getProperty", "(", "\"", "stats.enabled", "\"", ",", "\"", "true", "\"", ")", ")", ";", "useSearchCluster", "=", "Boolean", ".", "parseBoolean", "(", "settingsProps", ".", "getProperty", "(", "\"", "stats.useSearchCluster", "\"", ",", "\"", "true", "\"", ")", ")", ";", "async", "=", "Boolean", ".", "parseBoolean", "(", "settingsProps", ".", "getProperty", "(", "\"", "stats.async", "\"", ",", "\"", "true", "\"", ")", ")", ";", "}", "}" ]
Configuration for statistics client @author Libor Krzyzanek @author Vlastimil Elias (velias at redhat dot com)
[ "Configuration", "for", "statistics", "client", "@author", "Libor", "Krzyzanek", "@author", "Vlastimil", "Elias", "(", "velias", "at", "redhat", "dot", "com", ")" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
849871f078d9a15ff0f732ed9c82ac13a6cafcf3
leogomesdev/java-calculator
src/com/leogomesdev/services/ParserService.java
[ "MIT" ]
Java
ParserService
/** * Parse tokens into a result using the math operators. */
Parse tokens into a result using the math operators.
[ "Parse", "tokens", "into", "a", "result", "using", "the", "math", "operators", "." ]
class ParserService { private OperatorsDictionary operatorsDictionary = new OperatorsDictionary(); private Integer index = 0; private List<Token> tokens; ParserService(List<Token> tokens) { this.tokens = tokens; } private void moveToNext() { this.index++; } private Token current() { if (this.index < this.tokens.size()) { return this.tokens.get(this.index); } return new Token(this.operatorsDictionary.END_OF_EXPRESSION); } /** * Given a "node" of operation (e.g. x "operation" y), it'll call the correct eval(x, y) * It's recursive because it needs to resolve "x" and "y" before calling the eval for "operation" * @param precedence control of "importance" of operations. Force * and / to be resolved before - and + operators * @return the numeric result of the expression * @throws Exception in case of incomplete expression (missing parentheses closing or number to operate) */ double parseOperations(Integer precedence) throws Exception { double result = this.parseExpression(); while ( this.current().type.equals(this.operatorsDictionary.TYPE_OPERATOR) && this.current().precedence > precedence ) { Token token = this.current(); this.moveToNext(); double secondValue = this.parseOperations(token.precedence); result = this.operatorsDictionary.resolve(token.value, result, secondValue); } return result; } /** * Return the value of the current number, if it's just a number * If the current token is a parenthesis, will parse all operations inside those and then return its result * @return the result of the "node" * @throws Exception in case of incomplete expression (missing parentheses closing or number to operate) */ private double parseExpression() throws Exception { if (this.current().type.equals(this.operatorsDictionary.TYPE_NUM)) { double value = Double.parseDouble(this.current().value); this.moveToNext(); return value; } if (this.current().type.equals(this.operatorsDictionary.TYPE_LEFT_PAREN)) { this.moveToNext(); double result = this.parseOperations(0); if (!this.current().type.equals(this.operatorsDictionary.TYPE_RIGHT_PAREN)) { throw new Exception("Expect to close parentheses"); } this.moveToNext(); return result; } throw new Exception("Expect to find an operand"); } }
[ "class", "ParserService", "{", "private", "OperatorsDictionary", "operatorsDictionary", "=", "new", "OperatorsDictionary", "(", ")", ";", "private", "Integer", "index", "=", "0", ";", "private", "List", "<", "Token", ">", "tokens", ";", "ParserService", "(", "List", "<", "Token", ">", "tokens", ")", "{", "this", ".", "tokens", "=", "tokens", ";", "}", "private", "void", "moveToNext", "(", ")", "{", "this", ".", "index", "++", ";", "}", "private", "Token", "current", "(", ")", "{", "if", "(", "this", ".", "index", "<", "this", ".", "tokens", ".", "size", "(", ")", ")", "{", "return", "this", ".", "tokens", ".", "get", "(", "this", ".", "index", ")", ";", "}", "return", "new", "Token", "(", "this", ".", "operatorsDictionary", ".", "END_OF_EXPRESSION", ")", ";", "}", "/**\n * Given a \"node\" of operation (e.g. x \"operation\" y), it'll call the correct eval(x, y)\n * It's recursive because it needs to resolve \"x\" and \"y\" before calling the eval for \"operation\"\n * @param precedence control of \"importance\" of operations. Force * and / to be resolved before - and + operators\n * @return the numeric result of the expression\n * @throws Exception in case of incomplete expression (missing parentheses closing or number to operate)\n */", "double", "parseOperations", "(", "Integer", "precedence", ")", "throws", "Exception", "{", "double", "result", "=", "this", ".", "parseExpression", "(", ")", ";", "while", "(", "this", ".", "current", "(", ")", ".", "type", ".", "equals", "(", "this", ".", "operatorsDictionary", ".", "TYPE_OPERATOR", ")", "&&", "this", ".", "current", "(", ")", ".", "precedence", ">", "precedence", ")", "{", "Token", "token", "=", "this", ".", "current", "(", ")", ";", "this", ".", "moveToNext", "(", ")", ";", "double", "secondValue", "=", "this", ".", "parseOperations", "(", "token", ".", "precedence", ")", ";", "result", "=", "this", ".", "operatorsDictionary", ".", "resolve", "(", "token", ".", "value", ",", "result", ",", "secondValue", ")", ";", "}", "return", "result", ";", "}", "/**\n * Return the value of the current number, if it's just a number\n * If the current token is a parenthesis, will parse all operations inside those and then return its result\n * @return the result of the \"node\"\n * @throws Exception in case of incomplete expression (missing parentheses closing or number to operate)\n */", "private", "double", "parseExpression", "(", ")", "throws", "Exception", "{", "if", "(", "this", ".", "current", "(", ")", ".", "type", ".", "equals", "(", "this", ".", "operatorsDictionary", ".", "TYPE_NUM", ")", ")", "{", "double", "value", "=", "Double", ".", "parseDouble", "(", "this", ".", "current", "(", ")", ".", "value", ")", ";", "this", ".", "moveToNext", "(", ")", ";", "return", "value", ";", "}", "if", "(", "this", ".", "current", "(", ")", ".", "type", ".", "equals", "(", "this", ".", "operatorsDictionary", ".", "TYPE_LEFT_PAREN", ")", ")", "{", "this", ".", "moveToNext", "(", ")", ";", "double", "result", "=", "this", ".", "parseOperations", "(", "0", ")", ";", "if", "(", "!", "this", ".", "current", "(", ")", ".", "type", ".", "equals", "(", "this", ".", "operatorsDictionary", ".", "TYPE_RIGHT_PAREN", ")", ")", "{", "throw", "new", "Exception", "(", "\"", "Expect to close parentheses", "\"", ")", ";", "}", "this", ".", "moveToNext", "(", ")", ";", "return", "result", ";", "}", "throw", "new", "Exception", "(", "\"", "Expect to find an operand", "\"", ")", ";", "}", "}" ]
Parse tokens into a result using the math operators.
[ "Parse", "tokens", "into", "a", "result", "using", "the", "math", "operators", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8499b89fa22842448435cbbfefc5a9251350f4ca
aaronsms/tp
src/main/java/seedu/address/logic/commands/AddCheeseCommand.java
[ "MIT" ]
Java
AddCheeseCommand
/** * Adds a cheese to the address book. */
Adds a cheese to the address book.
[ "Adds", "a", "cheese", "to", "the", "address", "book", "." ]
public class AddCheeseCommand extends AddCommand { public static final String COMMAND_WORD = "addcheese"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a cheese to the address book.\n" + "Parameters: " + PREFIX_CHEESE_TYPE + "CHEESE TYPE " + PREFIX_QUANTITY + "QUANTITY " + "[" + PREFIX_MANUFACTURE_DATE + "MANUFACTURE_DATE] " + "[" + PREFIX_MATURITY_DATE + "MATURITY_DATE] " + "[" + PREFIX_EXPIRY_DATE + "EXPIRY_DATE]\n" + "Example: " + COMMAND_WORD + " " + PREFIX_CHEESE_TYPE + "Parmesan " + PREFIX_QUANTITY + "5 " + PREFIX_MANUFACTURE_DATE + "2020-12-30 " + PREFIX_MATURITY_DATE + "2021-01-20 " + PREFIX_EXPIRY_DATE + "2021-02-30"; public static final String MESSAGE_SUCCESS = "New cheeses added: "; private final Cheese[] toAddCheeses; /** * Creates an AddOrderCommand to add the specified {@code Order} */ public AddCheeseCommand(Cheese[] cheeses) { requireNonNull(cheeses); toAddCheeses = cheeses; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); for (Cheese toAddCheese : toAddCheeses) { model.addCheese(toAddCheese); } model.setPanelToCheeseList(); StringBuilder sb = new StringBuilder(MESSAGE_SUCCESS); for (Cheese toAddCheese : toAddCheeses) { sb.append("\n"); sb.append(toAddCheese); } return new CommandResult(sb.toString()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AddCheeseCommand // instanceof handles nulls && Arrays.equals(toAddCheeses, ((AddCheeseCommand) other).toAddCheeses)); } }
[ "public", "class", "AddCheeseCommand", "extends", "AddCommand", "{", "public", "static", "final", "String", "COMMAND_WORD", "=", "\"", "addcheese", "\"", ";", "public", "static", "final", "String", "MESSAGE_USAGE", "=", "COMMAND_WORD", "+", "\"", ": Adds a cheese to the address book.", "\\n", "\"", "+", "\"", "Parameters: ", "\"", "+", "PREFIX_CHEESE_TYPE", "+", "\"", "CHEESE TYPE ", "\"", "+", "PREFIX_QUANTITY", "+", "\"", "QUANTITY ", "\"", "+", "\"", "[", "\"", "+", "PREFIX_MANUFACTURE_DATE", "+", "\"", "MANUFACTURE_DATE] ", "\"", "+", "\"", "[", "\"", "+", "PREFIX_MATURITY_DATE", "+", "\"", "MATURITY_DATE] ", "\"", "+", "\"", "[", "\"", "+", "PREFIX_EXPIRY_DATE", "+", "\"", "EXPIRY_DATE]", "\\n", "\"", "+", "\"", "Example: ", "\"", "+", "COMMAND_WORD", "+", "\"", " ", "\"", "+", "PREFIX_CHEESE_TYPE", "+", "\"", "Parmesan ", "\"", "+", "PREFIX_QUANTITY", "+", "\"", "5 ", "\"", "+", "PREFIX_MANUFACTURE_DATE", "+", "\"", "2020-12-30 ", "\"", "+", "PREFIX_MATURITY_DATE", "+", "\"", "2021-01-20 ", "\"", "+", "PREFIX_EXPIRY_DATE", "+", "\"", "2021-02-30", "\"", ";", "public", "static", "final", "String", "MESSAGE_SUCCESS", "=", "\"", "New cheeses added: ", "\"", ";", "private", "final", "Cheese", "[", "]", "toAddCheeses", ";", "/**\n * Creates an AddOrderCommand to add the specified {@code Order}\n */", "public", "AddCheeseCommand", "(", "Cheese", "[", "]", "cheeses", ")", "{", "requireNonNull", "(", "cheeses", ")", ";", "toAddCheeses", "=", "cheeses", ";", "}", "@", "Override", "public", "CommandResult", "execute", "(", "Model", "model", ")", "throws", "CommandException", "{", "requireNonNull", "(", "model", ")", ";", "for", "(", "Cheese", "toAddCheese", ":", "toAddCheeses", ")", "{", "model", ".", "addCheese", "(", "toAddCheese", ")", ";", "}", "model", ".", "setPanelToCheeseList", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "MESSAGE_SUCCESS", ")", ";", "for", "(", "Cheese", "toAddCheese", ":", "toAddCheeses", ")", "{", "sb", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "toAddCheese", ")", ";", "}", "return", "new", "CommandResult", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "other", ")", "{", "return", "other", "==", "this", "||", "(", "other", "instanceof", "AddCheeseCommand", "&&", "Arrays", ".", "equals", "(", "toAddCheeses", ",", "(", "(", "AddCheeseCommand", ")", "other", ")", ".", "toAddCheeses", ")", ")", ";", "}", "}" ]
Adds a cheese to the address book.
[ "Adds", "a", "cheese", "to", "the", "address", "book", "." ]
[ "// short circuit if same object", "// instanceof handles nulls" ]
[ { "param": "AddCommand", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AddCommand", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
849c340df2876077f298f240a726a0430524e1ff
thomasdarimont/undertow-extensions
service-availability-http-handler/src/main/java/de/tdlabs/undertow/handler/sa/ServiceAvailabilityHandler.java
[ "Apache-2.0" ]
Java
ServiceAvailabilityHandler
/** * Special @link {@link HttpHandler} Filter which returns HTTP Status Code {@code 503 Service Unvailable} * until a given deployment unit is successfully deployed, from then on the application will control the HTTP Response. */
Special @link HttpHandler Filter which returns HTTP Status Code 503 Service Unvailable until a given deployment unit is successfully deployed, from then on the application will control the HTTP Response.
[ "Special", "@link", "HttpHandler", "Filter", "which", "returns", "HTTP", "Status", "Code", "503", "Service", "Unvailable", "until", "a", "given", "deployment", "unit", "is", "successfully", "deployed", "from", "then", "on", "the", "application", "will", "control", "the", "HTTP", "Response", "." ]
public class ServiceAvailabilityHandler implements HttpHandler { private static final Logger log = Logger.getLogger(ServiceAvailabilityHandler.class); private static final String JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE = "jboss.as:deployment=%s"; private static final int SERVICE_UNVAILABLE = 503; private final AtomicBoolean applicationReady = new AtomicBoolean(false); private Pattern pathPattern; private String pathPrefixPattern; private String deploymentName; private volatile boolean intialized = false; private final HttpHandler next; public ServiceAvailabilityHandler(HttpHandler next) { this.next = next; } public void handleRequest(HttpServerExchange exchange) throws Exception { // lazy initialize on first request //TODO figure out how to initialize an Undertow Handler after construction to get rid of this if (!intialized) { init(); intialized = true; } if (!pathPattern.matcher(exchange.getRequestPath()).matches()) { next.handleRequest(exchange); return; } if (applicationReady.get()) { next.handleRequest(exchange); return; } exchange.setStatusCode(SERVICE_UNVAILABLE); } private void init() { this.pathPattern = Pattern.compile(this.pathPrefixPattern); String deploymentObjectName = String.format(JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE, this.deploymentName); ApplicationAvailabilityChangeNotificationListener listener = new ApplicationAvailabilityChangeNotificationListener(deploymentObjectName, applicationReady); if (!ApplicationAvailabilityMbeanRegistrar.register(deploymentObjectName, listener)) { log.warn("Initialization of application availability detection failed! Marking the application as ready."); applicationReady.set(true); } } public String getPathPrefixPattern() { return pathPrefixPattern; } public void setPathPrefixPattern(String pathPrefixPattern) { this.pathPrefixPattern = pathPrefixPattern; } public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } static class ApplicationAvailabilityMbeanRegistrar { static boolean register(String objectName, NotificationListener listener) { try { ObjectName on = new ObjectName(objectName); ManagementFactory .getPlatformMBeanServer() .addNotificationListener(on, listener, null, null); return true; } catch (MalformedObjectNameException mone) { log.warn("Could not register application-availability ObjectName: {}", objectName, mone); } catch (InstanceNotFoundException infe) { log.warn("Could not find object instance with ObjectName: {}", objectName, infe); } return false; } } static class ApplicationAvailabilityChangeNotificationListener implements NotificationListener { private static final String DEPLOYMENT_DEPLOYED = "deployment-deployed"; private final AtomicBoolean applicationReady; private final String objectName; private ApplicationAvailabilityChangeNotificationListener(String objectName, AtomicBoolean applicationReady) { this.objectName = objectName; this.applicationReady = applicationReady; } public void handleNotification(Notification notification, Object handback) { if (!notification.getSource().toString().equals(objectName)) { return; } if (!DEPLOYMENT_DEPLOYED.equals(notification.getType())) { return; } log.warn("Detected application availability changed to ready! Marking the application as ready."); applicationReady.set(true); } } }
[ "public", "class", "ServiceAvailabilityHandler", "implements", "HttpHandler", "{", "private", "static", "final", "Logger", "log", "=", "Logger", ".", "getLogger", "(", "ServiceAvailabilityHandler", ".", "class", ")", ";", "private", "static", "final", "String", "JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE", "=", "\"", "jboss.as:deployment=%s", "\"", ";", "private", "static", "final", "int", "SERVICE_UNVAILABLE", "=", "503", ";", "private", "final", "AtomicBoolean", "applicationReady", "=", "new", "AtomicBoolean", "(", "false", ")", ";", "private", "Pattern", "pathPattern", ";", "private", "String", "pathPrefixPattern", ";", "private", "String", "deploymentName", ";", "private", "volatile", "boolean", "intialized", "=", "false", ";", "private", "final", "HttpHandler", "next", ";", "public", "ServiceAvailabilityHandler", "(", "HttpHandler", "next", ")", "{", "this", ".", "next", "=", "next", ";", "}", "public", "void", "handleRequest", "(", "HttpServerExchange", "exchange", ")", "throws", "Exception", "{", "if", "(", "!", "intialized", ")", "{", "init", "(", ")", ";", "intialized", "=", "true", ";", "}", "if", "(", "!", "pathPattern", ".", "matcher", "(", "exchange", ".", "getRequestPath", "(", ")", ")", ".", "matches", "(", ")", ")", "{", "next", ".", "handleRequest", "(", "exchange", ")", ";", "return", ";", "}", "if", "(", "applicationReady", ".", "get", "(", ")", ")", "{", "next", ".", "handleRequest", "(", "exchange", ")", ";", "return", ";", "}", "exchange", ".", "setStatusCode", "(", "SERVICE_UNVAILABLE", ")", ";", "}", "private", "void", "init", "(", ")", "{", "this", ".", "pathPattern", "=", "Pattern", ".", "compile", "(", "this", ".", "pathPrefixPattern", ")", ";", "String", "deploymentObjectName", "=", "String", ".", "format", "(", "JBOSS_AS_DEPLOYMENT_OBJECT_NAME_TEMPLATE", ",", "this", ".", "deploymentName", ")", ";", "ApplicationAvailabilityChangeNotificationListener", "listener", "=", "new", "ApplicationAvailabilityChangeNotificationListener", "(", "deploymentObjectName", ",", "applicationReady", ")", ";", "if", "(", "!", "ApplicationAvailabilityMbeanRegistrar", ".", "register", "(", "deploymentObjectName", ",", "listener", ")", ")", "{", "log", ".", "warn", "(", "\"", "Initialization of application availability detection failed! Marking the application as ready.", "\"", ")", ";", "applicationReady", ".", "set", "(", "true", ")", ";", "}", "}", "public", "String", "getPathPrefixPattern", "(", ")", "{", "return", "pathPrefixPattern", ";", "}", "public", "void", "setPathPrefixPattern", "(", "String", "pathPrefixPattern", ")", "{", "this", ".", "pathPrefixPattern", "=", "pathPrefixPattern", ";", "}", "public", "String", "getDeploymentName", "(", ")", "{", "return", "deploymentName", ";", "}", "public", "void", "setDeploymentName", "(", "String", "deploymentName", ")", "{", "this", ".", "deploymentName", "=", "deploymentName", ";", "}", "static", "class", "ApplicationAvailabilityMbeanRegistrar", "{", "static", "boolean", "register", "(", "String", "objectName", ",", "NotificationListener", "listener", ")", "{", "try", "{", "ObjectName", "on", "=", "new", "ObjectName", "(", "objectName", ")", ";", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ".", "addNotificationListener", "(", "on", ",", "listener", ",", "null", ",", "null", ")", ";", "return", "true", ";", "}", "catch", "(", "MalformedObjectNameException", "mone", ")", "{", "log", ".", "warn", "(", "\"", "Could not register application-availability ObjectName: {}", "\"", ",", "objectName", ",", "mone", ")", ";", "}", "catch", "(", "InstanceNotFoundException", "infe", ")", "{", "log", ".", "warn", "(", "\"", "Could not find object instance with ObjectName: {}", "\"", ",", "objectName", ",", "infe", ")", ";", "}", "return", "false", ";", "}", "}", "static", "class", "ApplicationAvailabilityChangeNotificationListener", "implements", "NotificationListener", "{", "private", "static", "final", "String", "DEPLOYMENT_DEPLOYED", "=", "\"", "deployment-deployed", "\"", ";", "private", "final", "AtomicBoolean", "applicationReady", ";", "private", "final", "String", "objectName", ";", "private", "ApplicationAvailabilityChangeNotificationListener", "(", "String", "objectName", ",", "AtomicBoolean", "applicationReady", ")", "{", "this", ".", "objectName", "=", "objectName", ";", "this", ".", "applicationReady", "=", "applicationReady", ";", "}", "public", "void", "handleNotification", "(", "Notification", "notification", ",", "Object", "handback", ")", "{", "if", "(", "!", "notification", ".", "getSource", "(", ")", ".", "toString", "(", ")", ".", "equals", "(", "objectName", ")", ")", "{", "return", ";", "}", "if", "(", "!", "DEPLOYMENT_DEPLOYED", ".", "equals", "(", "notification", ".", "getType", "(", ")", ")", ")", "{", "return", ";", "}", "log", ".", "warn", "(", "\"", "Detected application availability changed to ready! Marking the application as ready.", "\"", ")", ";", "applicationReady", ".", "set", "(", "true", ")", ";", "}", "}", "}" ]
Special @link {@link HttpHandler} Filter which returns HTTP Status Code {@code 503 Service Unvailable} until a given deployment unit is successfully deployed, from then on the application will control the HTTP Response.
[ "Special", "@link", "{", "@link", "HttpHandler", "}", "Filter", "which", "returns", "HTTP", "Status", "Code", "{", "@code", "503", "Service", "Unvailable", "}", "until", "a", "given", "deployment", "unit", "is", "successfully", "deployed", "from", "then", "on", "the", "application", "will", "control", "the", "HTTP", "Response", "." ]
[ "// lazy initialize on first request", "//TODO figure out how to initialize an Undertow Handler after construction to get rid of this" ]
[ { "param": "HttpHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "HttpHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
849d899f2cc6f5b981fef44ad3ee3a85aabeeb1d
aneeshpadmanabhan/secrets-proxy
src/main/java/com/oneops/proxy/model/SecretRequest.java
[ "Apache-2.0" ]
Java
SecretRequest
/** * Keywhiz secret request. * * @author Suresh */
Keywhiz secret request. @author Suresh
[ "Keywhiz", "secret", "request", ".", "@author", "Suresh" ]
@JsonIgnoreProperties(ignoreUnknown = true) public class SecretRequest { @JsonProperty @ApiModelProperty(example = "[BASE64 encoded secret data]") private String content; @JsonProperty @ApiModelProperty(example = "Uploaded by OneOps") private String description; @JsonProperty private Map<String, String> metadata; /** * Secret expiry. For keystores, it is recommended to use the expiry of the earliest key. Format * should be 2006-01-02T15:04:05Z or seconds since epoch. */ @JsonProperty @ApiModelProperty(example = "0") private long expiry; @JsonProperty @ApiModelProperty(example = "secret") private String type; public SecretRequest() {} public SecretRequest( String content, String description, Map<String, String> metadata, long expiry, String type) { this.content = content; this.description = description; this.metadata = metadata; this.expiry = expiry; this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, String> getMetadata() { return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public long getExpiry() { return expiry; } public void setExpiry(long expiry) { this.expiry = expiry; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "SecretRequest{" + "content=******" + ", description='" + description + '\'' + ", metadata=" + metadata + ", expiry=" + expiry + ", type='" + type + '\'' + '}'; } }
[ "@", "JsonIgnoreProperties", "(", "ignoreUnknown", "=", "true", ")", "public", "class", "SecretRequest", "{", "@", "JsonProperty", "@", "ApiModelProperty", "(", "example", "=", "\"", "[BASE64 encoded secret data]", "\"", ")", "private", "String", "content", ";", "@", "JsonProperty", "@", "ApiModelProperty", "(", "example", "=", "\"", "Uploaded by OneOps", "\"", ")", "private", "String", "description", ";", "@", "JsonProperty", "private", "Map", "<", "String", ",", "String", ">", "metadata", ";", "/**\n * Secret expiry. For keystores, it is recommended to use the expiry of the earliest key. Format\n * should be 2006-01-02T15:04:05Z or seconds since epoch.\n */", "@", "JsonProperty", "@", "ApiModelProperty", "(", "example", "=", "\"", "0", "\"", ")", "private", "long", "expiry", ";", "@", "JsonProperty", "@", "ApiModelProperty", "(", "example", "=", "\"", "secret", "\"", ")", "private", "String", "type", ";", "public", "SecretRequest", "(", ")", "{", "}", "public", "SecretRequest", "(", "String", "content", ",", "String", "description", ",", "Map", "<", "String", ",", "String", ">", "metadata", ",", "long", "expiry", ",", "String", "type", ")", "{", "this", ".", "content", "=", "content", ";", "this", ".", "description", "=", "description", ";", "this", ".", "metadata", "=", "metadata", ";", "this", ".", "expiry", "=", "expiry", ";", "this", ".", "type", "=", "type", ";", "}", "public", "String", "getContent", "(", ")", "{", "return", "content", ";", "}", "public", "void", "setContent", "(", "String", "content", ")", "{", "this", ".", "content", "=", "content", ";", "}", "public", "String", "getDescription", "(", ")", "{", "return", "description", ";", "}", "public", "void", "setDescription", "(", "String", "description", ")", "{", "this", ".", "description", "=", "description", ";", "}", "public", "Map", "<", "String", ",", "String", ">", "getMetadata", "(", ")", "{", "return", "metadata", ";", "}", "public", "void", "setMetadata", "(", "Map", "<", "String", ",", "String", ">", "metadata", ")", "{", "this", ".", "metadata", "=", "metadata", ";", "}", "public", "long", "getExpiry", "(", ")", "{", "return", "expiry", ";", "}", "public", "void", "setExpiry", "(", "long", "expiry", ")", "{", "this", ".", "expiry", "=", "expiry", ";", "}", "public", "String", "getType", "(", ")", "{", "return", "type", ";", "}", "public", "void", "setType", "(", "String", "type", ")", "{", "this", ".", "type", "=", "type", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "SecretRequest{", "\"", "+", "\"", "content=******", "\"", "+", "\"", ", description='", "\"", "+", "description", "+", "'\\''", "+", "\"", ", metadata=", "\"", "+", "metadata", "+", "\"", ", expiry=", "\"", "+", "expiry", "+", "\"", ", type='", "\"", "+", "type", "+", "'\\''", "+", "'}'", ";", "}", "}" ]
Keywhiz secret request.
[ "Keywhiz", "secret", "request", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84ada930db97ab363c304e7a36f955739c88f6db
thekalpesh7/qa-automation-accelerator
src/main/java/com/mindstix/cb/utils/RedisUtility.java
[ "MIT" ]
Java
RedisUtility
/** * This utility handles all the Redis database and Jedis related operations. * Following operations are handled by RedisUtility.java * <ol> * <li>Distributed coordination for running tests with specific set of users. * </li> * <li>Acting as a temporary storage for report data and notification stages in * Jenkins pipeline</li> * </ol> * Please refer following URLs for more information about Redis and Jedis * <ol> * <li><a href="https://redis.io/commands">Redis Commands</a></li> * <li><a href="http://www.baeldung.com/jedis-java-redis-client-library"> Jedis: * java redis client library</a></li> * </ol> * * @author Mindstix */
This utility handles all the Redis database and Jedis related operations. Following operations are handled by RedisUtility.java Distributed coordination for running tests with specific set of users. Acting as a temporary storage for report data and notification stages in Jenkins pipeline Please refer following URLs for more information about Redis and Jedis Redis Commands Jedis: java redis client library @author Mindstix
[ "This", "utility", "handles", "all", "the", "Redis", "database", "and", "Jedis", "related", "operations", ".", "Following", "operations", "are", "handled", "by", "RedisUtility", ".", "java", "Distributed", "coordination", "for", "running", "tests", "with", "specific", "set", "of", "users", ".", "Acting", "as", "a", "temporary", "storage", "for", "report", "data", "and", "notification", "stages", "in", "Jenkins", "pipeline", "Please", "refer", "following", "URLs", "for", "more", "information", "about", "Redis", "and", "Jedis", "Redis", "Commands", "Jedis", ":", "java", "redis", "client", "library", "@author", "Mindstix" ]
public final class RedisUtility { private final static Logger LOGGER = LoggerFactory.getLogger(RedisUtility.class); private static JedisPool pool; private static Jedis jedis; private static boolean isRedisAlive; /** * private constructor */ private RedisUtility() { } static { configureJedisPool(); } /** * This method is used to configure Jedis pool. It configures the host and * port of Jedis pool. It takes redisHost from command line. If not passed from command line * it takes localhost as default redis host. You can change the default redisHost in build.gradle. * For remaining Redis configurations please @see Constants.java * */ private static void configureJedisPool() { try { LOGGER.info("Configuring jedis pool"); pool = new JedisPool(System.getProperty("env.redisHost"), Constants.REDIS_PORT); jedis = pool.getResource(); isRedisAlive = true; } catch (Exception e) { LOGGER.error("Failed to configure redis", e); isRedisAlive = false; } } /** * This method is used to acquire username which are stored in Redis set. If * usernames are available in set then it randomly pops one user else it * waits for 10 minutes for user to be available. If after 10 minutes user * is not available then it throws RunTimeException. It takes set-key as * parameter * * @param userKey * @return userName */ public static String acquireUser(String userKey) { if (!isRedisAlive) { String userName = Constants.FALLBACK_USER; LOGGER.warn("Returning fallback user {} as jedis is not configured", userName); return userName; } LOGGER.info("Acquiring user"); String userName = null; List<Object> result = null; Transaction transaction; for (int i = 0; i < Constants.WAIT_TIMEOUT_IN_SEC; i++) { transaction = jedis.multi(); transaction.spop(userKey); result = transaction.exec(); if (result != null) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.error("InterruptedException", e); } } if (result == null) { throw new RuntimeException("Time limit exceeded to acquire the user"); } else { userName = result.get(0).toString(); } LOGGER.info("User {} acquired", userName); return userName; } /** * This method is used to add or release user back to redis set. It takes * userKey and username as parameter. * * @param userKey * @param userName */ public static void releaseUser(String userKey, String userName) { if (userName != null && isRedisAlive) { LOGGER.info("Releasing user {}.", userName); Transaction transaction = jedis.multi(); transaction.sadd(userKey, userName); transaction.exec(); LOGGER.info("User {} released.", userName); } } }
[ "public", "final", "class", "RedisUtility", "{", "private", "final", "static", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "RedisUtility", ".", "class", ")", ";", "private", "static", "JedisPool", "pool", ";", "private", "static", "Jedis", "jedis", ";", "private", "static", "boolean", "isRedisAlive", ";", "/**\n\t * private constructor\n\t */", "private", "RedisUtility", "(", ")", "{", "}", "static", "{", "configureJedisPool", "(", ")", ";", "}", "/**\n\t * This method is used to configure Jedis pool. It configures the host and\n\t * port of Jedis pool. It takes redisHost from command line. If not passed from command line \n\t * it takes localhost as default redis host. You can change the default redisHost in build.gradle.\n\t * For remaining Redis configurations please @see Constants.java\n\t * \n\t */", "private", "static", "void", "configureJedisPool", "(", ")", "{", "try", "{", "LOGGER", ".", "info", "(", "\"", "Configuring jedis pool", "\"", ")", ";", "pool", "=", "new", "JedisPool", "(", "System", ".", "getProperty", "(", "\"", "env.redisHost", "\"", ")", ",", "Constants", ".", "REDIS_PORT", ")", ";", "jedis", "=", "pool", ".", "getResource", "(", ")", ";", "isRedisAlive", "=", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "Failed to configure redis", "\"", ",", "e", ")", ";", "isRedisAlive", "=", "false", ";", "}", "}", "/**\n\t * This method is used to acquire username which are stored in Redis set. If\n\t * usernames are available in set then it randomly pops one user else it\n\t * waits for 10 minutes for user to be available. If after 10 minutes user\n\t * is not available then it throws RunTimeException. It takes set-key as\n\t * parameter\n\t * \n\t * @param userKey\n\t * @return userName\n\t */", "public", "static", "String", "acquireUser", "(", "String", "userKey", ")", "{", "if", "(", "!", "isRedisAlive", ")", "{", "String", "userName", "=", "Constants", ".", "FALLBACK_USER", ";", "LOGGER", ".", "warn", "(", "\"", "Returning fallback user {} as jedis is not configured", "\"", ",", "userName", ")", ";", "return", "userName", ";", "}", "LOGGER", ".", "info", "(", "\"", "Acquiring user", "\"", ")", ";", "String", "userName", "=", "null", ";", "List", "<", "Object", ">", "result", "=", "null", ";", "Transaction", "transaction", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "Constants", ".", "WAIT_TIMEOUT_IN_SEC", ";", "i", "++", ")", "{", "transaction", "=", "jedis", ".", "multi", "(", ")", ";", "transaction", ".", "spop", "(", "userKey", ")", ";", "result", "=", "transaction", ".", "exec", "(", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "break", ";", "}", "try", "{", "Thread", ".", "sleep", "(", "1000", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOGGER", ".", "error", "(", "\"", "InterruptedException", "\"", ",", "e", ")", ";", "}", "}", "if", "(", "result", "==", "null", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Time limit exceeded to acquire the user", "\"", ")", ";", "}", "else", "{", "userName", "=", "result", ".", "get", "(", "0", ")", ".", "toString", "(", ")", ";", "}", "LOGGER", ".", "info", "(", "\"", "User {} acquired", "\"", ",", "userName", ")", ";", "return", "userName", ";", "}", "/**\n\t * This method is used to add or release user back to redis set. It takes\n\t * userKey and username as parameter.\n\t * \n\t * @param userKey\n\t * @param userName\n\t */", "public", "static", "void", "releaseUser", "(", "String", "userKey", ",", "String", "userName", ")", "{", "if", "(", "userName", "!=", "null", "&&", "isRedisAlive", ")", "{", "LOGGER", ".", "info", "(", "\"", "Releasing user {}.", "\"", ",", "userName", ")", ";", "Transaction", "transaction", "=", "jedis", ".", "multi", "(", ")", ";", "transaction", ".", "sadd", "(", "userKey", ",", "userName", ")", ";", "transaction", ".", "exec", "(", ")", ";", "LOGGER", ".", "info", "(", "\"", "User {} released.", "\"", ",", "userName", ")", ";", "}", "}", "}" ]
This utility handles all the Redis database and Jedis related operations.
[ "This", "utility", "handles", "all", "the", "Redis", "database", "and", "Jedis", "related", "operations", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84b1be566fe1d9da193edfa5525d366afe97fff4
Ali-RS/SimEthereal
src/main/java/com/simsilica/ethereal/zone/StateCollector.java
[ "BSD-3-Clause" ]
Java
StateCollector
/** * Uses a background thread to periodically collect the accumulated * state for the zones and send the blocks of state to zone state * listeners. * * @author Paul Speed */
Uses a background thread to periodically collect the accumulated state for the zones and send the blocks of state to zone state listeners. @author Paul Speed
[ "Uses", "a", "background", "thread", "to", "periodically", "collect", "the", "accumulated", "state", "for", "the", "zones", "and", "send", "the", "blocks", "of", "state", "to", "zone", "state", "listeners", ".", "@author", "Paul", "Speed" ]
public class StateCollector { static Logger log = LoggerFactory.getLogger(StateCollector.class); private static final long NANOS_PER_SEC = 1000000000L; public static final long DEFAULT_PERIOD = NANOS_PER_SEC / 20; private ZoneManager zones; private long collectionPeriod; private long idleSleepTime = 1; // for our standard 20 FPS that's more than fine private final Runner runner = new Runner(); private final Set<StateListener> listeners = new CopyOnWriteArraySet<>(); private final ConcurrentLinkedQueue<StateListener> removed = new ConcurrentLinkedQueue<>(); /** * This is the actual zone interest management. It's only used by the * background thread which is why it is unsynchronized. All interactio * is done through the listeners set and removed queue. */ private final Map<ZoneKey,List<StateListener>> zoneListeners = new HashMap<>(); public StateCollector( ZoneManager zones ) { this(zones, DEFAULT_PERIOD); } public StateCollector( ZoneManager zones, long collectionPeriod ) { this.zones = zones; this.collectionPeriod = collectionPeriod == 0 ? DEFAULT_PERIOD : collectionPeriod; } public void start() { log.info("Starting state collector."); runner.start(); } public void shutdown() { log.info("Shutting down state collector."); runner.close(); } /** * Adds a listener that self-indicates which specific zones * it is interested in from one frame to the next. This is necessary * so that it syncs with the background state collection in a way * that does not cause partial state, etc... it's also nicer to * to the background threads and synchronization if zone interest * is synched with updates. */ public void addListener( StateListener l ) { listeners.add(l); } public void removeListener( StateListener l ) { listeners.remove(l); removed.add(l); } /** * Sets the sleep() time for the state collector's idle periods. * This defaults to 1 which keeps the CPU happier while also providing * timely checks against the interval time. However, for higher rates of * state collection (lower collectionPeriods such as 16 ms or 60 FPS) on windows, * sleep(1) may take longer than 1/60th of a second or close enough to still * cause collection frame drops. In that case, it can be configured to 0 which * should provide timelier updates. * Set to -1 to avoid sleeping at all in which case the thread will consume 100% * of a single core in order to busy wait between collection intervals. */ public void setIdleSleepTime( long millis ) { this.idleSleepTime = millis; } public long getIdleSleepTime() { return idleSleepTime; } protected List<StateListener> getListeners( ZoneKey key, boolean create ) { List<StateListener> result = zoneListeners.get(key); if( result == null && create ) { result = new ArrayList<>(); zoneListeners.put(key, result); } return result; } protected void watch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("watch(" + key + ", " + l + ")"); } getListeners(key, true).add(l); } protected void unwatch( ZoneKey key, StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatch(" + key + ", " + l + ")" ); } List<StateListener> list = getListeners(key, false); if( list == null ) { return; } list.remove(l); } protected void unwatchAll( StateListener l ) { if( log.isTraceEnabled() ) { log.trace("unwatchAll(" + l + ")" ); } for( List<StateListener> list : zoneListeners.values() ) { list.remove(l); } } /** * Called from the background thread when it first starts up. */ protected void initialize() { // Let the zone manager know that it can start collecting history zones.setCollectHistory(true); } protected void publish( StateBlock b ) { List<StateListener> list = getListeners(b.getZone(), false); if( list == null ) { return; } for( StateListener l : list ) { l.stateChanged(b); } } /** * Adjusts the per-listener zone interest based on latest * listener state, then publishes the state frame to all * interested listeners. */ protected void publishFrame( StateFrame frame ) { log.trace("publishFrame()"); for( StateListener l : listeners ) { if( l.hasChangedZones() ) { List<ZoneKey> exited = l.getExitedZones(); for( ZoneKey k : exited ) { unwatch( k, l ); } List<ZoneKey> entered = l.getEnteredZones(); for( ZoneKey k : entered ) { watch( k, l ); } } l.beginFrame(frame.getTime()); } for( StateBlock b : frame ) { publish( b ); } for( StateListener l : listeners ) { l.endFrame(frame.getTime()); } log.trace("end publishFrame()"); } /** * Called by the background thread to collect all * of the accumulated state since the last collection and * distribute it to the state listeners. This is called * once per "collectionPeriod". */ protected void collect() { log.trace("collect()"); // Purge any pending removals StateListener remove; while( (remove = removed.poll()) != null ) { unwatchAll(remove); } // Collect all state since the last time we asked // long start = System.nanoTime(); StateFrame[] frames = zones.purgeState(); // long end = System.nanoTime(); // System.out.println( "State purged in:" + ((end - start)/1000000.0) + " ms" ); for( StateListener l : listeners ) { l.beginFrameBlock(); } // start = end; for( StateFrame f : frames ) { if( f == null ) { continue; } publishFrame(f); } for( StateListener l : listeners ) { l.endFrameBlock(); } // end = System.nanoTime(); // System.out.println( "State published in:" + ((end - start)/1000000.0) + " ms" ); log.trace("end collect()"); } /** * Called by the background thread when it is shutting down. * Currently does nothing. */ protected void terminate() { // Let the zone manager know that it should stop collecting // history because we won't be purging it anymore. zones.setCollectHistory(false); } protected void collectionError( Exception e ) { log.error("Collection error", e); } private class Runner extends Thread { private final AtomicBoolean go = new AtomicBoolean(true); public Runner() { setName( "StateCollectionThread" ); //setPriority( Thread.MAX_PRIORITY ); } public void close() { go.set(false); try { join(); } catch( InterruptedException e ) { throw new RuntimeException( "Interrupted while waiting for physic thread to complete.", e ); } } @Override public void run() { initialize(); long lastTime = System.nanoTime(); long counter = 0; long nextCountTime = lastTime + 1000000000L; while( go.get() ) { long time = System.nanoTime(); long delta = time - lastTime; if( delta >= collectionPeriod ) { // Time to collect lastTime = time; try { collect(); counter++; //long end = System.nanoTime(); //delta = end - time; } catch( Exception e ) { collectionError(e); } if( lastTime > nextCountTime ) { if( counter < 20 ) { System.out.println("collect underflow FPS:" + counter); } //System.out.println("collect FPS:" + counter); counter = 0; nextCountTime = lastTime + 1000000000L; } // Don't sleep when we've processed in case we need // to process again immediately. continue; } // Wait just a little. This is an important enough thread // that we'll poll instead of smart-sleep. try { if( idleSleepTime > 0 ) { Thread.sleep(idleSleepTime); } } catch( InterruptedException e ) { throw new RuntimeException("Interrupted sleeping", e); } } terminate(); } } }
[ "public", "class", "StateCollector", "{", "static", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "StateCollector", ".", "class", ")", ";", "private", "static", "final", "long", "NANOS_PER_SEC", "=", "1000000000L", ";", "public", "static", "final", "long", "DEFAULT_PERIOD", "=", "NANOS_PER_SEC", "/", "20", ";", "private", "ZoneManager", "zones", ";", "private", "long", "collectionPeriod", ";", "private", "long", "idleSleepTime", "=", "1", ";", "private", "final", "Runner", "runner", "=", "new", "Runner", "(", ")", ";", "private", "final", "Set", "<", "StateListener", ">", "listeners", "=", "new", "CopyOnWriteArraySet", "<", ">", "(", ")", ";", "private", "final", "ConcurrentLinkedQueue", "<", "StateListener", ">", "removed", "=", "new", "ConcurrentLinkedQueue", "<", ">", "(", ")", ";", "/**\r\n * This is the actual zone interest management. It's only used by the\r\n * background thread which is why it is unsynchronized. All interactio\r\n * is done through the listeners set and removed queue.\r\n */", "private", "final", "Map", "<", "ZoneKey", ",", "List", "<", "StateListener", ">", ">", "zoneListeners", "=", "new", "HashMap", "<", ">", "(", ")", ";", "public", "StateCollector", "(", "ZoneManager", "zones", ")", "{", "this", "(", "zones", ",", "DEFAULT_PERIOD", ")", ";", "}", "public", "StateCollector", "(", "ZoneManager", "zones", ",", "long", "collectionPeriod", ")", "{", "this", ".", "zones", "=", "zones", ";", "this", ".", "collectionPeriod", "=", "collectionPeriod", "==", "0", "?", "DEFAULT_PERIOD", ":", "collectionPeriod", ";", "}", "public", "void", "start", "(", ")", "{", "log", ".", "info", "(", "\"", "Starting state collector.", "\"", ")", ";", "runner", ".", "start", "(", ")", ";", "}", "public", "void", "shutdown", "(", ")", "{", "log", ".", "info", "(", "\"", "Shutting down state collector.", "\"", ")", ";", "runner", ".", "close", "(", ")", ";", "}", "/**\r\n * Adds a listener that self-indicates which specific zones\r\n * it is interested in from one frame to the next. This is necessary\r\n * so that it syncs with the background state collection in a way\r\n * that does not cause partial state, etc... it's also nicer to\r\n * to the background threads and synchronization if zone interest\r\n * is synched with updates.\r\n */", "public", "void", "addListener", "(", "StateListener", "l", ")", "{", "listeners", ".", "add", "(", "l", ")", ";", "}", "public", "void", "removeListener", "(", "StateListener", "l", ")", "{", "listeners", ".", "remove", "(", "l", ")", ";", "removed", ".", "add", "(", "l", ")", ";", "}", "/**\r\n * Sets the sleep() time for the state collector's idle periods.\r\n * This defaults to 1 which keeps the CPU happier while also providing\r\n * timely checks against the interval time. However, for higher rates of \r\n * state collection (lower collectionPeriods such as 16 ms or 60 FPS) on windows, \r\n * sleep(1) may take longer than 1/60th of a second or close enough to still \r\n * cause collection frame drops. In that case, it can be configured to 0 which \r\n * should provide timelier updates.\r\n * Set to -1 to avoid sleeping at all in which case the thread will consume 100%\r\n * of a single core in order to busy wait between collection intervals.\r\n */", "public", "void", "setIdleSleepTime", "(", "long", "millis", ")", "{", "this", ".", "idleSleepTime", "=", "millis", ";", "}", "public", "long", "getIdleSleepTime", "(", ")", "{", "return", "idleSleepTime", ";", "}", "protected", "List", "<", "StateListener", ">", "getListeners", "(", "ZoneKey", "key", ",", "boolean", "create", ")", "{", "List", "<", "StateListener", ">", "result", "=", "zoneListeners", ".", "get", "(", "key", ")", ";", "if", "(", "result", "==", "null", "&&", "create", ")", "{", "result", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "zoneListeners", ".", "put", "(", "key", ",", "result", ")", ";", "}", "return", "result", ";", "}", "protected", "void", "watch", "(", "ZoneKey", "key", ",", "StateListener", "l", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"", "watch(", "\"", "+", "key", "+", "\"", ", ", "\"", "+", "l", "+", "\"", ")", "\"", ")", ";", "}", "getListeners", "(", "key", ",", "true", ")", ".", "add", "(", "l", ")", ";", "}", "protected", "void", "unwatch", "(", "ZoneKey", "key", ",", "StateListener", "l", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"", "unwatch(", "\"", "+", "key", "+", "\"", ", ", "\"", "+", "l", "+", "\"", ")", "\"", ")", ";", "}", "List", "<", "StateListener", ">", "list", "=", "getListeners", "(", "key", ",", "false", ")", ";", "if", "(", "list", "==", "null", ")", "{", "return", ";", "}", "list", ".", "remove", "(", "l", ")", ";", "}", "protected", "void", "unwatchAll", "(", "StateListener", "l", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"", "unwatchAll(", "\"", "+", "l", "+", "\"", ")", "\"", ")", ";", "}", "for", "(", "List", "<", "StateListener", ">", "list", ":", "zoneListeners", ".", "values", "(", ")", ")", "{", "list", ".", "remove", "(", "l", ")", ";", "}", "}", "/**\r\n * Called from the background thread when it first starts up.\r\n */", "protected", "void", "initialize", "(", ")", "{", "zones", ".", "setCollectHistory", "(", "true", ")", ";", "}", "protected", "void", "publish", "(", "StateBlock", "b", ")", "{", "List", "<", "StateListener", ">", "list", "=", "getListeners", "(", "b", ".", "getZone", "(", ")", ",", "false", ")", ";", "if", "(", "list", "==", "null", ")", "{", "return", ";", "}", "for", "(", "StateListener", "l", ":", "list", ")", "{", "l", ".", "stateChanged", "(", "b", ")", ";", "}", "}", "/**\r\n * Adjusts the per-listener zone interest based on latest\r\n * listener state, then publishes the state frame to all\r\n * interested listeners. \r\n */", "protected", "void", "publishFrame", "(", "StateFrame", "frame", ")", "{", "log", ".", "trace", "(", "\"", "publishFrame()", "\"", ")", ";", "for", "(", "StateListener", "l", ":", "listeners", ")", "{", "if", "(", "l", ".", "hasChangedZones", "(", ")", ")", "{", "List", "<", "ZoneKey", ">", "exited", "=", "l", ".", "getExitedZones", "(", ")", ";", "for", "(", "ZoneKey", "k", ":", "exited", ")", "{", "unwatch", "(", "k", ",", "l", ")", ";", "}", "List", "<", "ZoneKey", ">", "entered", "=", "l", ".", "getEnteredZones", "(", ")", ";", "for", "(", "ZoneKey", "k", ":", "entered", ")", "{", "watch", "(", "k", ",", "l", ")", ";", "}", "}", "l", ".", "beginFrame", "(", "frame", ".", "getTime", "(", ")", ")", ";", "}", "for", "(", "StateBlock", "b", ":", "frame", ")", "{", "publish", "(", "b", ")", ";", "}", "for", "(", "StateListener", "l", ":", "listeners", ")", "{", "l", ".", "endFrame", "(", "frame", ".", "getTime", "(", ")", ")", ";", "}", "log", ".", "trace", "(", "\"", "end publishFrame()", "\"", ")", ";", "}", "/**\r\n * Called by the background thread to collect all\r\n * of the accumulated state since the last collection and\r\n * distribute it to the state listeners. This is called\r\n * once per \"collectionPeriod\".\r\n */", "protected", "void", "collect", "(", ")", "{", "log", ".", "trace", "(", "\"", "collect()", "\"", ")", ";", "StateListener", "remove", ";", "while", "(", "(", "remove", "=", "removed", ".", "poll", "(", ")", ")", "!=", "null", ")", "{", "unwatchAll", "(", "remove", ")", ";", "}", "StateFrame", "[", "]", "frames", "=", "zones", ".", "purgeState", "(", ")", ";", "for", "(", "StateListener", "l", ":", "listeners", ")", "{", "l", ".", "beginFrameBlock", "(", ")", ";", "}", "for", "(", "StateFrame", "f", ":", "frames", ")", "{", "if", "(", "f", "==", "null", ")", "{", "continue", ";", "}", "publishFrame", "(", "f", ")", ";", "}", "for", "(", "StateListener", "l", ":", "listeners", ")", "{", "l", ".", "endFrameBlock", "(", ")", ";", "}", "log", ".", "trace", "(", "\"", "end collect()", "\"", ")", ";", "}", "/**\r\n * Called by the background thread when it is shutting down.\r\n * Currently does nothing.\r\n */", "protected", "void", "terminate", "(", ")", "{", "zones", ".", "setCollectHistory", "(", "false", ")", ";", "}", "protected", "void", "collectionError", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"", "Collection error", "\"", ",", "e", ")", ";", "}", "private", "class", "Runner", "extends", "Thread", "{", "private", "final", "AtomicBoolean", "go", "=", "new", "AtomicBoolean", "(", "true", ")", ";", "public", "Runner", "(", ")", "{", "setName", "(", "\"", "StateCollectionThread", "\"", ")", ";", "}", "public", "void", "close", "(", ")", "{", "go", ".", "set", "(", "false", ")", ";", "try", "{", "join", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Interrupted while waiting for physic thread to complete.", "\"", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "initialize", "(", ")", ";", "long", "lastTime", "=", "System", ".", "nanoTime", "(", ")", ";", "long", "counter", "=", "0", ";", "long", "nextCountTime", "=", "lastTime", "+", "1000000000L", ";", "while", "(", "go", ".", "get", "(", ")", ")", "{", "long", "time", "=", "System", ".", "nanoTime", "(", ")", ";", "long", "delta", "=", "time", "-", "lastTime", ";", "if", "(", "delta", ">=", "collectionPeriod", ")", "{", "lastTime", "=", "time", ";", "try", "{", "collect", "(", ")", ";", "counter", "++", ";", "}", "catch", "(", "Exception", "e", ")", "{", "collectionError", "(", "e", ")", ";", "}", "if", "(", "lastTime", ">", "nextCountTime", ")", "{", "if", "(", "counter", "<", "20", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "collect underflow FPS:", "\"", "+", "counter", ")", ";", "}", "counter", "=", "0", ";", "nextCountTime", "=", "lastTime", "+", "1000000000L", ";", "}", "continue", ";", "}", "try", "{", "if", "(", "idleSleepTime", ">", "0", ")", "{", "Thread", ".", "sleep", "(", "idleSleepTime", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Interrupted sleeping", "\"", ",", "e", ")", ";", "}", "}", "terminate", "(", ")", ";", "}", "}", "}" ]
Uses a background thread to periodically collect the accumulated state for the zones and send the blocks of state to zone state listeners.
[ "Uses", "a", "background", "thread", "to", "periodically", "collect", "the", "accumulated", "state", "for", "the", "zones", "and", "send", "the", "blocks", "of", "state", "to", "zone", "state", "listeners", "." ]
[ "// for our standard 20 FPS that's more than fine\r", "// Let the zone manager know that it can start collecting history\r", "// Purge any pending removals\r", "// Collect all state since the last time we asked \r", "// long start = System.nanoTime();\r", "// long end = System.nanoTime(); \r", "// System.out.println( \"State purged in:\" + ((end - start)/1000000.0) + \" ms\" );\r", "// start = end;\r", "// end = System.nanoTime(); \r", "// System.out.println( \"State published in:\" + ((end - start)/1000000.0) + \" ms\" );\r", "// Let the zone manager know that it should stop collecting\r", "// history because we won't be purging it anymore.\r", "//setPriority( Thread.MAX_PRIORITY ); \r", "// Time to collect \r", "//long end = System.nanoTime();\r", "//delta = end - time;\r", "//System.out.println(\"collect FPS:\" + counter); \r", "// Don't sleep when we've processed in case we need\r", "// to process again immediately.\r", "// Wait just a little. This is an important enough thread\r", "// that we'll poll instead of smart-sleep.\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84b22ca1b1fbfb8d25fbe26224b8c3d0cf81dcd0
mikiec84/DERT
dert/src/gov/nasa/arc/dert/action/mapelement/PlaceHereAction.java
[ "libtiff" ]
Java
PlaceHereAction
/** * Context menu item for placing a map element at a point in the landscape. User * is prompted with a list of map elements. * */
Context menu item for placing a map element at a point in the landscape. User is prompted with a list of map elements.
[ "Context", "menu", "item", "for", "placing", "a", "map", "element", "at", "a", "point", "in", "the", "landscape", ".", "User", "is", "prompted", "with", "a", "list", "of", "map", "elements", "." ]
public class PlaceHereAction extends MenuItemAction { private Vector3 position; /** * Constructor * * @param position */ public PlaceHereAction(ReadOnlyVector3 position) { super("Place Here ..."); this.position = new Vector3(position); } @Override protected void run() { // Get a list of movable map elements List<Spatial> landmarks = World.getInstance().getLandmarks().getChildren(); List<Spatial> tools = World.getInstance().getTools().getChildren(); ArrayList<Spatial> list = new ArrayList<Spatial>(); for (int i = 0; i < landmarks.size(); ++i) { list.add(landmarks.get(i)); } for (int i = 0; i < tools.size(); ++i) { Spatial spat = tools.get(i); if (!((spat instanceof Path) || (spat instanceof Profile))) { list.add(spat); } } if (list.size() == 0) { return; } // Sort the list alphabetically Collections.sort(list, new Comparator<Spatial>() { @Override public int compare(Spatial me1, Spatial me2) { return (me1.getName().compareTo(me2.getName())); } @Override public boolean equals(Object obj) { return (this == obj); } }); Spatial[] spatials = new Spatial[list.size()]; list.toArray(spatials); // ask user to select one Movable movable = (Movable) JOptionPane.showInputDialog(Dert.getMainWindow(), "Select a Map Element", "Place Here", JOptionPane.PLAIN_MESSAGE, null, spatials, spatials[0]); // move the map element and hand it to the undo handler if (movable != null) { Vector3 trans = new Vector3(movable.getTranslation()); movable.setLocation(position, false); movable.updateGeometricState(0); if (movable instanceof Landmark) ((Landmark)movable).update(Dert.getWorldView().getViewpoint().getCamera()); else if (movable instanceof Tool) ((Tool)movable).update(Dert.getWorldView().getViewpoint().getCamera()); UndoHandler.getInstance().addEdit(new MoveEdit(movable, trans)); } } }
[ "public", "class", "PlaceHereAction", "extends", "MenuItemAction", "{", "private", "Vector3", "position", ";", "/**\n\t * Constructor\n\t * \n\t * @param position\n\t */", "public", "PlaceHereAction", "(", "ReadOnlyVector3", "position", ")", "{", "super", "(", "\"", "Place Here ...", "\"", ")", ";", "this", ".", "position", "=", "new", "Vector3", "(", "position", ")", ";", "}", "@", "Override", "protected", "void", "run", "(", ")", "{", "List", "<", "Spatial", ">", "landmarks", "=", "World", ".", "getInstance", "(", ")", ".", "getLandmarks", "(", ")", ".", "getChildren", "(", ")", ";", "List", "<", "Spatial", ">", "tools", "=", "World", ".", "getInstance", "(", ")", ".", "getTools", "(", ")", ".", "getChildren", "(", ")", ";", "ArrayList", "<", "Spatial", ">", "list", "=", "new", "ArrayList", "<", "Spatial", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "landmarks", ".", "size", "(", ")", ";", "++", "i", ")", "{", "list", ".", "add", "(", "landmarks", ".", "get", "(", "i", ")", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tools", ".", "size", "(", ")", ";", "++", "i", ")", "{", "Spatial", "spat", "=", "tools", ".", "get", "(", "i", ")", ";", "if", "(", "!", "(", "(", "spat", "instanceof", "Path", ")", "||", "(", "spat", "instanceof", "Profile", ")", ")", ")", "{", "list", ".", "add", "(", "spat", ")", ";", "}", "}", "if", "(", "list", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "Collections", ".", "sort", "(", "list", ",", "new", "Comparator", "<", "Spatial", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Spatial", "me1", ",", "Spatial", "me2", ")", "{", "return", "(", "me1", ".", "getName", "(", ")", ".", "compareTo", "(", "me2", ".", "getName", "(", ")", ")", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "return", "(", "this", "==", "obj", ")", ";", "}", "}", ")", ";", "Spatial", "[", "]", "spatials", "=", "new", "Spatial", "[", "list", ".", "size", "(", ")", "]", ";", "list", ".", "toArray", "(", "spatials", ")", ";", "Movable", "movable", "=", "(", "Movable", ")", "JOptionPane", ".", "showInputDialog", "(", "Dert", ".", "getMainWindow", "(", ")", ",", "\"", "Select a Map Element", "\"", ",", "\"", "Place Here", "\"", ",", "JOptionPane", ".", "PLAIN_MESSAGE", ",", "null", ",", "spatials", ",", "spatials", "[", "0", "]", ")", ";", "if", "(", "movable", "!=", "null", ")", "{", "Vector3", "trans", "=", "new", "Vector3", "(", "movable", ".", "getTranslation", "(", ")", ")", ";", "movable", ".", "setLocation", "(", "position", ",", "false", ")", ";", "movable", ".", "updateGeometricState", "(", "0", ")", ";", "if", "(", "movable", "instanceof", "Landmark", ")", "(", "(", "Landmark", ")", "movable", ")", ".", "update", "(", "Dert", ".", "getWorldView", "(", ")", ".", "getViewpoint", "(", ")", ".", "getCamera", "(", ")", ")", ";", "else", "if", "(", "movable", "instanceof", "Tool", ")", "(", "(", "Tool", ")", "movable", ")", ".", "update", "(", "Dert", ".", "getWorldView", "(", ")", ".", "getViewpoint", "(", ")", ".", "getCamera", "(", ")", ")", ";", "UndoHandler", ".", "getInstance", "(", ")", ".", "addEdit", "(", "new", "MoveEdit", "(", "movable", ",", "trans", ")", ")", ";", "}", "}", "}" ]
Context menu item for placing a map element at a point in the landscape.
[ "Context", "menu", "item", "for", "placing", "a", "map", "element", "at", "a", "point", "in", "the", "landscape", "." ]
[ "// Get a list of movable map elements", "// Sort the list alphabetically", "// ask user to select one", "// move the map element and hand it to the undo handler" ]
[ { "param": "MenuItemAction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MenuItemAction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84b5e4d10ccf29baccb97de5a1b06c32e22e08e4
BaumannDaniel/sptemp_java
src/main/java/org/baumanndaniel/sptemp/zeit/TS_Unit.java
[ "MIT" ]
Java
TS_Unit
/** * This class can be used to represent static methods, timestamped with a Time_Period. * * @author Daniel Baumann * @version 0.0.1 * @since 0.0.1 */
This class can be used to represent static methods, timestamped with a Time_Period.
[ "This", "class", "can", "be", "used", "to", "represent", "static", "methods", "timestamped", "with", "a", "Time_Period", "." ]
public class TS_Unit extends TS_Object<InterpolationInterface, Time_Period> { /** * * @param value A interpolation method. * @param ts A Time_Period object. */ public TS_Unit(InterpolationInterface value, Time_Period ts) { super(value, ts); } /** * Calls timestamped function of the TS_Unit, and returns interpolated value. * * @param start_ts TS_Object laying before end_ts on the time axis * @param end_ts TS_Object laying after start_ts on the time axis * @param time OffsetDateTime defining the point in time for which the value will be interpolated * @param kwargs HashMap with additional arguments for the interpolation function. * @throws IllegalArgumentException if start_ts.get_type() does not equal end_ts.get_type() * @return TS_Object holding interpolated value and 'time' as timestamp. */ public TS_Object<?,?> interpolate(TS_Object<?,?> start_ts, TS_Object<?,?> end_ts, OffsetDateTime time, HashMap<?, ?> kwargs) { if (start_ts.get_type().equals(end_ts.get_type())) { return this.ip(this.get_value(), start_ts, end_ts, time, kwargs); } else { throw new IllegalArgumentException("ts must be of type OffsetDateTime or of type Time_Period"); } } private TS_Object<?,?> ip(InterpolationInterface ipf, TS_Object<?,?> start_ts, TS_Object<?,?> end_ts, OffsetDateTime time, HashMap<?, ?> kwargs) { return ipf.interpolate(start_ts, end_ts, time, kwargs); } }
[ "public", "class", "TS_Unit", "extends", "TS_Object", "<", "InterpolationInterface", ",", "Time_Period", ">", "{", "/**\n\t * \n\t * @param value A interpolation method.\n\t * @param ts A Time_Period object.\n\t */", "public", "TS_Unit", "(", "InterpolationInterface", "value", ",", "Time_Period", "ts", ")", "{", "super", "(", "value", ",", "ts", ")", ";", "}", "/**\n\t * Calls timestamped function of the TS_Unit, and returns interpolated value.\n\t * \n\t * @param start_ts TS_Object laying before end_ts on the time axis\n\t * @param end_ts TS_Object laying after start_ts on the time axis\n\t * @param time OffsetDateTime defining the point in time for which the value will be interpolated\n\t * @param kwargs HashMap with additional arguments for the interpolation function.\n\t * @throws IllegalArgumentException if start_ts.get_type() does not equal end_ts.get_type()\n\t * @return TS_Object holding interpolated value and 'time' as timestamp.\n\t */", "public", "TS_Object", "<", "?", ",", "?", ">", "interpolate", "(", "TS_Object", "<", "?", ",", "?", ">", "start_ts", ",", "TS_Object", "<", "?", ",", "?", ">", "end_ts", ",", "OffsetDateTime", "time", ",", "HashMap", "<", "?", ",", "?", ">", "kwargs", ")", "{", "if", "(", "start_ts", ".", "get_type", "(", ")", ".", "equals", "(", "end_ts", ".", "get_type", "(", ")", ")", ")", "{", "return", "this", ".", "ip", "(", "this", ".", "get_value", "(", ")", ",", "start_ts", ",", "end_ts", ",", "time", ",", "kwargs", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "ts must be of type OffsetDateTime or of type Time_Period", "\"", ")", ";", "}", "}", "private", "TS_Object", "<", "?", ",", "?", ">", "ip", "(", "InterpolationInterface", "ipf", ",", "TS_Object", "<", "?", ",", "?", ">", "start_ts", ",", "TS_Object", "<", "?", ",", "?", ">", "end_ts", ",", "OffsetDateTime", "time", ",", "HashMap", "<", "?", ",", "?", ">", "kwargs", ")", "{", "return", "ipf", ".", "interpolate", "(", "start_ts", ",", "end_ts", ",", "time", ",", "kwargs", ")", ";", "}", "}" ]
This class can be used to represent static methods, timestamped with a Time_Period.
[ "This", "class", "can", "be", "used", "to", "represent", "static", "methods", "timestamped", "with", "a", "Time_Period", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84b689653f1be34e8a79ee8d188374507961ef9a
JLLeitschuh/ephemerals
core/src/main/java/com/liveperson/ephemerals/deploy/DeploymentContext.java
[ "MIT" ]
Java
DeploymentContext
/** * Created by waseemh on 9/26/16. */
Created by waseemh on 9/26/16.
[ "Created", "by", "waseemh", "on", "9", "/", "26", "/", "16", "." ]
public class DeploymentContext { private final DeploymentHandler deploymentHandler; private final DeploymentConfiguration deploymentConfiguration; public DeploymentContext(DeploymentHandler deploymentHandler, DeploymentConfiguration deploymentConfiguration) { this.deploymentHandler = deploymentHandler; this.deploymentConfiguration = deploymentConfiguration; } public DeploymentHandler getDeploymentHandler() { return deploymentHandler; } public DeploymentConfiguration getDeploymentConfiguration() { return deploymentConfiguration; } }
[ "public", "class", "DeploymentContext", "{", "private", "final", "DeploymentHandler", "deploymentHandler", ";", "private", "final", "DeploymentConfiguration", "deploymentConfiguration", ";", "public", "DeploymentContext", "(", "DeploymentHandler", "deploymentHandler", ",", "DeploymentConfiguration", "deploymentConfiguration", ")", "{", "this", ".", "deploymentHandler", "=", "deploymentHandler", ";", "this", ".", "deploymentConfiguration", "=", "deploymentConfiguration", ";", "}", "public", "DeploymentHandler", "getDeploymentHandler", "(", ")", "{", "return", "deploymentHandler", ";", "}", "public", "DeploymentConfiguration", "getDeploymentConfiguration", "(", ")", "{", "return", "deploymentConfiguration", ";", "}", "}" ]
Created by waseemh on 9/26/16.
[ "Created", "by", "waseemh", "on", "9", "/", "26", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84b758c862090552a12fb16e12593f3c10e36d02
dawsonlp/herd
dm-code/dm-rest/src/test/java/org/finra/dm/rest/BusinessObjectDataRestControllerGetBusinessObjectDataVersionsTest.java
[ "Apache-2.0" ]
Java
BusinessObjectDataRestControllerGetBusinessObjectDataVersionsTest
/** * This class tests get business object data versions functionality within the business object data REST controller. */
This class tests get business object data versions functionality within the business object data REST controller.
[ "This", "class", "tests", "get", "business", "object", "data", "versions", "functionality", "within", "the", "business", "object", "data", "REST", "controller", "." ]
public class BusinessObjectDataRestControllerGetBusinessObjectDataVersionsTest extends AbstractRestTest { @Autowired DmDaoHelper dmDaoHelper; private static final int NUMBER_OF_FORMAT_VERSIONS = 2; private static final int NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION = 3; @Test public void testGetBusinessObjectDataVersions() { // Create and persist test database entities. createTestDatabaseEntities(SUBPARTITION_VALUES); // Retrieve the relative business object data version by specifying values for all input parameters. for (int businessObjectFormatVersion = INITIAL_FORMAT_VERSION; businessObjectFormatVersion < NUMBER_OF_FORMAT_VERSIONS; businessObjectFormatVersion++) { for (int businessObjectDataVersion = INITIAL_DATA_VERSION; businessObjectDataVersion < NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION; businessObjectDataVersion++) { BusinessObjectDataVersions businessObjectDataVersions = businessObjectDataRestController .getBusinessObjectDataVersions(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, PARTITION_VALUE, getDelimitedFieldValues(SUBPARTITION_VALUES), businessObjectFormatVersion, businessObjectDataVersion); // Validate the returned object. assertNotNull(businessObjectDataVersions); assertEquals(1, businessObjectDataVersions.getBusinessObjectDataVersions().size()); validateBusinessObjectDataKey(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, businessObjectFormatVersion, PARTITION_VALUE, SUBPARTITION_VALUES, businessObjectDataVersion, businessObjectDataVersions.getBusinessObjectDataVersions().get(0).getBusinessObjectDataKey()); assertEquals(BDATA_STATUS, businessObjectDataVersions.getBusinessObjectDataVersions().get(0).getStatus()); } } } @Test public void testGetBusinessObjectDataMissingOptionalParameters() { // Create and persist a business object data entities without subpartition values. createTestDatabaseEntities(NO_SUBPARTITION_VALUES); // Retrieve business object data versions without specifying any of the optional parameters including the subpartition values. BusinessObjectDataVersions resultBusinessObjectDataVersions = businessObjectDataRestController .getBusinessObjectDataVersions(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, PARTITION_VALUE, null, null, null); // Validate the returned object. assertNotNull(resultBusinessObjectDataVersions); assertEquals(NUMBER_OF_FORMAT_VERSIONS * NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION, resultBusinessObjectDataVersions.getBusinessObjectDataVersions().size()); } /** * Create and persist database entities required for testing. */ private void createTestDatabaseEntities(List<String> subPartitionValues) { for (int businessObjectFormatVersion = INITIAL_FORMAT_VERSION; businessObjectFormatVersion < NUMBER_OF_FORMAT_VERSIONS; businessObjectFormatVersion++) { createBusinessObjectFormatEntity(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, businessObjectFormatVersion, FORMAT_DESCRIPTION, businessObjectFormatVersion == SECOND_FORMAT_VERSION, PARTITION_KEY); for (int businessObjectDataVersion = INITIAL_DATA_VERSION; businessObjectDataVersion < NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION; businessObjectDataVersion++) { createBusinessObjectDataEntity(NAMESPACE_CD, BOD_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, businessObjectFormatVersion, PARTITION_VALUE, subPartitionValues, businessObjectDataVersion, businessObjectDataVersion == SECOND_DATA_VERSION, BDATA_STATUS); } } } }
[ "public", "class", "BusinessObjectDataRestControllerGetBusinessObjectDataVersionsTest", "extends", "AbstractRestTest", "{", "@", "Autowired", "DmDaoHelper", "dmDaoHelper", ";", "private", "static", "final", "int", "NUMBER_OF_FORMAT_VERSIONS", "=", "2", ";", "private", "static", "final", "int", "NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION", "=", "3", ";", "@", "Test", "public", "void", "testGetBusinessObjectDataVersions", "(", ")", "{", "createTestDatabaseEntities", "(", "SUBPARTITION_VALUES", ")", ";", "for", "(", "int", "businessObjectFormatVersion", "=", "INITIAL_FORMAT_VERSION", ";", "businessObjectFormatVersion", "<", "NUMBER_OF_FORMAT_VERSIONS", ";", "businessObjectFormatVersion", "++", ")", "{", "for", "(", "int", "businessObjectDataVersion", "=", "INITIAL_DATA_VERSION", ";", "businessObjectDataVersion", "<", "NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION", ";", "businessObjectDataVersion", "++", ")", "{", "BusinessObjectDataVersions", "businessObjectDataVersions", "=", "businessObjectDataRestController", ".", "getBusinessObjectDataVersions", "(", "NAMESPACE_CD", ",", "BOD_NAME", ",", "FORMAT_USAGE_CODE", ",", "FORMAT_FILE_TYPE_CODE", ",", "PARTITION_VALUE", ",", "getDelimitedFieldValues", "(", "SUBPARTITION_VALUES", ")", ",", "businessObjectFormatVersion", ",", "businessObjectDataVersion", ")", ";", "assertNotNull", "(", "businessObjectDataVersions", ")", ";", "assertEquals", "(", "1", ",", "businessObjectDataVersions", ".", "getBusinessObjectDataVersions", "(", ")", ".", "size", "(", ")", ")", ";", "validateBusinessObjectDataKey", "(", "NAMESPACE_CD", ",", "BOD_NAME", ",", "FORMAT_USAGE_CODE", ",", "FORMAT_FILE_TYPE_CODE", ",", "businessObjectFormatVersion", ",", "PARTITION_VALUE", ",", "SUBPARTITION_VALUES", ",", "businessObjectDataVersion", ",", "businessObjectDataVersions", ".", "getBusinessObjectDataVersions", "(", ")", ".", "get", "(", "0", ")", ".", "getBusinessObjectDataKey", "(", ")", ")", ";", "assertEquals", "(", "BDATA_STATUS", ",", "businessObjectDataVersions", ".", "getBusinessObjectDataVersions", "(", ")", ".", "get", "(", "0", ")", ".", "getStatus", "(", ")", ")", ";", "}", "}", "}", "@", "Test", "public", "void", "testGetBusinessObjectDataMissingOptionalParameters", "(", ")", "{", "createTestDatabaseEntities", "(", "NO_SUBPARTITION_VALUES", ")", ";", "BusinessObjectDataVersions", "resultBusinessObjectDataVersions", "=", "businessObjectDataRestController", ".", "getBusinessObjectDataVersions", "(", "NAMESPACE_CD", ",", "BOD_NAME", ",", "FORMAT_USAGE_CODE", ",", "FORMAT_FILE_TYPE_CODE", ",", "PARTITION_VALUE", ",", "null", ",", "null", ",", "null", ")", ";", "assertNotNull", "(", "resultBusinessObjectDataVersions", ")", ";", "assertEquals", "(", "NUMBER_OF_FORMAT_VERSIONS", "*", "NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION", ",", "resultBusinessObjectDataVersions", ".", "getBusinessObjectDataVersions", "(", ")", ".", "size", "(", ")", ")", ";", "}", "/**\n * Create and persist database entities required for testing.\n */", "private", "void", "createTestDatabaseEntities", "(", "List", "<", "String", ">", "subPartitionValues", ")", "{", "for", "(", "int", "businessObjectFormatVersion", "=", "INITIAL_FORMAT_VERSION", ";", "businessObjectFormatVersion", "<", "NUMBER_OF_FORMAT_VERSIONS", ";", "businessObjectFormatVersion", "++", ")", "{", "createBusinessObjectFormatEntity", "(", "NAMESPACE_CD", ",", "BOD_NAME", ",", "FORMAT_USAGE_CODE", ",", "FORMAT_FILE_TYPE_CODE", ",", "businessObjectFormatVersion", ",", "FORMAT_DESCRIPTION", ",", "businessObjectFormatVersion", "==", "SECOND_FORMAT_VERSION", ",", "PARTITION_KEY", ")", ";", "for", "(", "int", "businessObjectDataVersion", "=", "INITIAL_DATA_VERSION", ";", "businessObjectDataVersion", "<", "NUMBER_OF_DATA_VERSIONS_PER_FORMAT_VERSION", ";", "businessObjectDataVersion", "++", ")", "{", "createBusinessObjectDataEntity", "(", "NAMESPACE_CD", ",", "BOD_NAME", ",", "FORMAT_USAGE_CODE", ",", "FORMAT_FILE_TYPE_CODE", ",", "businessObjectFormatVersion", ",", "PARTITION_VALUE", ",", "subPartitionValues", ",", "businessObjectDataVersion", ",", "businessObjectDataVersion", "==", "SECOND_DATA_VERSION", ",", "BDATA_STATUS", ")", ";", "}", "}", "}", "}" ]
This class tests get business object data versions functionality within the business object data REST controller.
[ "This", "class", "tests", "get", "business", "object", "data", "versions", "functionality", "within", "the", "business", "object", "data", "REST", "controller", "." ]
[ "// Create and persist test database entities.", "// Retrieve the relative business object data version by specifying values for all input parameters.", "// Validate the returned object.", "// Create and persist a business object data entities without subpartition values.", "// Retrieve business object data versions without specifying any of the optional parameters including the subpartition values.", "// Validate the returned object." ]
[ { "param": "AbstractRestTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractRestTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84b7685d7f27e8b9ae296a6133eaa83468f3962e
MatthijsKamstra/haxejava
04lwjgl/code/lwjgl/org/lwjgl/opengl/EXTVertexAttrib64bit.java
[ "MIT" ]
Java
EXTVertexAttrib64bit
/** * Native bindings to the <a href="http://www.opengl.org/registry/specs/EXT/vertex_attrib_64bit.txt">EXT_vertex_attrib_64bit</a> extension. * * <p>This extension provides OpenGL shading language support for vertex shader inputs with 64-bit floating-point components and OpenGL API support for * specifying the value of those inputs using vertex array or immediate mode entry points. This builds on the support for general-purpose support for * 64-bit floating-point values in the ARB_gpu_shader_fp64 extension.</p> * * <p>This extension provides a new class of vertex attribute functions, beginning with "VertexAttribL" ("L" for "long"), that can be used to specify * attributes with 64-bit floating-point components. This extension provides no automatic type conversion between attribute and shader variables; * single-precision attributes are not automatically converted to double-precision or vice versa. For shader variables with 64-bit component types, the * "VertexAttribL" functions must be used to specify attribute values. For other shader variables, the "VertexAttribL" functions must not be used. If a * vertex attribute is specified using the wrong attribute function, the values of the corresponding shader input are undefined. This approach requiring * matching types is identical to that used for the "VertexAttribI" functions provided by OpenGL 3.0 and the EXT_gpu_shader4 extension.</p> * * <p>Additionally, some vertex shader inputs using the wider 64-bit components may count double against the implementation-dependent limit on the number of * vertex shader attribute vectors. A 64-bit scalar or a two-component vector consumes only a single generic vertex attribute; three- and four-component * "long" may count as two. This approach is similar to the one used in the current GL where matrix attributes consume multiple attributes.</p> * * <p>Note that 64-bit generic vertex attributes were nominally supported beginning with the introduction of vertex shaders in OpenGL 2.0. However, the * OpenGL Shading Language at the time had no support for 64-bit data types, so any such values were automatically converted to 32-bit.</p> * * <p>Support for 64-bit floating-point vertex attributes in this extension can be combined with other extensions. In particular, this extension provides an * entry point that can be used with EXT_direct_state_access to directly set state for any vertex array object. Also, the related * NV_vertex_attrib_integer_64bit extension provides an entry point to specify bindless vertex attribute arrays with 64-bit components, integer or * floating-point.</p> * * <p>Requires {@link GL30 OpenGL 3.0} and {@link ARBGPUShaderFP64 ARB_gpu_shader_fp64} (or equivalent functionality).</p> */
Native bindings to the EXT_vertex_attrib_64bit extension. This extension provides OpenGL shading language support for vertex shader inputs with 64-bit floating-point components and OpenGL API support for specifying the value of those inputs using vertex array or immediate mode entry points. This builds on the support for general-purpose support for 64-bit floating-point values in the ARB_gpu_shader_fp64 extension. Additionally, some vertex shader inputs using the wider 64-bit components may count double against the implementation-dependent limit on the number of vertex shader attribute vectors. A 64-bit scalar or a two-component vector consumes only a single generic vertex attribute; three- and four-component "long" may count as two. This approach is similar to the one used in the current GL where matrix attributes consume multiple attributes. Note that 64-bit generic vertex attributes were nominally supported beginning with the introduction of vertex shaders in OpenGL 2.0. However, the OpenGL Shading Language at the time had no support for 64-bit data types, so any such values were automatically converted to 32-bit. Support for 64-bit floating-point vertex attributes in this extension can be combined with other extensions. In particular, this extension provides an entry point that can be used with EXT_direct_state_access to directly set state for any vertex array object. Also, the related NV_vertex_attrib_integer_64bit extension provides an entry point to specify bindless vertex attribute arrays with 64-bit components, integer or floating-point. Requires GL30 OpenGL 3.0 and ARBGPUShaderFP64 ARB_gpu_shader_fp64 (or equivalent functionality).
[ "Native", "bindings", "to", "the", "EXT_vertex_attrib_64bit", "extension", ".", "This", "extension", "provides", "OpenGL", "shading", "language", "support", "for", "vertex", "shader", "inputs", "with", "64", "-", "bit", "floating", "-", "point", "components", "and", "OpenGL", "API", "support", "for", "specifying", "the", "value", "of", "those", "inputs", "using", "vertex", "array", "or", "immediate", "mode", "entry", "points", ".", "This", "builds", "on", "the", "support", "for", "general", "-", "purpose", "support", "for", "64", "-", "bit", "floating", "-", "point", "values", "in", "the", "ARB_gpu_shader_fp64", "extension", ".", "Additionally", "some", "vertex", "shader", "inputs", "using", "the", "wider", "64", "-", "bit", "components", "may", "count", "double", "against", "the", "implementation", "-", "dependent", "limit", "on", "the", "number", "of", "vertex", "shader", "attribute", "vectors", ".", "A", "64", "-", "bit", "scalar", "or", "a", "two", "-", "component", "vector", "consumes", "only", "a", "single", "generic", "vertex", "attribute", ";", "three", "-", "and", "four", "-", "component", "\"", "long", "\"", "may", "count", "as", "two", ".", "This", "approach", "is", "similar", "to", "the", "one", "used", "in", "the", "current", "GL", "where", "matrix", "attributes", "consume", "multiple", "attributes", ".", "Note", "that", "64", "-", "bit", "generic", "vertex", "attributes", "were", "nominally", "supported", "beginning", "with", "the", "introduction", "of", "vertex", "shaders", "in", "OpenGL", "2", ".", "0", ".", "However", "the", "OpenGL", "Shading", "Language", "at", "the", "time", "had", "no", "support", "for", "64", "-", "bit", "data", "types", "so", "any", "such", "values", "were", "automatically", "converted", "to", "32", "-", "bit", ".", "Support", "for", "64", "-", "bit", "floating", "-", "point", "vertex", "attributes", "in", "this", "extension", "can", "be", "combined", "with", "other", "extensions", ".", "In", "particular", "this", "extension", "provides", "an", "entry", "point", "that", "can", "be", "used", "with", "EXT_direct_state_access", "to", "directly", "set", "state", "for", "any", "vertex", "array", "object", ".", "Also", "the", "related", "NV_vertex_attrib_integer_64bit", "extension", "provides", "an", "entry", "point", "to", "specify", "bindless", "vertex", "attribute", "arrays", "with", "64", "-", "bit", "components", "integer", "or", "floating", "-", "point", ".", "Requires", "GL30", "OpenGL", "3", ".", "0", "and", "ARBGPUShaderFP64", "ARB_gpu_shader_fp64", "(", "or", "equivalent", "functionality", ")", "." ]
public class EXTVertexAttrib64bit { /** Returned in the {@code type} parameter of GetActiveAttrib. */ public static final int GL_DOUBLE_VEC2_EXT = 0x8FFC, GL_DOUBLE_VEC3_EXT = 0x8FFD, GL_DOUBLE_VEC4_EXT = 0x8FFE, GL_DOUBLE_MAT2_EXT = 0x8F46, GL_DOUBLE_MAT3_EXT = 0x8F47, GL_DOUBLE_MAT4_EXT = 0x8F48, GL_DOUBLE_MAT2x3_EXT = 0x8F49, GL_DOUBLE_MAT2x4_EXT = 0x8F4A, GL_DOUBLE_MAT3x2_EXT = 0x8F4B, GL_DOUBLE_MAT3x4_EXT = 0x8F4C, GL_DOUBLE_MAT4x2_EXT = 0x8F4D, GL_DOUBLE_MAT4x3_EXT = 0x8F4E; protected EXTVertexAttrib64bit() { throw new UnsupportedOperationException(); } static boolean isAvailable(GLCapabilities caps, java.util.Set<String> ext) { return checkFunctions( caps.glVertexAttribL1dEXT, caps.glVertexAttribL2dEXT, caps.glVertexAttribL3dEXT, caps.glVertexAttribL4dEXT, caps.glVertexAttribL1dvEXT, caps.glVertexAttribL2dvEXT, caps.glVertexAttribL3dvEXT, caps.glVertexAttribL4dvEXT, caps.glVertexAttribLPointerEXT, caps.glGetVertexAttribLdvEXT, ext.contains("GL_EXT_direct_state_access") ? caps.glVertexArrayVertexAttribLOffsetEXT : -1L ); } // --- [ glVertexAttribL1dEXT ] --- public static void glVertexAttribL1dEXT(int index, double x) { long __functionAddress = GL.getCapabilities().glVertexAttribL1dEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x); } // --- [ glVertexAttribL2dEXT ] --- public static void glVertexAttribL2dEXT(int index, double x, double y) { long __functionAddress = GL.getCapabilities().glVertexAttribL2dEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y); } // --- [ glVertexAttribL3dEXT ] --- public static void glVertexAttribL3dEXT(int index, double x, double y, double z) { long __functionAddress = GL.getCapabilities().glVertexAttribL3dEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y, z); } // --- [ glVertexAttribL4dEXT ] --- public static void glVertexAttribL4dEXT(int index, double x, double y, double z, double w) { long __functionAddress = GL.getCapabilities().glVertexAttribL4dEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callV(__functionAddress, index, x, y, z, w); } // --- [ glVertexAttribL1dvEXT ] --- public static void nglVertexAttribL1dvEXT(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL1dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } public static void glVertexAttribL1dvEXT(int index, DoubleBuffer v) { nglVertexAttribL1dvEXT(index, memAddress(v)); } // --- [ glVertexAttribL2dvEXT ] --- public static void nglVertexAttribL2dvEXT(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL2dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } public static void glVertexAttribL2dvEXT(int index, DoubleBuffer v) { nglVertexAttribL2dvEXT(index, memAddress(v)); } // --- [ glVertexAttribL3dvEXT ] --- public static void nglVertexAttribL3dvEXT(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL3dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } public static void glVertexAttribL3dvEXT(int index, DoubleBuffer v) { nglVertexAttribL3dvEXT(index, memAddress(v)); } // --- [ glVertexAttribL4dvEXT ] --- public static void nglVertexAttribL4dvEXT(int index, long v) { long __functionAddress = GL.getCapabilities().glVertexAttribL4dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } public static void glVertexAttribL4dvEXT(int index, DoubleBuffer v) { nglVertexAttribL4dvEXT(index, memAddress(v)); } // --- [ glVertexAttribLPointerEXT ] --- public static void nglVertexAttribLPointerEXT(int index, int size, int type, int stride, long pointer) { long __functionAddress = GL.getCapabilities().glVertexAttribLPointerEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, size, type, stride, pointer); } public static void glVertexAttribLPointerEXT(int index, int size, int type, int stride, ByteBuffer pointer) { if ( CHECKS ) GLChecks.ensureBufferObject(GL15.GL_ARRAY_BUFFER_BINDING, false); nglVertexAttribLPointerEXT(index, size, type, stride, memAddress(pointer)); } public static void glVertexAttribLPointerEXT(int index, int size, int type, int stride, long pointer) { if ( CHECKS ) GLChecks.ensureBufferObject(GL15.GL_ARRAY_BUFFER_BINDING, true); nglVertexAttribLPointerEXT(index, size, type, stride, pointer); } public static void glVertexAttribLPointerEXT(int index, int size, int stride, DoubleBuffer pointer) { if ( CHECKS ) GLChecks.ensureBufferObject(GL15.GL_ARRAY_BUFFER_BINDING, false); nglVertexAttribLPointerEXT(index, size, GL11.GL_DOUBLE, stride, memAddress(pointer)); } // --- [ glGetVertexAttribLdvEXT ] --- public static void nglGetVertexAttribLdvEXT(int index, int pname, long params) { long __functionAddress = GL.getCapabilities().glGetVertexAttribLdvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, pname, params); } public static void glGetVertexAttribLdvEXT(int index, int pname, DoubleBuffer params) { nglGetVertexAttribLdvEXT(index, pname, memAddress(params)); } // --- [ glVertexArrayVertexAttribLOffsetEXT ] --- public static void glVertexArrayVertexAttribLOffsetEXT(int vaobj, int buffer, int index, int size, int type, int stride, long offset) { long __functionAddress = GL.getCapabilities().glVertexArrayVertexAttribLOffsetEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, vaobj, buffer, index, size, type, stride, offset); } /** Array version of: {@link #glVertexAttribL1dvEXT VertexAttribL1dvEXT} */ public static void glVertexAttribL1dvEXT(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL1dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** Array version of: {@link #glVertexAttribL2dvEXT VertexAttribL2dvEXT} */ public static void glVertexAttribL2dvEXT(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL2dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** Array version of: {@link #glVertexAttribL3dvEXT VertexAttribL3dvEXT} */ public static void glVertexAttribL3dvEXT(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL3dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** Array version of: {@link #glVertexAttribL4dvEXT VertexAttribL4dvEXT} */ public static void glVertexAttribL4dvEXT(int index, double[] v) { long __functionAddress = GL.getCapabilities().glVertexAttribL4dvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, v); } /** Array version of: {@link #glGetVertexAttribLdvEXT GetVertexAttribLdvEXT} */ public static void glGetVertexAttribLdvEXT(int index, int pname, double[] params) { long __functionAddress = GL.getCapabilities().glGetVertexAttribLdvEXT; if ( CHECKS ) checkFunctionAddress(__functionAddress); callPV(__functionAddress, index, pname, params); } }
[ "public", "class", "EXTVertexAttrib64bit", "{", "/** Returned in the {@code type} parameter of GetActiveAttrib. */", "public", "static", "final", "int", "GL_DOUBLE_VEC2_EXT", "=", "0x8FFC", ",", "GL_DOUBLE_VEC3_EXT", "=", "0x8FFD", ",", "GL_DOUBLE_VEC4_EXT", "=", "0x8FFE", ",", "GL_DOUBLE_MAT2_EXT", "=", "0x8F46", ",", "GL_DOUBLE_MAT3_EXT", "=", "0x8F47", ",", "GL_DOUBLE_MAT4_EXT", "=", "0x8F48", ",", "GL_DOUBLE_MAT2x3_EXT", "=", "0x8F49", ",", "GL_DOUBLE_MAT2x4_EXT", "=", "0x8F4A", ",", "GL_DOUBLE_MAT3x2_EXT", "=", "0x8F4B", ",", "GL_DOUBLE_MAT3x4_EXT", "=", "0x8F4C", ",", "GL_DOUBLE_MAT4x2_EXT", "=", "0x8F4D", ",", "GL_DOUBLE_MAT4x3_EXT", "=", "0x8F4E", ";", "protected", "EXTVertexAttrib64bit", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "static", "boolean", "isAvailable", "(", "GLCapabilities", "caps", ",", "java", ".", "util", ".", "Set", "<", "String", ">", "ext", ")", "{", "return", "checkFunctions", "(", "caps", ".", "glVertexAttribL1dEXT", ",", "caps", ".", "glVertexAttribL2dEXT", ",", "caps", ".", "glVertexAttribL3dEXT", ",", "caps", ".", "glVertexAttribL4dEXT", ",", "caps", ".", "glVertexAttribL1dvEXT", ",", "caps", ".", "glVertexAttribL2dvEXT", ",", "caps", ".", "glVertexAttribL3dvEXT", ",", "caps", ".", "glVertexAttribL4dvEXT", ",", "caps", ".", "glVertexAttribLPointerEXT", ",", "caps", ".", "glGetVertexAttribLdvEXT", ",", "ext", ".", "contains", "(", "\"", "GL_EXT_direct_state_access", "\"", ")", "?", "caps", ".", "glVertexArrayVertexAttribLOffsetEXT", ":", "-", "1L", ")", ";", "}", "public", "static", "void", "glVertexAttribL1dEXT", "(", "int", "index", ",", "double", "x", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL1dEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callV", "(", "__functionAddress", ",", "index", ",", "x", ")", ";", "}", "public", "static", "void", "glVertexAttribL2dEXT", "(", "int", "index", ",", "double", "x", ",", "double", "y", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL2dEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callV", "(", "__functionAddress", ",", "index", ",", "x", ",", "y", ")", ";", "}", "public", "static", "void", "glVertexAttribL3dEXT", "(", "int", "index", ",", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL3dEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callV", "(", "__functionAddress", ",", "index", ",", "x", ",", "y", ",", "z", ")", ";", "}", "public", "static", "void", "glVertexAttribL4dEXT", "(", "int", "index", ",", "double", "x", ",", "double", "y", ",", "double", "z", ",", "double", "w", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL4dEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callV", "(", "__functionAddress", ",", "index", ",", "x", ",", "y", ",", "z", ",", "w", ")", ";", "}", "public", "static", "void", "nglVertexAttribL1dvEXT", "(", "int", "index", ",", "long", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL1dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "public", "static", "void", "glVertexAttribL1dvEXT", "(", "int", "index", ",", "DoubleBuffer", "v", ")", "{", "nglVertexAttribL1dvEXT", "(", "index", ",", "memAddress", "(", "v", ")", ")", ";", "}", "public", "static", "void", "nglVertexAttribL2dvEXT", "(", "int", "index", ",", "long", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL2dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "public", "static", "void", "glVertexAttribL2dvEXT", "(", "int", "index", ",", "DoubleBuffer", "v", ")", "{", "nglVertexAttribL2dvEXT", "(", "index", ",", "memAddress", "(", "v", ")", ")", ";", "}", "public", "static", "void", "nglVertexAttribL3dvEXT", "(", "int", "index", ",", "long", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL3dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "public", "static", "void", "glVertexAttribL3dvEXT", "(", "int", "index", ",", "DoubleBuffer", "v", ")", "{", "nglVertexAttribL3dvEXT", "(", "index", ",", "memAddress", "(", "v", ")", ")", ";", "}", "public", "static", "void", "nglVertexAttribL4dvEXT", "(", "int", "index", ",", "long", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL4dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "public", "static", "void", "glVertexAttribL4dvEXT", "(", "int", "index", ",", "DoubleBuffer", "v", ")", "{", "nglVertexAttribL4dvEXT", "(", "index", ",", "memAddress", "(", "v", ")", ")", ";", "}", "public", "static", "void", "nglVertexAttribLPointerEXT", "(", "int", "index", ",", "int", "size", ",", "int", "type", ",", "int", "stride", ",", "long", "pointer", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribLPointerEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "size", ",", "type", ",", "stride", ",", "pointer", ")", ";", "}", "public", "static", "void", "glVertexAttribLPointerEXT", "(", "int", "index", ",", "int", "size", ",", "int", "type", ",", "int", "stride", ",", "ByteBuffer", "pointer", ")", "{", "if", "(", "CHECKS", ")", "GLChecks", ".", "ensureBufferObject", "(", "GL15", ".", "GL_ARRAY_BUFFER_BINDING", ",", "false", ")", ";", "nglVertexAttribLPointerEXT", "(", "index", ",", "size", ",", "type", ",", "stride", ",", "memAddress", "(", "pointer", ")", ")", ";", "}", "public", "static", "void", "glVertexAttribLPointerEXT", "(", "int", "index", ",", "int", "size", ",", "int", "type", ",", "int", "stride", ",", "long", "pointer", ")", "{", "if", "(", "CHECKS", ")", "GLChecks", ".", "ensureBufferObject", "(", "GL15", ".", "GL_ARRAY_BUFFER_BINDING", ",", "true", ")", ";", "nglVertexAttribLPointerEXT", "(", "index", ",", "size", ",", "type", ",", "stride", ",", "pointer", ")", ";", "}", "public", "static", "void", "glVertexAttribLPointerEXT", "(", "int", "index", ",", "int", "size", ",", "int", "stride", ",", "DoubleBuffer", "pointer", ")", "{", "if", "(", "CHECKS", ")", "GLChecks", ".", "ensureBufferObject", "(", "GL15", ".", "GL_ARRAY_BUFFER_BINDING", ",", "false", ")", ";", "nglVertexAttribLPointerEXT", "(", "index", ",", "size", ",", "GL11", ".", "GL_DOUBLE", ",", "stride", ",", "memAddress", "(", "pointer", ")", ")", ";", "}", "public", "static", "void", "nglGetVertexAttribLdvEXT", "(", "int", "index", ",", "int", "pname", ",", "long", "params", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glGetVertexAttribLdvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "pname", ",", "params", ")", ";", "}", "public", "static", "void", "glGetVertexAttribLdvEXT", "(", "int", "index", ",", "int", "pname", ",", "DoubleBuffer", "params", ")", "{", "nglGetVertexAttribLdvEXT", "(", "index", ",", "pname", ",", "memAddress", "(", "params", ")", ")", ";", "}", "public", "static", "void", "glVertexArrayVertexAttribLOffsetEXT", "(", "int", "vaobj", ",", "int", "buffer", ",", "int", "index", ",", "int", "size", ",", "int", "type", ",", "int", "stride", ",", "long", "offset", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexArrayVertexAttribLOffsetEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "vaobj", ",", "buffer", ",", "index", ",", "size", ",", "type", ",", "stride", ",", "offset", ")", ";", "}", "/** Array version of: {@link #glVertexAttribL1dvEXT VertexAttribL1dvEXT} */", "public", "static", "void", "glVertexAttribL1dvEXT", "(", "int", "index", ",", "double", "[", "]", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL1dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "/** Array version of: {@link #glVertexAttribL2dvEXT VertexAttribL2dvEXT} */", "public", "static", "void", "glVertexAttribL2dvEXT", "(", "int", "index", ",", "double", "[", "]", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL2dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "/** Array version of: {@link #glVertexAttribL3dvEXT VertexAttribL3dvEXT} */", "public", "static", "void", "glVertexAttribL3dvEXT", "(", "int", "index", ",", "double", "[", "]", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL3dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "/** Array version of: {@link #glVertexAttribL4dvEXT VertexAttribL4dvEXT} */", "public", "static", "void", "glVertexAttribL4dvEXT", "(", "int", "index", ",", "double", "[", "]", "v", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glVertexAttribL4dvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "v", ")", ";", "}", "/** Array version of: {@link #glGetVertexAttribLdvEXT GetVertexAttribLdvEXT} */", "public", "static", "void", "glGetVertexAttribLdvEXT", "(", "int", "index", ",", "int", "pname", ",", "double", "[", "]", "params", ")", "{", "long", "__functionAddress", "=", "GL", ".", "getCapabilities", "(", ")", ".", "glGetVertexAttribLdvEXT", ";", "if", "(", "CHECKS", ")", "checkFunctionAddress", "(", "__functionAddress", ")", ";", "callPV", "(", "__functionAddress", ",", "index", ",", "pname", ",", "params", ")", ";", "}", "}" ]
Native bindings to the <a href="http://www.opengl.org/registry/specs/EXT/vertex_attrib_64bit.txt">EXT_vertex_attrib_64bit</a> extension.
[ "Native", "bindings", "to", "the", "<a", "href", "=", "\"", "http", ":", "//", "www", ".", "opengl", ".", "org", "/", "registry", "/", "specs", "/", "EXT", "/", "vertex_attrib_64bit", ".", "txt", "\"", ">", "EXT_vertex_attrib_64bit<", "/", "a", ">", "extension", "." ]
[ "// --- [ glVertexAttribL1dEXT ] ---", "// --- [ glVertexAttribL2dEXT ] ---", "// --- [ glVertexAttribL3dEXT ] ---", "// --- [ glVertexAttribL4dEXT ] ---", "// --- [ glVertexAttribL1dvEXT ] ---", "// --- [ glVertexAttribL2dvEXT ] ---", "// --- [ glVertexAttribL3dvEXT ] ---", "// --- [ glVertexAttribL4dvEXT ] ---", "// --- [ glVertexAttribLPointerEXT ] ---", "// --- [ glGetVertexAttribLdvEXT ] ---", "// --- [ glVertexArrayVertexAttribLOffsetEXT ] ---" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84b97be0f0839a153ea5722061a69ed3aed038e6
chrisnharris/Recaf
src/main/java/me/coley/recaf/util/VMUtil.java
[ "MIT" ]
Java
VMUtil
/** * Dependent and non-dependent platform utilities for VM. * * @author xxDark */
Dependent and non-dependent platform utilities for VM. @author xxDark
[ "Dependent", "and", "non", "-", "dependent", "platform", "utilities", "for", "VM", ".", "@author", "xxDark" ]
public final class VMUtil { /** * Deny all constructions. */ private VMUtil() { } /** * Appends URL to the {@link URLClassLoader}. * * @param cl the classloader to add {@link URL} for. * @param url the {@link URL} to add. */ public static void addURL(ClassLoader cl, URL url) { if (cl instanceof URLClassLoader) { addURL0(cl, url); } else { addURL1(cl, url); } } /** * @return running VM version. */ public static int getVmVersion() { return (int) (Float.parseFloat(System.getProperty("java.class.version", "52" /* what? */)) - 44); } private static void addURL0(ClassLoader loader, URL url) { Method method; try { method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); } catch (NoSuchMethodException ex) { throw new RuntimeException("No 'addURL' method in java.net.URLClassLoader", ex); } method.setAccessible(true); try { method.invoke(loader, url); } catch (IllegalAccessException ex) { throw new IllegalStateException("'addURL' became inaccessible", ex); } catch (InvocationTargetException ex) { throw new RuntimeException("Error adding URL", ex.getTargetException()); } } private static void addURL1(ClassLoader loader, URL url) { Class<?> currentClass = loader.getClass(); do { Field field; try { field = currentClass.getDeclaredField("ucp"); } catch (NoSuchFieldException ignored) { continue; } field.setAccessible(true); Object ucp; try { ucp = field.get(loader); } catch (IllegalAccessException ex) { throw new IllegalStateException("'ucp' became inaccessible", ex); } String className; if (getVmVersion() < 9) { className = "sun.misc.URLClassPath"; } else { className = "jdk.internal.misc.URLClassPath"; } Method method; try { method = Class.forName(className, true, null).getDeclaredMethod("addURL", URL.class); } catch (NoSuchMethodException ex) { throw new RuntimeException("No 'addURL' method in " + className, ex); } catch (ClassNotFoundException ex) { throw new RuntimeException(className + " was not found", ex); } method.setAccessible(true); try { method.invoke(ucp, url); break; } catch (IllegalAccessException ex) { throw new IllegalStateException("'addURL' became inaccessible", ex); } catch (InvocationTargetException ex) { throw new RuntimeException("Error adding URL", ex.getTargetException()); } } while ((currentClass=currentClass.getSuperclass()) != Object.class); throw new IllegalArgumentException("No 'ucp' field in " + loader); } /** * Closes {@link URLClassLoader}. * * @param loader * Loader to close. * * @throws IOException * When I/O error occurs. */ public static void close(URLClassLoader loader) throws IOException { loader.close(); } /** * Sets parent class loader. * * @param loader * Loader to change parent for. * @param parent * New parent loader. */ public static void setParent(ClassLoader loader, ClassLoader parent) { Field field; try { field = ClassLoader.class.getDeclaredField("parent"); } catch (NoSuchFieldException ex) { throw new IllegalStateException("No 'parent' field in java.lang.ClassLoader", ex); } field.setAccessible(true); try { field.set(loader, parent); } catch (IllegalAccessException ex) { throw new IllegalStateException("'parent' became inaccessible", ex); } } /** * Initializes toolkit. */ public static void tkIint() { if (getVmVersion() < 9) { PlatformImpl.startup(() -> {}); } else { Method m; try { m = Platform.class.getDeclaredMethod("startup", Runnable.class); } catch (NoSuchMethodException ex) { throw new IllegalStateException("javafx.application.Platform.startup(Runnable) is missing", ex); } m.setAccessible(true); try { m.invoke(null, (Runnable) () -> {}); } catch (IllegalAccessException ex) { throw new IllegalStateException("'startup' became inaccessible", ex); } catch (InvocationTargetException ex) { throw new IllegalStateException("Unable to initialize toolkit", ex.getTargetException()); } } } }
[ "public", "final", "class", "VMUtil", "{", "/**\n * Deny all constructions.\n */", "private", "VMUtil", "(", ")", "{", "}", "/**\n * Appends URL to the {@link URLClassLoader}.\n *\n * @param cl the classloader to add {@link URL} for.\n * @param url the {@link URL} to add.\n */", "public", "static", "void", "addURL", "(", "ClassLoader", "cl", ",", "URL", "url", ")", "{", "if", "(", "cl", "instanceof", "URLClassLoader", ")", "{", "addURL0", "(", "cl", ",", "url", ")", ";", "}", "else", "{", "addURL1", "(", "cl", ",", "url", ")", ";", "}", "}", "/**\n * @return running VM version.\n */", "public", "static", "int", "getVmVersion", "(", ")", "{", "return", "(", "int", ")", "(", "Float", ".", "parseFloat", "(", "System", ".", "getProperty", "(", "\"", "java.class.version", "\"", ",", "\"", "52", "\"", "/* what? */", ")", ")", "-", "44", ")", ";", "}", "private", "static", "void", "addURL0", "(", "ClassLoader", "loader", ",", "URL", "url", ")", "{", "Method", "method", ";", "try", "{", "method", "=", "URLClassLoader", ".", "class", ".", "getDeclaredMethod", "(", "\"", "addURL", "\"", ",", "URL", ".", "class", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "No 'addURL' method in java.net.URLClassLoader", "\"", ",", "ex", ")", ";", "}", "method", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "method", ".", "invoke", "(", "loader", ",", "url", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "'addURL' became inaccessible", "\"", ",", "ex", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Error adding URL", "\"", ",", "ex", ".", "getTargetException", "(", ")", ")", ";", "}", "}", "private", "static", "void", "addURL1", "(", "ClassLoader", "loader", ",", "URL", "url", ")", "{", "Class", "<", "?", ">", "currentClass", "=", "loader", ".", "getClass", "(", ")", ";", "do", "{", "Field", "field", ";", "try", "{", "field", "=", "currentClass", ".", "getDeclaredField", "(", "\"", "ucp", "\"", ")", ";", "}", "catch", "(", "NoSuchFieldException", "ignored", ")", "{", "continue", ";", "}", "field", ".", "setAccessible", "(", "true", ")", ";", "Object", "ucp", ";", "try", "{", "ucp", "=", "field", ".", "get", "(", "loader", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "'ucp' became inaccessible", "\"", ",", "ex", ")", ";", "}", "String", "className", ";", "if", "(", "getVmVersion", "(", ")", "<", "9", ")", "{", "className", "=", "\"", "sun.misc.URLClassPath", "\"", ";", "}", "else", "{", "className", "=", "\"", "jdk.internal.misc.URLClassPath", "\"", ";", "}", "Method", "method", ";", "try", "{", "method", "=", "Class", ".", "forName", "(", "className", ",", "true", ",", "null", ")", ".", "getDeclaredMethod", "(", "\"", "addURL", "\"", ",", "URL", ".", "class", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "No 'addURL' method in ", "\"", "+", "className", ",", "ex", ")", ";", "}", "catch", "(", "ClassNotFoundException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "className", "+", "\"", " was not found", "\"", ",", "ex", ")", ";", "}", "method", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "method", ".", "invoke", "(", "ucp", ",", "url", ")", ";", "break", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "'addURL' became inaccessible", "\"", ",", "ex", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "\"", "Error adding URL", "\"", ",", "ex", ".", "getTargetException", "(", ")", ")", ";", "}", "}", "while", "(", "(", "currentClass", "=", "currentClass", ".", "getSuperclass", "(", ")", ")", "!=", "Object", ".", "class", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"", "No 'ucp' field in ", "\"", "+", "loader", ")", ";", "}", "/**\n * Closes {@link URLClassLoader}.\n *\n * @param loader\n * Loader to close.\n *\n * @throws IOException\n * When I/O error occurs.\n */", "public", "static", "void", "close", "(", "URLClassLoader", "loader", ")", "throws", "IOException", "{", "loader", ".", "close", "(", ")", ";", "}", "/**\n * Sets parent class loader.\n *\n * @param loader\n * Loader to change parent for.\n * @param parent\n * New parent loader.\n */", "public", "static", "void", "setParent", "(", "ClassLoader", "loader", ",", "ClassLoader", "parent", ")", "{", "Field", "field", ";", "try", "{", "field", "=", "ClassLoader", ".", "class", ".", "getDeclaredField", "(", "\"", "parent", "\"", ")", ";", "}", "catch", "(", "NoSuchFieldException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "No 'parent' field in java.lang.ClassLoader", "\"", ",", "ex", ")", ";", "}", "field", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "field", ".", "set", "(", "loader", ",", "parent", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "'parent' became inaccessible", "\"", ",", "ex", ")", ";", "}", "}", "/**\n * Initializes toolkit.\n */", "public", "static", "void", "tkIint", "(", ")", "{", "if", "(", "getVmVersion", "(", ")", "<", "9", ")", "{", "PlatformImpl", ".", "startup", "(", "(", ")", "->", "{", "}", ")", ";", "}", "else", "{", "Method", "m", ";", "try", "{", "m", "=", "Platform", ".", "class", ".", "getDeclaredMethod", "(", "\"", "startup", "\"", ",", "Runnable", ".", "class", ")", ";", "}", "catch", "(", "NoSuchMethodException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "javafx.application.Platform.startup(Runnable) is missing", "\"", ",", "ex", ")", ";", "}", "m", ".", "setAccessible", "(", "true", ")", ";", "try", "{", "m", ".", "invoke", "(", "null", ",", "(", "Runnable", ")", "(", ")", "->", "{", "}", ")", ";", "}", "catch", "(", "IllegalAccessException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "'startup' became inaccessible", "\"", ",", "ex", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "Unable to initialize toolkit", "\"", ",", "ex", ".", "getTargetException", "(", ")", ")", ";", "}", "}", "}", "}" ]
Dependent and non-dependent platform utilities for VM.
[ "Dependent", "and", "non", "-", "dependent", "platform", "utilities", "for", "VM", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84bc8bf42f1e25117718614bc938ce1078a48e71
MKLab-ITI/mklab-stream-manager
src/main/java/gr/iti/mklab/sfc/streams/impl/InstagramStream.java
[ "Apache-2.0" ]
Java
InstagramStream
/** * Class responsible for setting up the connection to Instagram API * for retrieving relevant Instagram content. * * @author manosetro - [email protected] */
Class responsible for setting up the connection to Instagram API for retrieving relevant Instagram content.
[ "Class", "responsible", "for", "setting", "up", "the", "connection", "to", "Instagram", "API", "for", "retrieving", "relevant", "Instagram", "content", "." ]
public class InstagramStream extends Stream { private Logger logger = LogManager.getLogger(InstagramStream.class); public static final Source SOURCE = Source.Instagram; @Override public void open(Configuration config) throws StreamException { logger.info("#Instagram : Open stream"); if (config == null) { logger.error("#Instagram : Config file is null."); return; } String key = config.getParameter(KEY); String secret = config.getParameter(SECRET); String token = config.getParameter(ACCESS_TOKEN); if (key == null || secret == null || token == null) { logger.error("#Instagram : Stream requires authentication."); throw new StreamException("Stream requires authentication."); } Credentials credentials = new Credentials(); credentials.setKey(key); credentials.setSecret(secret); credentials.setAccessToken(token); maxRequests = Integer.parseInt(config.getParameter(MAX_REQUESTS)); timeWindow = Long.parseLong(config.getParameter(TIME_WINDOW)); rateLimitsMonitor = new RateLimitsMonitor(maxRequests, timeWindow); retriever = new InstagramRetriever(credentials); } @Override public String getName() { return SOURCE.name(); } }
[ "public", "class", "InstagramStream", "extends", "Stream", "{", "private", "Logger", "logger", "=", "LogManager", ".", "getLogger", "(", "InstagramStream", ".", "class", ")", ";", "public", "static", "final", "Source", "SOURCE", "=", "Source", ".", "Instagram", ";", "@", "Override", "public", "void", "open", "(", "Configuration", "config", ")", "throws", "StreamException", "{", "logger", ".", "info", "(", "\"", "#Instagram : Open stream", "\"", ")", ";", "if", "(", "config", "==", "null", ")", "{", "logger", ".", "error", "(", "\"", "#Instagram : Config file is null.", "\"", ")", ";", "return", ";", "}", "String", "key", "=", "config", ".", "getParameter", "(", "KEY", ")", ";", "String", "secret", "=", "config", ".", "getParameter", "(", "SECRET", ")", ";", "String", "token", "=", "config", ".", "getParameter", "(", "ACCESS_TOKEN", ")", ";", "if", "(", "key", "==", "null", "||", "secret", "==", "null", "||", "token", "==", "null", ")", "{", "logger", ".", "error", "(", "\"", "#Instagram : Stream requires authentication.", "\"", ")", ";", "throw", "new", "StreamException", "(", "\"", "Stream requires authentication.", "\"", ")", ";", "}", "Credentials", "credentials", "=", "new", "Credentials", "(", ")", ";", "credentials", ".", "setKey", "(", "key", ")", ";", "credentials", ".", "setSecret", "(", "secret", ")", ";", "credentials", ".", "setAccessToken", "(", "token", ")", ";", "maxRequests", "=", "Integer", ".", "parseInt", "(", "config", ".", "getParameter", "(", "MAX_REQUESTS", ")", ")", ";", "timeWindow", "=", "Long", ".", "parseLong", "(", "config", ".", "getParameter", "(", "TIME_WINDOW", ")", ")", ";", "rateLimitsMonitor", "=", "new", "RateLimitsMonitor", "(", "maxRequests", ",", "timeWindow", ")", ";", "retriever", "=", "new", "InstagramRetriever", "(", "credentials", ")", ";", "}", "@", "Override", "public", "String", "getName", "(", ")", "{", "return", "SOURCE", ".", "name", "(", ")", ";", "}", "}" ]
Class responsible for setting up the connection to Instagram API for retrieving relevant Instagram content.
[ "Class", "responsible", "for", "setting", "up", "the", "connection", "to", "Instagram", "API", "for", "retrieving", "relevant", "Instagram", "content", "." ]
[]
[ { "param": "Stream", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Stream", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84bc94f30794cc16bfc620ca6d78d5ae34c96c42
jamezp/resteasy-examples
jaxrs2-async-pubsub-example/src/main/java/org/jboss/resteasy/example/pubsub/PubSubApplication.java
[ "Apache-2.0" ]
Java
PubSubApplication
/** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */
@author Bill Burke @version $Revision: 1 $
[ "@author", "Bill", "Burke", "@version", "$Revision", ":", "1", "$" ]
public class PubSubApplication extends Application { protected Set<Object> singletons = new HashSet<Object>(); public PubSubApplication() { singletons.add(new SubscriptionResource()); } @Override public Set<Object> getSingletons() { return singletons; } }
[ "public", "class", "PubSubApplication", "extends", "Application", "{", "protected", "Set", "<", "Object", ">", "singletons", "=", "new", "HashSet", "<", "Object", ">", "(", ")", ";", "public", "PubSubApplication", "(", ")", "{", "singletons", ".", "add", "(", "new", "SubscriptionResource", "(", ")", ")", ";", "}", "@", "Override", "public", "Set", "<", "Object", ">", "getSingletons", "(", ")", "{", "return", "singletons", ";", "}", "}" ]
@author <a href="mailto:[email protected]">Bill Burke</a> @version $Revision: 1 $
[ "@author", "<a", "href", "=", "\"", "mailto", ":", "bill@burkecentral", ".", "com", "\"", ">", "Bill", "Burke<", "/", "a", ">", "@version", "$Revision", ":", "1", "$" ]
[]
[ { "param": "Application", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Application", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84bde1d5b29342ccfd1f240193363cd435d9290c
UBICUA-JSSI/ssi
ursa/src/main/java/jssi/ursa/credential/CredentialPrimaryPublicKey.java
[ "Apache-2.0" ]
Java
CredentialPrimaryPublicKey
/** * Issuer's "Public Key" is used to verify the Issuer's signature over the Credential's attributes' values (primary credential). */
Issuer's "Public Key" is used to verify the Issuer's signature over the Credential's attributes' values (primary credential).
[ "Issuer", "'", "s", "\"", "Public", "Key", "\"", "is", "used", "to", "verify", "the", "Issuer", "'", "s", "signature", "over", "the", "Credential", "'", "s", "attributes", "'", "values", "(", "primary", "credential", ")", "." ]
public class CredentialPrimaryPublicKey { @JsonProperty("n") public BigInteger n; @JsonProperty("s") public BigInteger s; @JsonProperty("r") public Map<String, BigInteger> r; @JsonProperty("rctxt") public BigInteger rctxt; @JsonProperty("z") public BigInteger z; @JsonCreator public CredentialPrimaryPublicKey(@JsonProperty("n") BigInteger n, @JsonProperty("s") BigInteger s, @JsonProperty("rctxt") BigInteger rctxt, @JsonProperty("r") Map<String, BigInteger> r, @JsonProperty("z") BigInteger z){ this.n = n; this.s = s; this.r = r; this.rctxt = rctxt; this.z = z; } }
[ "public", "class", "CredentialPrimaryPublicKey", "{", "@", "JsonProperty", "(", "\"", "n", "\"", ")", "public", "BigInteger", "n", ";", "@", "JsonProperty", "(", "\"", "s", "\"", ")", "public", "BigInteger", "s", ";", "@", "JsonProperty", "(", "\"", "r", "\"", ")", "public", "Map", "<", "String", ",", "BigInteger", ">", "r", ";", "@", "JsonProperty", "(", "\"", "rctxt", "\"", ")", "public", "BigInteger", "rctxt", ";", "@", "JsonProperty", "(", "\"", "z", "\"", ")", "public", "BigInteger", "z", ";", "@", "JsonCreator", "public", "CredentialPrimaryPublicKey", "(", "@", "JsonProperty", "(", "\"", "n", "\"", ")", "BigInteger", "n", ",", "@", "JsonProperty", "(", "\"", "s", "\"", ")", "BigInteger", "s", ",", "@", "JsonProperty", "(", "\"", "rctxt", "\"", ")", "BigInteger", "rctxt", ",", "@", "JsonProperty", "(", "\"", "r", "\"", ")", "Map", "<", "String", ",", "BigInteger", ">", "r", ",", "@", "JsonProperty", "(", "\"", "z", "\"", ")", "BigInteger", "z", ")", "{", "this", ".", "n", "=", "n", ";", "this", ".", "s", "=", "s", ";", "this", ".", "r", "=", "r", ";", "this", ".", "rctxt", "=", "rctxt", ";", "this", ".", "z", "=", "z", ";", "}", "}" ]
Issuer's "Public Key" is used to verify the Issuer's signature over the Credential's attributes' values (primary credential).
[ "Issuer", "'", "s", "\"", "Public", "Key", "\"", "is", "used", "to", "verify", "the", "Issuer", "'", "s", "signature", "over", "the", "Credential", "'", "s", "attributes", "'", "values", "(", "primary", "credential", ")", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84bdf679ec3e6fce70266439caf66b5d9959e8ea
LobbyTech-MC/EcoPower
src/main/java/io/github/thebusybiscuit/ecopower/generators/HighEnergySolarGenerator.java
[ "MIT" ]
Java
HighEnergySolarGenerator
/** * The {@link HighEnergySolarGenerator} is simply a {@link SolarGenerator} which generates * a ton of energy. * * @author TheBusyBiscuit * */
The HighEnergySolarGenerator is simply a SolarGenerator which generates a ton of energy.
[ "The", "HighEnergySolarGenerator", "is", "simply", "a", "SolarGenerator", "which", "generates", "a", "ton", "of", "energy", "." ]
public class HighEnergySolarGenerator extends SolarGenerator { public HighEnergySolarGenerator(ItemGroup itemGroup, SlimefunItemStack item, RecipeType recipeType, ItemStack[] recipe, int energy) { super(itemGroup, energy, energy, item, recipeType, recipe); } }
[ "public", "class", "HighEnergySolarGenerator", "extends", "SolarGenerator", "{", "public", "HighEnergySolarGenerator", "(", "ItemGroup", "itemGroup", ",", "SlimefunItemStack", "item", ",", "RecipeType", "recipeType", ",", "ItemStack", "[", "]", "recipe", ",", "int", "energy", ")", "{", "super", "(", "itemGroup", ",", "energy", ",", "energy", ",", "item", ",", "recipeType", ",", "recipe", ")", ";", "}", "}" ]
The {@link HighEnergySolarGenerator} is simply a {@link SolarGenerator} which generates a ton of energy.
[ "The", "{", "@link", "HighEnergySolarGenerator", "}", "is", "simply", "a", "{", "@link", "SolarGenerator", "}", "which", "generates", "a", "ton", "of", "energy", "." ]
[]
[ { "param": "SolarGenerator", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SolarGenerator", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84be4440443b85050705cff28257edddae336a02
faboyds/Uniquiz
uniquiz/core/src/main/java/dto/SolutionDTO.java
[ "MIT" ]
Java
SolutionDTO
/** * Created by Rafael Santos on 08-09-2017. */
Created by Rafael Santos on 08-09-2017.
[ "Created", "by", "Rafael", "Santos", "on", "08", "-", "09", "-", "2017", "." ]
public class SolutionDTO { private Long pk; private Long quizPk; private String email; private byte rightAnswers; private byte wrongAnswers; public SolutionDTO(Long pk, Long quizPk, String email, byte rightAnswers, byte wrongAnswers){ this.setPk(pk); this.setQuizPk(quizPk); this.setEmail(email); this.setRightAnswers(rightAnswers); this.setWrongAnswers(wrongAnswers); } public SolutionDTO() { } public Long getPk() { return pk; } public void setPk(Long pk) { this.pk = pk; } public Long getQuizPk() { return quizPk; } public void setQuizPk(Long quizPk) { this.quizPk = quizPk; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public byte getRightAnswers() { return rightAnswers; } public void setRightAnswers(byte rightAnswers) { this.rightAnswers = rightAnswers; } public byte getWrongAnswers() { return wrongAnswers; } public void setWrongAnswers(byte wrongAnswers) { this.wrongAnswers = wrongAnswers; } }
[ "public", "class", "SolutionDTO", "{", "private", "Long", "pk", ";", "private", "Long", "quizPk", ";", "private", "String", "email", ";", "private", "byte", "rightAnswers", ";", "private", "byte", "wrongAnswers", ";", "public", "SolutionDTO", "(", "Long", "pk", ",", "Long", "quizPk", ",", "String", "email", ",", "byte", "rightAnswers", ",", "byte", "wrongAnswers", ")", "{", "this", ".", "setPk", "(", "pk", ")", ";", "this", ".", "setQuizPk", "(", "quizPk", ")", ";", "this", ".", "setEmail", "(", "email", ")", ";", "this", ".", "setRightAnswers", "(", "rightAnswers", ")", ";", "this", ".", "setWrongAnswers", "(", "wrongAnswers", ")", ";", "}", "public", "SolutionDTO", "(", ")", "{", "}", "public", "Long", "getPk", "(", ")", "{", "return", "pk", ";", "}", "public", "void", "setPk", "(", "Long", "pk", ")", "{", "this", ".", "pk", "=", "pk", ";", "}", "public", "Long", "getQuizPk", "(", ")", "{", "return", "quizPk", ";", "}", "public", "void", "setQuizPk", "(", "Long", "quizPk", ")", "{", "this", ".", "quizPk", "=", "quizPk", ";", "}", "public", "String", "getEmail", "(", ")", "{", "return", "email", ";", "}", "public", "void", "setEmail", "(", "String", "email", ")", "{", "this", ".", "email", "=", "email", ";", "}", "public", "byte", "getRightAnswers", "(", ")", "{", "return", "rightAnswers", ";", "}", "public", "void", "setRightAnswers", "(", "byte", "rightAnswers", ")", "{", "this", ".", "rightAnswers", "=", "rightAnswers", ";", "}", "public", "byte", "getWrongAnswers", "(", ")", "{", "return", "wrongAnswers", ";", "}", "public", "void", "setWrongAnswers", "(", "byte", "wrongAnswers", ")", "{", "this", ".", "wrongAnswers", "=", "wrongAnswers", ";", "}", "}" ]
Created by Rafael Santos on 08-09-2017.
[ "Created", "by", "Rafael", "Santos", "on", "08", "-", "09", "-", "2017", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84beda2e07c03e1101abdcf24e7821aab9f5753a
apyrgio/spring-boot-microservices-starter
MovieService/src/main/java/com/printezisn/moviestore/movieservice/movie/repositories/CustomMovieIndexRepositoryImpl.java
[ "MIT" ]
Java
CustomMovieIndexRepositoryImpl
/** * Implementation of the interface with extra repository methods for indexing * movies */
Implementation of the interface with extra repository methods for indexing movies
[ "Implementation", "of", "the", "interface", "with", "extra", "repository", "methods", "for", "indexing", "movies" ]
@RequiredArgsConstructor public class CustomMovieIndexRepositoryImpl implements CustomMovieIndexRepository { private static final String TITLE_FIELD = "title"; private static final String DESCRIPTION_FIELD = "description"; @Value("${elasticsearch.indexName}") private final String indexName; private final ElasticsearchTemplate elasticsearchTemplate; /** * {@inheritDoc} */ @Override public Page<MovieIndex> search(final Optional<String> text, final Pageable pageable) { final SearchQuery searchQuery; if (text.isPresent() && !text.get().isBlank()) { searchQuery = new NativeSearchQueryBuilder() .withIndices(indexName) .withQuery(multiMatchQuery("*" + text.get() + "*", TITLE_FIELD, DESCRIPTION_FIELD) .type(MultiMatchQueryBuilder.Type.BEST_FIELDS) .operator(Operator.AND) .fuzziness(Fuzziness.TWO)) .withPageable(pageable) .build(); } else { searchQuery = new NativeSearchQueryBuilder() .withIndices(indexName) .withQuery(matchAllQuery()) .withPageable(pageable) .build(); } elasticsearchTemplate.putMapping(MovieIndex.class); return elasticsearchTemplate.query(searchQuery, searchResponse -> { try { final ObjectMapper objectMapper = new ObjectMapper(); final long totalHits = searchResponse.getHits().getTotalHits(); final List<MovieIndex> results = new LinkedList<>(); for (final SearchHit hit : searchResponse.getHits().getHits()) { final MovieIndex searchMovie = objectMapper.readValue(hit.getSourceAsString(), MovieIndex.class); results.add(searchMovie); } return new PageImpl<MovieIndex>(results, pageable, totalHits); } catch (final Exception ex) { throw new RuntimeException(ex); } }); } }
[ "@", "RequiredArgsConstructor", "public", "class", "CustomMovieIndexRepositoryImpl", "implements", "CustomMovieIndexRepository", "{", "private", "static", "final", "String", "TITLE_FIELD", "=", "\"", "title", "\"", ";", "private", "static", "final", "String", "DESCRIPTION_FIELD", "=", "\"", "description", "\"", ";", "@", "Value", "(", "\"", "${elasticsearch.indexName}", "\"", ")", "private", "final", "String", "indexName", ";", "private", "final", "ElasticsearchTemplate", "elasticsearchTemplate", ";", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Page", "<", "MovieIndex", ">", "search", "(", "final", "Optional", "<", "String", ">", "text", ",", "final", "Pageable", "pageable", ")", "{", "final", "SearchQuery", "searchQuery", ";", "if", "(", "text", ".", "isPresent", "(", ")", "&&", "!", "text", ".", "get", "(", ")", ".", "isBlank", "(", ")", ")", "{", "searchQuery", "=", "new", "NativeSearchQueryBuilder", "(", ")", ".", "withIndices", "(", "indexName", ")", ".", "withQuery", "(", "multiMatchQuery", "(", "\"", "*", "\"", "+", "text", ".", "get", "(", ")", "+", "\"", "*", "\"", ",", "TITLE_FIELD", ",", "DESCRIPTION_FIELD", ")", ".", "type", "(", "MultiMatchQueryBuilder", ".", "Type", ".", "BEST_FIELDS", ")", ".", "operator", "(", "Operator", ".", "AND", ")", ".", "fuzziness", "(", "Fuzziness", ".", "TWO", ")", ")", ".", "withPageable", "(", "pageable", ")", ".", "build", "(", ")", ";", "}", "else", "{", "searchQuery", "=", "new", "NativeSearchQueryBuilder", "(", ")", ".", "withIndices", "(", "indexName", ")", ".", "withQuery", "(", "matchAllQuery", "(", ")", ")", ".", "withPageable", "(", "pageable", ")", ".", "build", "(", ")", ";", "}", "elasticsearchTemplate", ".", "putMapping", "(", "MovieIndex", ".", "class", ")", ";", "return", "elasticsearchTemplate", ".", "query", "(", "searchQuery", ",", "searchResponse", "->", "{", "try", "{", "final", "ObjectMapper", "objectMapper", "=", "new", "ObjectMapper", "(", ")", ";", "final", "long", "totalHits", "=", "searchResponse", ".", "getHits", "(", ")", ".", "getTotalHits", "(", ")", ";", "final", "List", "<", "MovieIndex", ">", "results", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "for", "(", "final", "SearchHit", "hit", ":", "searchResponse", ".", "getHits", "(", ")", ".", "getHits", "(", ")", ")", "{", "final", "MovieIndex", "searchMovie", "=", "objectMapper", ".", "readValue", "(", "hit", ".", "getSourceAsString", "(", ")", ",", "MovieIndex", ".", "class", ")", ";", "results", ".", "add", "(", "searchMovie", ")", ";", "}", "return", "new", "PageImpl", "<", "MovieIndex", ">", "(", "results", ",", "pageable", ",", "totalHits", ")", ";", "}", "catch", "(", "final", "Exception", "ex", ")", "{", "throw", "new", "RuntimeException", "(", "ex", ")", ";", "}", "}", ")", ";", "}", "}" ]
Implementation of the interface with extra repository methods for indexing movies
[ "Implementation", "of", "the", "interface", "with", "extra", "repository", "methods", "for", "indexing", "movies" ]
[]
[ { "param": "CustomMovieIndexRepository", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CustomMovieIndexRepository", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84c082985f38ccfa083cbc145e9d61c775b767ae
slachiewicz/maven-dependency-tree
src/main/java/org/apache/maven/shared/dependency/graph/filter/AndDependencyNodeFilter.java
[ "Apache-2.0" ]
Java
AndDependencyNodeFilter
/** * A dependency node filter that logically ANDs together a number of other dependency node filters. * * @author <a href="mailto:[email protected]">Mark Hobson</a> * @version $Id$ * @since 1.1 */
A dependency node filter that logically ANDs together a number of other dependency node filters. @author Mark Hobson @version $Id$ @since 1.1
[ "A", "dependency", "node", "filter", "that", "logically", "ANDs", "together", "a", "number", "of", "other", "dependency", "node", "filters", ".", "@author", "Mark", "Hobson", "@version", "$Id$", "@since", "1", ".", "1" ]
public class AndDependencyNodeFilter implements DependencyNodeFilter { // fields ----------------------------------------------------------------- /** * The dependency node filters that this filter ANDs together. */ private final List<DependencyNodeFilter> filters; // constructors ----------------------------------------------------------- /** * Creates a dependency node filter that logically ANDs together the two specified dependency node filters. * * @param filter1 the first dependency node filter to logically AND together * @param filter2 the second dependency node filter to logically AND together */ public AndDependencyNodeFilter( DependencyNodeFilter filter1, DependencyNodeFilter filter2 ) { this( Arrays.asList( filter1, filter2 ) ); } /** * Creates a dependency node filter that logically ANDs together the specified dependency node filters. * * @param filters the list of dependency node filters to logically AND together */ public AndDependencyNodeFilter( List<DependencyNodeFilter> filters ) { this.filters = Collections.unmodifiableList( filters ); } // DependencyNodeFilter methods ------------------------------------------- /** * {@inheritDoc} */ @Override public boolean accept( DependencyNode node ) { for ( DependencyNodeFilter filter : filters ) { if ( !filter.accept( node ) ) { return false; } } return true; } // public methods --------------------------------------------------------- /** * Gets the list of dependency node filters that this filter ANDs together. * * @return the dependency node filters that this filter ANDs together */ public List<DependencyNodeFilter> getDependencyNodeFilters() { return filters; } }
[ "public", "class", "AndDependencyNodeFilter", "implements", "DependencyNodeFilter", "{", "/**\n * The dependency node filters that this filter ANDs together.\n */", "private", "final", "List", "<", "DependencyNodeFilter", ">", "filters", ";", "/**\n * Creates a dependency node filter that logically ANDs together the two specified dependency node filters.\n * \n * @param filter1 the first dependency node filter to logically AND together\n * @param filter2 the second dependency node filter to logically AND together\n */", "public", "AndDependencyNodeFilter", "(", "DependencyNodeFilter", "filter1", ",", "DependencyNodeFilter", "filter2", ")", "{", "this", "(", "Arrays", ".", "asList", "(", "filter1", ",", "filter2", ")", ")", ";", "}", "/**\n * Creates a dependency node filter that logically ANDs together the specified dependency node filters.\n * \n * @param filters the list of dependency node filters to logically AND together\n */", "public", "AndDependencyNodeFilter", "(", "List", "<", "DependencyNodeFilter", ">", "filters", ")", "{", "this", ".", "filters", "=", "Collections", ".", "unmodifiableList", "(", "filters", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "boolean", "accept", "(", "DependencyNode", "node", ")", "{", "for", "(", "DependencyNodeFilter", "filter", ":", "filters", ")", "{", "if", "(", "!", "filter", ".", "accept", "(", "node", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "/**\n * Gets the list of dependency node filters that this filter ANDs together.\n * \n * @return the dependency node filters that this filter ANDs together\n */", "public", "List", "<", "DependencyNodeFilter", ">", "getDependencyNodeFilters", "(", ")", "{", "return", "filters", ";", "}", "}" ]
A dependency node filter that logically ANDs together a number of other dependency node filters.
[ "A", "dependency", "node", "filter", "that", "logically", "ANDs", "together", "a", "number", "of", "other", "dependency", "node", "filters", "." ]
[ "// fields -----------------------------------------------------------------", "// constructors -----------------------------------------------------------", "// DependencyNodeFilter methods -------------------------------------------", "// public methods ---------------------------------------------------------" ]
[ { "param": "DependencyNodeFilter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DependencyNodeFilter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84c15719195b278494779357214da270d21c7b49
paoliveira/graphhopper
tools/src/main/java/com/graphhopper/tools/Import.java
[ "Apache-2.0" ]
Java
Import
/** * @author Peter Karich */
@author Peter Karich
[ "@author", "Peter", "Karich" ]
public class Import { private static final Logger logger = LoggerFactory.getLogger(Import.class); public static void main(String[] strs) throws Exception { CmdArgs args = CmdArgs.read(strs); args = CmdArgs.readFromConfigAndMerge(args, "config", "graphhopper.config"); GraphHopper hopper = new GraphHopperOSM( SpatialRuleLookupHelper.createLandmarkSplittingFeatureCollection(args.get(Parameters.Landmark.PREPARE + "split_area_location", "")) ); SpatialRuleLookupHelper.buildAndInjectSpatialRuleIntoGH(hopper, args); hopper.init(args); hopper.importOrLoad(); hopper.close(); } }
[ "public", "class", "Import", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "Import", ".", "class", ")", ";", "public", "static", "void", "main", "(", "String", "[", "]", "strs", ")", "throws", "Exception", "{", "CmdArgs", "args", "=", "CmdArgs", ".", "read", "(", "strs", ")", ";", "args", "=", "CmdArgs", ".", "readFromConfigAndMerge", "(", "args", ",", "\"", "config", "\"", ",", "\"", "graphhopper.config", "\"", ")", ";", "GraphHopper", "hopper", "=", "new", "GraphHopperOSM", "(", "SpatialRuleLookupHelper", ".", "createLandmarkSplittingFeatureCollection", "(", "args", ".", "get", "(", "Parameters", ".", "Landmark", ".", "PREPARE", "+", "\"", "split_area_location", "\"", ",", "\"", "\"", ")", ")", ")", ";", "SpatialRuleLookupHelper", ".", "buildAndInjectSpatialRuleIntoGH", "(", "hopper", ",", "args", ")", ";", "hopper", ".", "init", "(", "args", ")", ";", "hopper", ".", "importOrLoad", "(", ")", ";", "hopper", ".", "close", "(", ")", ";", "}", "}" ]
@author Peter Karich
[ "@author", "Peter", "Karich" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84c210e038c1f861ec53ba314145e0a89029f190
olenagerasimova/takes
src/main/java/org/takes/facets/hamcrest/HmRsStatus.java
[ "MIT" ]
Java
HmRsStatus
/** * Response Status Matcher. * * <p>This "matcher" tests given response status code. * <p>The class is immutable and thread-safe. * * @since 0.13 */
Response Status Matcher. This "matcher" tests given response status code. The class is immutable and thread-safe.
[ "Response", "Status", "Matcher", ".", "This", "\"", "matcher", "\"", "tests", "given", "response", "status", "code", ".", "The", "class", "is", "immutable", "and", "thread", "-", "safe", "." ]
public final class HmRsStatus extends FeatureMatcher<Response, Integer> { /** * Description message. */ private static final String FEATURE_NAME = "HTTP status code"; /** * Create matcher using HTTP code. * @param val HTTP code value * @since 0.17 */ public HmRsStatus(final int val) { this(Matchers.equalTo(val)); } /** * Create matcher using HTTP code matcher. * @param matcher HTTP code matcher */ public HmRsStatus(final Matcher<Integer> matcher) { super(matcher, HmRsStatus.FEATURE_NAME, HmRsStatus.FEATURE_NAME); } @Override public Integer featureValueOf(final Response response) { try { final String head = response.head().iterator().next(); final String[] parts = head.split(" "); return Integer.parseInt(parts[1]); } catch (final IOException ex) { throw new IllegalStateException(ex); } } }
[ "public", "final", "class", "HmRsStatus", "extends", "FeatureMatcher", "<", "Response", ",", "Integer", ">", "{", "/**\n * Description message.\n */", "private", "static", "final", "String", "FEATURE_NAME", "=", "\"", "HTTP status code", "\"", ";", "/**\n * Create matcher using HTTP code.\n * @param val HTTP code value\n * @since 0.17\n */", "public", "HmRsStatus", "(", "final", "int", "val", ")", "{", "this", "(", "Matchers", ".", "equalTo", "(", "val", ")", ")", ";", "}", "/**\n * Create matcher using HTTP code matcher.\n * @param matcher HTTP code matcher\n */", "public", "HmRsStatus", "(", "final", "Matcher", "<", "Integer", ">", "matcher", ")", "{", "super", "(", "matcher", ",", "HmRsStatus", ".", "FEATURE_NAME", ",", "HmRsStatus", ".", "FEATURE_NAME", ")", ";", "}", "@", "Override", "public", "Integer", "featureValueOf", "(", "final", "Response", "response", ")", "{", "try", "{", "final", "String", "head", "=", "response", ".", "head", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "final", "String", "[", "]", "parts", "=", "head", ".", "split", "(", "\"", " ", "\"", ")", ";", "return", "Integer", ".", "parseInt", "(", "parts", "[", "1", "]", ")", ";", "}", "catch", "(", "final", "IOException", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "ex", ")", ";", "}", "}", "}" ]
Response Status Matcher.
[ "Response", "Status", "Matcher", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84c45b20c8c49f108f15d91e8ab1c7d368367467
cucina/opencucina
search/src/test/java/org/cucina/search/query/modifier/TranslatedMessageRestrictionCriteriaModiferTest.java
[ "Apache-2.0" ]
Java
TranslatedMessageRestrictionCriteriaModiferTest
/** * Tests TranslatedMessageRestrictionCriteriaModifer functions as expected. * * @author $Author: $ * @version $Revision: $ */
Tests TranslatedMessageRestrictionCriteriaModifer functions as expected. @author $Author: $ @version $Revision: $
[ "Tests", "TranslatedMessageRestrictionCriteriaModifer", "functions", "as", "expected", ".", "@author", "$Author", ":", "$", "@version", "$Revision", ":", "$" ]
public class TranslatedMessageRestrictionCriteriaModiferTest { private TranslatedMessageRestrictionCriteriaModifer modifier; /** * JAVADOC Method Level Comments */ @Before public void setup() { LocaleService localeService = mock(LocaleService.class); when(localeService.currentUserLocale()).thenReturn(Locale.ENGLISH); modifier = new TranslatedMessageRestrictionCriteriaModifer(localeService); } /** * Adds restriction criterion for users locale per TranslatedMessageWithJoinProjection. */ @Test public void testAddsCriterion() { Projection proj1 = new TranslatedMessageWithJoinProjection("tName", "tAlias", "foo"); Projection proj2 = new TranslatedMessageWithJoinProjection("tName2", "tAlias2", "foo"); SearchBean searchBean = new SearchBean(); searchBean.addProjection(new SimplePropertyProjection("name", "any", "foo")); searchBean.addProjection(proj1); searchBean.addProjection(proj2); modifier.modify(searchBean, null); Collection<SearchCriterion> criteria = searchBean.getCriteria(); assertEquals("incorrect number criterion added", 2, criteria.size()); boolean found1 = false; boolean found2 = false; proj1.setParentAliases(Collections.singletonMap("foo", "parent1")); proj2.setParentAliases(Collections.singletonMap("foo", "parent2")); for (SearchCriterion searchCriterion : criteria) { if ("parent1".equals(searchCriterion.getParentAliases().get("foo"))) { assertEquals("Incorrect rootAlias", "foo", searchCriterion.getRootAlias()); assertEquals("Incorrect value", "en", searchCriterion.getValues().get(0)); assertEquals("Incorrect name", "localeCd", searchCriterion.getName()); found1 = true; } if ("parent2".equals(searchCriterion.getParentAliases().get("foo"))) { assertEquals("Incorrect rootAlias", "foo", searchCriterion.getRootAlias()); assertEquals("Incorrect value", "en", searchCriterion.getValues().get(0)); assertEquals("Incorrect name", "localeCd", searchCriterion.getName()); found2 = true; } } assertTrue("tName criterion not found", found1); assertTrue("tName2 criterion not found", found2); } /** * Does nothing if no criteria of interest */ @Test public void testIgnoresIrrelevantCriterion() { SearchBean searchBean = new SearchBean(); searchBean.addProjection(new SimplePropertyProjection("name", "any", "foo")); modifier.modify(searchBean, null); Collection<SearchCriterion> criteria = searchBean.getCriteria(); assertEquals("incorrect number criterion added", 0, criteria.size()); } }
[ "public", "class", "TranslatedMessageRestrictionCriteriaModiferTest", "{", "private", "TranslatedMessageRestrictionCriteriaModifer", "modifier", ";", "/**\n\t * JAVADOC Method Level Comments\n\t */", "@", "Before", "public", "void", "setup", "(", ")", "{", "LocaleService", "localeService", "=", "mock", "(", "LocaleService", ".", "class", ")", ";", "when", "(", "localeService", ".", "currentUserLocale", "(", ")", ")", ".", "thenReturn", "(", "Locale", ".", "ENGLISH", ")", ";", "modifier", "=", "new", "TranslatedMessageRestrictionCriteriaModifer", "(", "localeService", ")", ";", "}", "/**\n\t * Adds restriction criterion for users locale per TranslatedMessageWithJoinProjection.\n\t */", "@", "Test", "public", "void", "testAddsCriterion", "(", ")", "{", "Projection", "proj1", "=", "new", "TranslatedMessageWithJoinProjection", "(", "\"", "tName", "\"", ",", "\"", "tAlias", "\"", ",", "\"", "foo", "\"", ")", ";", "Projection", "proj2", "=", "new", "TranslatedMessageWithJoinProjection", "(", "\"", "tName2", "\"", ",", "\"", "tAlias2", "\"", ",", "\"", "foo", "\"", ")", ";", "SearchBean", "searchBean", "=", "new", "SearchBean", "(", ")", ";", "searchBean", ".", "addProjection", "(", "new", "SimplePropertyProjection", "(", "\"", "name", "\"", ",", "\"", "any", "\"", ",", "\"", "foo", "\"", ")", ")", ";", "searchBean", ".", "addProjection", "(", "proj1", ")", ";", "searchBean", ".", "addProjection", "(", "proj2", ")", ";", "modifier", ".", "modify", "(", "searchBean", ",", "null", ")", ";", "Collection", "<", "SearchCriterion", ">", "criteria", "=", "searchBean", ".", "getCriteria", "(", ")", ";", "assertEquals", "(", "\"", "incorrect number criterion added", "\"", ",", "2", ",", "criteria", ".", "size", "(", ")", ")", ";", "boolean", "found1", "=", "false", ";", "boolean", "found2", "=", "false", ";", "proj1", ".", "setParentAliases", "(", "Collections", ".", "singletonMap", "(", "\"", "foo", "\"", ",", "\"", "parent1", "\"", ")", ")", ";", "proj2", ".", "setParentAliases", "(", "Collections", ".", "singletonMap", "(", "\"", "foo", "\"", ",", "\"", "parent2", "\"", ")", ")", ";", "for", "(", "SearchCriterion", "searchCriterion", ":", "criteria", ")", "{", "if", "(", "\"", "parent1", "\"", ".", "equals", "(", "searchCriterion", ".", "getParentAliases", "(", ")", ".", "get", "(", "\"", "foo", "\"", ")", ")", ")", "{", "assertEquals", "(", "\"", "Incorrect rootAlias", "\"", ",", "\"", "foo", "\"", ",", "searchCriterion", ".", "getRootAlias", "(", ")", ")", ";", "assertEquals", "(", "\"", "Incorrect value", "\"", ",", "\"", "en", "\"", ",", "searchCriterion", ".", "getValues", "(", ")", ".", "get", "(", "0", ")", ")", ";", "assertEquals", "(", "\"", "Incorrect name", "\"", ",", "\"", "localeCd", "\"", ",", "searchCriterion", ".", "getName", "(", ")", ")", ";", "found1", "=", "true", ";", "}", "if", "(", "\"", "parent2", "\"", ".", "equals", "(", "searchCriterion", ".", "getParentAliases", "(", ")", ".", "get", "(", "\"", "foo", "\"", ")", ")", ")", "{", "assertEquals", "(", "\"", "Incorrect rootAlias", "\"", ",", "\"", "foo", "\"", ",", "searchCriterion", ".", "getRootAlias", "(", ")", ")", ";", "assertEquals", "(", "\"", "Incorrect value", "\"", ",", "\"", "en", "\"", ",", "searchCriterion", ".", "getValues", "(", ")", ".", "get", "(", "0", ")", ")", ";", "assertEquals", "(", "\"", "Incorrect name", "\"", ",", "\"", "localeCd", "\"", ",", "searchCriterion", ".", "getName", "(", ")", ")", ";", "found2", "=", "true", ";", "}", "}", "assertTrue", "(", "\"", "tName criterion not found", "\"", ",", "found1", ")", ";", "assertTrue", "(", "\"", "tName2 criterion not found", "\"", ",", "found2", ")", ";", "}", "/**\n\t * Does nothing if no criteria of interest\n\t */", "@", "Test", "public", "void", "testIgnoresIrrelevantCriterion", "(", ")", "{", "SearchBean", "searchBean", "=", "new", "SearchBean", "(", ")", ";", "searchBean", ".", "addProjection", "(", "new", "SimplePropertyProjection", "(", "\"", "name", "\"", ",", "\"", "any", "\"", ",", "\"", "foo", "\"", ")", ")", ";", "modifier", ".", "modify", "(", "searchBean", ",", "null", ")", ";", "Collection", "<", "SearchCriterion", ">", "criteria", "=", "searchBean", ".", "getCriteria", "(", ")", ";", "assertEquals", "(", "\"", "incorrect number criterion added", "\"", ",", "0", ",", "criteria", ".", "size", "(", ")", ")", ";", "}", "}" ]
Tests TranslatedMessageRestrictionCriteriaModifer functions as expected.
[ "Tests", "TranslatedMessageRestrictionCriteriaModifer", "functions", "as", "expected", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84c6c096c147d9f331c2f59868478894d08f444e
sullis/lettuce-core
src/main/java/io/lettuce/core/dynamic/DefaultMethodParametersAccessor.java
[ "Apache-2.0" ]
Java
BindableParameterIterator
/** * Iterator class to allow traversing all bindable parameters inside the accessor. */
Iterator class to allow traversing all bindable parameters inside the accessor.
[ "Iterator", "class", "to", "allow", "traversing", "all", "bindable", "parameters", "inside", "the", "accessor", "." ]
static class BindableParameterIterator implements Iterator<Object> { private final int bindableParameterCount; private final DefaultMethodParametersAccessor accessor; private int currentIndex = 0; /** * Creates a new {@link BindableParameterIterator}. * * @param accessor must not be {@code null}. */ BindableParameterIterator(DefaultMethodParametersAccessor accessor) { LettuceAssert.notNull(accessor, "ParametersParameterAccessor must not be null!"); this.accessor = accessor; this.bindableParameterCount = accessor.getParameters().getBindableParameters().size(); } /** * Return the next bindable parameter. * * @return */ public Object next() { return accessor.getBindableValue(currentIndex++); } public boolean hasNext() { return bindableParameterCount > currentIndex; } public void remove() { throw new UnsupportedOperationException(); } }
[ "static", "class", "BindableParameterIterator", "implements", "Iterator", "<", "Object", ">", "{", "private", "final", "int", "bindableParameterCount", ";", "private", "final", "DefaultMethodParametersAccessor", "accessor", ";", "private", "int", "currentIndex", "=", "0", ";", "/**\n * Creates a new {@link BindableParameterIterator}.\n *\n * @param accessor must not be {@code null}.\n */", "BindableParameterIterator", "(", "DefaultMethodParametersAccessor", "accessor", ")", "{", "LettuceAssert", ".", "notNull", "(", "accessor", ",", "\"", "ParametersParameterAccessor must not be null!", "\"", ")", ";", "this", ".", "accessor", "=", "accessor", ";", "this", ".", "bindableParameterCount", "=", "accessor", ".", "getParameters", "(", ")", ".", "getBindableParameters", "(", ")", ".", "size", "(", ")", ";", "}", "/**\n * Return the next bindable parameter.\n *\n * @return\n */", "public", "Object", "next", "(", ")", "{", "return", "accessor", ".", "getBindableValue", "(", "currentIndex", "++", ")", ";", "}", "public", "boolean", "hasNext", "(", ")", "{", "return", "bindableParameterCount", ">", "currentIndex", ";", "}", "public", "void", "remove", "(", ")", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}" ]
Iterator class to allow traversing all bindable parameters inside the accessor.
[ "Iterator", "class", "to", "allow", "traversing", "all", "bindable", "parameters", "inside", "the", "accessor", "." ]
[]
[ { "param": "Iterator<Object>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Iterator<Object>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84cb656f809f77d75e31e379fb1fe475c27c860e
Per-Kristian/xacml-stuff
src/sunxacml/com/sun/xacml/attr/Base64.java
[ "BSD-3-Clause-No-Nuclear-Warranty" ]
Java
Base64
/** * Class that knows how to encode and decode Base64 values. Base64 * Content-Transfer-Encoding rules are defined in Section 6.8 of IETF RFC 2045 * <i>Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet * Message Bodies</i>, available at <a * href="ftp://ftp.isi.edu/in-notes/rfc2045.txt"> * <code>ftp://ftp.isi.edu/in-notes/rfc2045.txt</code></a>. * <p> * All methods of this class are static and thread-safe. * * @since 1.0 * @author Anne Anderson */
Class that knows how to encode and decode Base64 values. @since 1.0 @author Anne Anderson
[ "Class", "that", "knows", "how", "to", "encode", "and", "decode", "Base64", "values", ".", "@since", "1", ".", "0", "@author", "Anne", "Anderson" ]
class Base64 { /* * ASCII white-space characters. These are the ones recognized by the * C and Java language [pre-processors]. */ private static final char SPACE = 0x20; /* space, or blank, character */ private static final char ETX = 0x04; /* end-of-text character */ private static final char VTAB = 0x0b; /* vertical tab character */ private static final char FF = 0x0c; /* form-feed character */ private static final char HTAB = 0x09; /* horizontal tab character */ private static final char LF = 0x0a; /* line feed character */ private static final char ALTLF = 0x13; /* line feed on some systems */ private static final char CR = 0x0d; /* carriage-return character */ /* * The character used to pad out a 4-character Base64-encoded block, * or "quantum". */ private static char PAD = '='; /* * String used for BASE64 encoding and decoding. * * For index values 0-63, the character at each index is the Base-64 * encoded value of the index value. Index values beyond 63 are never * referenced during encoding, but are used in this implementation to * help in decoding. The character at index 64 is the Base64 pad * character '='. * * Charaters in index positions 0-64 MUST NOT be moved or altered, as * this will break the implementation. * * The characters after index 64 are white space characters that should be * ignored in Base64-encoded input strings while doing decoding. Note that * the white-space character set should include values used on various * platforms, since a Base64-encoded value may have been generated on a * non-Java platform. The values included here are those used in Java and * in C. * * The white-space character set may be modified without affecting the * implementation of the encoding algorithm. */ private static final String BASE64EncodingString = "ABCDEFGHIJ" + "KLMNOPQRST" + "UVWXYZabcd" + "efghijklmn" + "opqrstuvwx" + "yz01234567" + "89+/" + "=" + SPACE + ETX + VTAB + FF + HTAB + LF + ALTLF + CR; // Index of pad character in Base64EncodingString private static final int PAD_INDEX = 64; /* * The character in Base64EncodingString with the maximum * character value in Unicode. */ private static final int MAX_BASE64_CHAR = 'z'; /* * Array for mapping encoded characters to decoded values. * This array is initialized when needed by calling * initDecodeArray(). Only includes entries up to * MAX_BASE64_CHAR. */ private static int [] Base64DecodeArray = null; /* * State values used for decoding a quantum of four encoded input * characters as follows. * * Initial state: NO_CHARS_DECODED * NO_CHARS_DECODED: no characters have been decoded * on encoded char: decode char into output quantum; * new state: ONE_CHAR_DECODED * otherwise: Exception * ONE_CHAR_DECODED: one character has been decoded * on encoded char: decode char into output quantum; * new state: TWO_CHARS_DECODED * otherwise: Exception * TWO_CHARS_DECODED: two characters have been decoded * on encoded char: decode char into output quantum; * new state: THREE_CHARS_DECODED * on pad: write quantum byte 0 to output; * new state: PAD_THREE_READ * THREE_CHARS_DECODED: three characters have been decoded * on encoded char: decode char into output quantum; * write quantum bytes 0-2 to output; * new state: NO_CHARS_DECODED * on pad: write quantum bytes 0-1 to output; * new state: PAD_FOUR_READ * PAD_THREE_READ: pad character has been read as 3rd of 4 chars * on pad: new state: PAD_FOUR_READ * otherwise: Exception * PAD_FOUR_READ: pad character has been read as 4th of 4 char * on any char: Exception * * The valid terminal states are NO_CHARS_DECODED and PAD_FOUR_READ. */ private static final int NO_CHARS_DECODED = 0; private static final int ONE_CHAR_DECODED = 1; private static final int TWO_CHARS_DECODED = 2; private static final int THREE_CHARS_DECODED = 3; private static final int PAD_THREE_READ = 5; private static final int PAD_FOUR_READ = 6; /** * The maximum number of groups that should be encoded * onto a single line (so we don't exceed 76 characters * per line). */ private static final int MAX_GROUPS_PER_LINE = 76/4; /** * Encodes the input byte array into a Base64-encoded * <code>String</code>. The output <code>String</code> * has a CR LF (0x0d 0x0a) after every 76 bytes, but * not at the end. * <p> * <b>WARNING</b>: If the input byte array is modified * while encoding is in progress, the output is undefined. * * @param binaryValue the byte array to be encoded * * @return the Base64-encoded <code>String</code> */ public static String encode(byte[] binaryValue) { int binaryValueLen = binaryValue.length; // Estimated output length (about 1.4x input, due to CRLF) int maxChars = (binaryValueLen * 7) / 5; // Buffer for encoded output StringBuffer sb = new StringBuffer(maxChars); int groupsToEOL = MAX_GROUPS_PER_LINE; // Convert groups of 3 input bytes, with pad if < 3 in final for (int binaryValueNdx = 0; binaryValueNdx < binaryValueLen; binaryValueNdx += 3) { // Encode 1st 6-bit group int group1 = (binaryValue[binaryValueNdx] >> 2) & 0x3F; sb.append(BASE64EncodingString.charAt(group1)); // Encode 2nd 6-bit group int group2 = (binaryValue[binaryValueNdx] << 4) & 0x030; if ((binaryValueNdx+1) < binaryValueLen) { group2 = group2 | ((binaryValue[binaryValueNdx+1] >> 4) & 0xF); } sb.append(BASE64EncodingString.charAt(group2)); // Encode 3rd 6-bit group int group3; if ((binaryValueNdx+1) < binaryValueLen) { group3 = (binaryValue[binaryValueNdx+1] << 2) & 0x03C; if ((binaryValueNdx+2) < binaryValueLen) { group3 = group3 | ((binaryValue[binaryValueNdx+2] >> 6) & 0x3); } } else { group3 = PAD_INDEX; } sb.append(BASE64EncodingString.charAt(group3)); // Encode 4th 6-bit group int group4; if ((binaryValueNdx+2) < binaryValueLen) { group4 = binaryValue[binaryValueNdx+2] & 0x3F; } else { group4 = PAD_INDEX; } sb.append(BASE64EncodingString.charAt(group4)); // After every MAX_GROUPS_PER_LINE groups, insert CR LF. // Unless this is the final line, in which case we skip that. groupsToEOL = groupsToEOL - 1; if (groupsToEOL == 0) { groupsToEOL = MAX_GROUPS_PER_LINE; if ((binaryValueNdx+3) <= binaryValueLen) { sb.append(CR); sb.append(LF); } } } return sb.toString(); } /** * Initializes Base64DecodeArray, if this hasn't already been * done. */ private static void initDecodeArray() { if (Base64DecodeArray != null) return; int [] ourArray = new int [MAX_BASE64_CHAR+1]; for (int i = 0; i <= MAX_BASE64_CHAR; i++) ourArray[i] = BASE64EncodingString.indexOf(i); Base64DecodeArray = ourArray; } /** * Decodes a Base64-encoded <code>String</code>. The result * is returned in a byte array that should match the original * binary value (before encoding). Whitespace characters * in the input <code>String</code> are ignored. * <p> * If the <code>ignoreBadChars</code> parameter is * <code>true</code>, characters that are not allowed * in a BASE64-encoded string are ignored. Otherwise, * they cause an <code>IOException</code> to be raised. * * @param encoded a <code>String</code> containing a * Base64-encoded value * @param ignoreBadChars If <code>true</code>, bad characters * are ignored. Otherwise, they cause * an <code>IOException</code> to be * raised. * * @return a byte array containing the decoded value * * @throws IOException if the input <code>String</code> is not * a valid Base64-encoded value */ public static byte[] decode(String encoded, boolean ignoreBadChars) throws IOException { int encodedLen = encoded.length(); int maxBytes = (encodedLen/4)*3; /* Maximum possible output bytes */ ByteArrayOutputStream ba = /* Buffer for decoded output */ new ByteArrayOutputStream(maxBytes); byte[] quantum = new byte[3]; /* one output quantum */ // ensure Base64DecodeArray is initialized initDecodeArray(); /* * Every 4 encoded characters in input are converted to 3 bytes of * output. This is called one "quantum". Each encoded character is * mapped to one 6-bit unit of the output. Whitespace characters in * the input are passed over; they are not included in the output. */ int state = NO_CHARS_DECODED; for (int encodedNdx = 0; encodedNdx < encodedLen; encodedNdx++) { // Turn encoded char into decoded value int encodedChar = encoded.charAt(encodedNdx); int decodedChar; if (encodedChar > MAX_BASE64_CHAR) decodedChar = -1; else decodedChar = Base64DecodeArray[encodedChar]; // Handle white space and invalid characters if (decodedChar == -1) { if (ignoreBadChars) continue; throw new IOException("Invalid character"); } if (decodedChar > PAD_INDEX) { /* whitespace */ continue; } // Handle valid characters switch (state) { case NO_CHARS_DECODED: if (decodedChar == PAD_INDEX) { throw new IOException("Pad character in invalid position"); } quantum[0] = (byte) ((decodedChar << 2) & 0xFC); state = ONE_CHAR_DECODED; break; case ONE_CHAR_DECODED: if (decodedChar == PAD_INDEX) { throw new IOException("Pad character in invalid position"); } quantum[0] = (byte) (quantum[0] | ((decodedChar >> 4) & 0x3)); quantum[1] = (byte) ((decodedChar << 4) & 0xF0); state = TWO_CHARS_DECODED; break; case TWO_CHARS_DECODED: if (decodedChar == PAD_INDEX) { ba.write(quantum, 0, 1); state = PAD_THREE_READ; } else { quantum[1] = (byte) (quantum[1] | ((decodedChar >> 2) & 0x0F)); quantum[2] = (byte) ((decodedChar << 6) & 0xC0); state = THREE_CHARS_DECODED; } break; case THREE_CHARS_DECODED: if (decodedChar == PAD_INDEX) { ba.write(quantum, 0, 2); state = PAD_FOUR_READ; } else { quantum[2] = (byte) (quantum[2] | decodedChar); ba.write(quantum, 0, 3); state = NO_CHARS_DECODED; } break; case PAD_THREE_READ: if (decodedChar != PAD_INDEX) { throw new IOException("Missing pad character"); } state = PAD_FOUR_READ; break; case PAD_FOUR_READ: throw new IOException("Invalid input follows pad character"); } } // Test valid terminal states if (state != NO_CHARS_DECODED && state != PAD_FOUR_READ) throw new IOException("Invalid sequence of input characters"); return ba.toByteArray(); } }
[ "class", "Base64", "{", "/*\n * ASCII white-space characters. These are the ones recognized by the\n * C and Java language [pre-processors].\n */", "private", "static", "final", "char", "SPACE", "=", "0x20", ";", "/* space, or blank, character */", "private", "static", "final", "char", "ETX", "=", "0x04", ";", "/* end-of-text character */", "private", "static", "final", "char", "VTAB", "=", "0x0b", ";", "/* vertical tab character */", "private", "static", "final", "char", "FF", "=", "0x0c", ";", "/* form-feed character */", "private", "static", "final", "char", "HTAB", "=", "0x09", ";", "/* horizontal tab character */", "private", "static", "final", "char", "LF", "=", "0x0a", ";", "/* line feed character */", "private", "static", "final", "char", "ALTLF", "=", "0x13", ";", "/* line feed on some systems */", "private", "static", "final", "char", "CR", "=", "0x0d", ";", "/* carriage-return character */", "/*\n * The character used to pad out a 4-character Base64-encoded block,\n * or \"quantum\".\n */", "private", "static", "char", "PAD", "=", "'='", ";", "/*\n * String used for BASE64 encoding and decoding.\n *\n * For index values 0-63, the character at each index is the Base-64\n * encoded value of the index value. Index values beyond 63 are never\n * referenced during encoding, but are used in this implementation to\n * help in decoding. The character at index 64 is the Base64 pad\n * character '='.\n *\n * Charaters in index positions 0-64 MUST NOT be moved or altered, as\n * this will break the implementation.\n *\n * The characters after index 64 are white space characters that should be\n * ignored in Base64-encoded input strings while doing decoding. Note that\n * the white-space character set should include values used on various\n * platforms, since a Base64-encoded value may have been generated on a\n * non-Java platform. The values included here are those used in Java and\n * in C.\n *\n * The white-space character set may be modified without affecting the\n * implementation of the encoding algorithm.\n */", "private", "static", "final", "String", "BASE64EncodingString", "=", "\"", "ABCDEFGHIJ", "\"", "+", "\"", "KLMNOPQRST", "\"", "+", "\"", "UVWXYZabcd", "\"", "+", "\"", "efghijklmn", "\"", "+", "\"", "opqrstuvwx", "\"", "+", "\"", "yz01234567", "\"", "+", "\"", "89+/", "\"", "+", "\"", "=", "\"", "+", "SPACE", "+", "ETX", "+", "VTAB", "+", "FF", "+", "HTAB", "+", "LF", "+", "ALTLF", "+", "CR", ";", "private", "static", "final", "int", "PAD_INDEX", "=", "64", ";", "/*\n * The character in Base64EncodingString with the maximum\n * character value in Unicode.\n */", "private", "static", "final", "int", "MAX_BASE64_CHAR", "=", "'z'", ";", "/*\n * Array for mapping encoded characters to decoded values.\n * This array is initialized when needed by calling\n * initDecodeArray(). Only includes entries up to\n * MAX_BASE64_CHAR.\n */", "private", "static", "int", "[", "]", "Base64DecodeArray", "=", "null", ";", "/*\n * State values used for decoding a quantum of four encoded input\n * characters as follows.\n *\n * Initial state: NO_CHARS_DECODED\n * NO_CHARS_DECODED: no characters have been decoded\n * on encoded char: decode char into output quantum;\n * new state: ONE_CHAR_DECODED\n * otherwise: Exception\n * ONE_CHAR_DECODED: one character has been decoded\n * on encoded char: decode char into output quantum;\n * new state: TWO_CHARS_DECODED\n * otherwise: Exception\n * TWO_CHARS_DECODED: two characters have been decoded\n * on encoded char: decode char into output quantum;\n * new state: THREE_CHARS_DECODED\n * on pad: write quantum byte 0 to output;\n * new state: PAD_THREE_READ\n * THREE_CHARS_DECODED: three characters have been decoded\n * on encoded char: decode char into output quantum;\n * write quantum bytes 0-2 to output;\n * new state: NO_CHARS_DECODED\n * on pad: write quantum bytes 0-1 to output;\n * new state: PAD_FOUR_READ\n * PAD_THREE_READ: pad character has been read as 3rd of 4 chars\n * on pad: new state: PAD_FOUR_READ\n * otherwise: Exception\n * PAD_FOUR_READ: pad character has been read as 4th of 4 char\n * on any char: Exception\n *\n * The valid terminal states are NO_CHARS_DECODED and PAD_FOUR_READ.\n */", "private", "static", "final", "int", "NO_CHARS_DECODED", "=", "0", ";", "private", "static", "final", "int", "ONE_CHAR_DECODED", "=", "1", ";", "private", "static", "final", "int", "TWO_CHARS_DECODED", "=", "2", ";", "private", "static", "final", "int", "THREE_CHARS_DECODED", "=", "3", ";", "private", "static", "final", "int", "PAD_THREE_READ", "=", "5", ";", "private", "static", "final", "int", "PAD_FOUR_READ", "=", "6", ";", "/**\n * The maximum number of groups that should be encoded\n * onto a single line (so we don't exceed 76 characters\n * per line).\n */", "private", "static", "final", "int", "MAX_GROUPS_PER_LINE", "=", "76", "/", "4", ";", "/**\n * Encodes the input byte array into a Base64-encoded\n * <code>String</code>. The output <code>String</code>\n * has a CR LF (0x0d 0x0a) after every 76 bytes, but\n * not at the end.\n * <p>\n * <b>WARNING</b>: If the input byte array is modified\n * while encoding is in progress, the output is undefined.\n *\n * @param binaryValue the byte array to be encoded\n * \n * @return the Base64-encoded <code>String</code>\n */", "public", "static", "String", "encode", "(", "byte", "[", "]", "binaryValue", ")", "{", "int", "binaryValueLen", "=", "binaryValue", ".", "length", ";", "int", "maxChars", "=", "(", "binaryValueLen", "*", "7", ")", "/", "5", ";", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", "maxChars", ")", ";", "int", "groupsToEOL", "=", "MAX_GROUPS_PER_LINE", ";", "for", "(", "int", "binaryValueNdx", "=", "0", ";", "binaryValueNdx", "<", "binaryValueLen", ";", "binaryValueNdx", "+=", "3", ")", "{", "int", "group1", "=", "(", "binaryValue", "[", "binaryValueNdx", "]", ">>", "2", ")", "&", "0x3F", ";", "sb", ".", "append", "(", "BASE64EncodingString", ".", "charAt", "(", "group1", ")", ")", ";", "int", "group2", "=", "(", "binaryValue", "[", "binaryValueNdx", "]", "<<", "4", ")", "&", "0x030", ";", "if", "(", "(", "binaryValueNdx", "+", "1", ")", "<", "binaryValueLen", ")", "{", "group2", "=", "group2", "|", "(", "(", "binaryValue", "[", "binaryValueNdx", "+", "1", "]", ">>", "4", ")", "&", "0xF", ")", ";", "}", "sb", ".", "append", "(", "BASE64EncodingString", ".", "charAt", "(", "group2", ")", ")", ";", "int", "group3", ";", "if", "(", "(", "binaryValueNdx", "+", "1", ")", "<", "binaryValueLen", ")", "{", "group3", "=", "(", "binaryValue", "[", "binaryValueNdx", "+", "1", "]", "<<", "2", ")", "&", "0x03C", ";", "if", "(", "(", "binaryValueNdx", "+", "2", ")", "<", "binaryValueLen", ")", "{", "group3", "=", "group3", "|", "(", "(", "binaryValue", "[", "binaryValueNdx", "+", "2", "]", ">>", "6", ")", "&", "0x3", ")", ";", "}", "}", "else", "{", "group3", "=", "PAD_INDEX", ";", "}", "sb", ".", "append", "(", "BASE64EncodingString", ".", "charAt", "(", "group3", ")", ")", ";", "int", "group4", ";", "if", "(", "(", "binaryValueNdx", "+", "2", ")", "<", "binaryValueLen", ")", "{", "group4", "=", "binaryValue", "[", "binaryValueNdx", "+", "2", "]", "&", "0x3F", ";", "}", "else", "{", "group4", "=", "PAD_INDEX", ";", "}", "sb", ".", "append", "(", "BASE64EncodingString", ".", "charAt", "(", "group4", ")", ")", ";", "groupsToEOL", "=", "groupsToEOL", "-", "1", ";", "if", "(", "groupsToEOL", "==", "0", ")", "{", "groupsToEOL", "=", "MAX_GROUPS_PER_LINE", ";", "if", "(", "(", "binaryValueNdx", "+", "3", ")", "<=", "binaryValueLen", ")", "{", "sb", ".", "append", "(", "CR", ")", ";", "sb", ".", "append", "(", "LF", ")", ";", "}", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * Initializes Base64DecodeArray, if this hasn't already been\n * done.\n */", "private", "static", "void", "initDecodeArray", "(", ")", "{", "if", "(", "Base64DecodeArray", "!=", "null", ")", "return", ";", "int", "[", "]", "ourArray", "=", "new", "int", "[", "MAX_BASE64_CHAR", "+", "1", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "MAX_BASE64_CHAR", ";", "i", "++", ")", "ourArray", "[", "i", "]", "=", "BASE64EncodingString", ".", "indexOf", "(", "i", ")", ";", "Base64DecodeArray", "=", "ourArray", ";", "}", "/**\n * Decodes a Base64-encoded <code>String</code>. The result\n * is returned in a byte array that should match the original\n * binary value (before encoding). Whitespace characters\n * in the input <code>String</code> are ignored.\n * <p>\n * If the <code>ignoreBadChars</code> parameter is\n * <code>true</code>, characters that are not allowed\n * in a BASE64-encoded string are ignored. Otherwise,\n * they cause an <code>IOException</code> to be raised.\n *\n * @param encoded a <code>String</code> containing a\n * Base64-encoded value\n * @param ignoreBadChars If <code>true</code>, bad characters\n * are ignored. Otherwise, they cause\n * an <code>IOException</code> to be\n * raised.\n *\n * @return a byte array containing the decoded value\n *\n * @throws IOException if the input <code>String</code> is not\n * a valid Base64-encoded value\n */", "public", "static", "byte", "[", "]", "decode", "(", "String", "encoded", ",", "boolean", "ignoreBadChars", ")", "throws", "IOException", "{", "int", "encodedLen", "=", "encoded", ".", "length", "(", ")", ";", "int", "maxBytes", "=", "(", "encodedLen", "/", "4", ")", "*", "3", ";", "/* Maximum possible output bytes */", "ByteArrayOutputStream", "ba", "=", "/* Buffer for decoded output */", "new", "ByteArrayOutputStream", "(", "maxBytes", ")", ";", "byte", "[", "]", "quantum", "=", "new", "byte", "[", "3", "]", ";", "/* one output quantum */", "initDecodeArray", "(", ")", ";", "/*\n * Every 4 encoded characters in input are converted to 3 bytes of\n * output. This is called one \"quantum\". Each encoded character is\n * mapped to one 6-bit unit of the output. Whitespace characters in\n * the input are passed over; they are not included in the output.\n */", "int", "state", "=", "NO_CHARS_DECODED", ";", "for", "(", "int", "encodedNdx", "=", "0", ";", "encodedNdx", "<", "encodedLen", ";", "encodedNdx", "++", ")", "{", "int", "encodedChar", "=", "encoded", ".", "charAt", "(", "encodedNdx", ")", ";", "int", "decodedChar", ";", "if", "(", "encodedChar", ">", "MAX_BASE64_CHAR", ")", "decodedChar", "=", "-", "1", ";", "else", "decodedChar", "=", "Base64DecodeArray", "[", "encodedChar", "]", ";", "if", "(", "decodedChar", "==", "-", "1", ")", "{", "if", "(", "ignoreBadChars", ")", "continue", ";", "throw", "new", "IOException", "(", "\"", "Invalid character", "\"", ")", ";", "}", "if", "(", "decodedChar", ">", "PAD_INDEX", ")", "{", "/* whitespace */", "continue", ";", "}", "switch", "(", "state", ")", "{", "case", "NO_CHARS_DECODED", ":", "if", "(", "decodedChar", "==", "PAD_INDEX", ")", "{", "throw", "new", "IOException", "(", "\"", "Pad character in invalid position", "\"", ")", ";", "}", "quantum", "[", "0", "]", "=", "(", "byte", ")", "(", "(", "decodedChar", "<<", "2", ")", "&", "0xFC", ")", ";", "state", "=", "ONE_CHAR_DECODED", ";", "break", ";", "case", "ONE_CHAR_DECODED", ":", "if", "(", "decodedChar", "==", "PAD_INDEX", ")", "{", "throw", "new", "IOException", "(", "\"", "Pad character in invalid position", "\"", ")", ";", "}", "quantum", "[", "0", "]", "=", "(", "byte", ")", "(", "quantum", "[", "0", "]", "|", "(", "(", "decodedChar", ">>", "4", ")", "&", "0x3", ")", ")", ";", "quantum", "[", "1", "]", "=", "(", "byte", ")", "(", "(", "decodedChar", "<<", "4", ")", "&", "0xF0", ")", ";", "state", "=", "TWO_CHARS_DECODED", ";", "break", ";", "case", "TWO_CHARS_DECODED", ":", "if", "(", "decodedChar", "==", "PAD_INDEX", ")", "{", "ba", ".", "write", "(", "quantum", ",", "0", ",", "1", ")", ";", "state", "=", "PAD_THREE_READ", ";", "}", "else", "{", "quantum", "[", "1", "]", "=", "(", "byte", ")", "(", "quantum", "[", "1", "]", "|", "(", "(", "decodedChar", ">>", "2", ")", "&", "0x0F", ")", ")", ";", "quantum", "[", "2", "]", "=", "(", "byte", ")", "(", "(", "decodedChar", "<<", "6", ")", "&", "0xC0", ")", ";", "state", "=", "THREE_CHARS_DECODED", ";", "}", "break", ";", "case", "THREE_CHARS_DECODED", ":", "if", "(", "decodedChar", "==", "PAD_INDEX", ")", "{", "ba", ".", "write", "(", "quantum", ",", "0", ",", "2", ")", ";", "state", "=", "PAD_FOUR_READ", ";", "}", "else", "{", "quantum", "[", "2", "]", "=", "(", "byte", ")", "(", "quantum", "[", "2", "]", "|", "decodedChar", ")", ";", "ba", ".", "write", "(", "quantum", ",", "0", ",", "3", ")", ";", "state", "=", "NO_CHARS_DECODED", ";", "}", "break", ";", "case", "PAD_THREE_READ", ":", "if", "(", "decodedChar", "!=", "PAD_INDEX", ")", "{", "throw", "new", "IOException", "(", "\"", "Missing pad character", "\"", ")", ";", "}", "state", "=", "PAD_FOUR_READ", ";", "break", ";", "case", "PAD_FOUR_READ", ":", "throw", "new", "IOException", "(", "\"", "Invalid input follows pad character", "\"", ")", ";", "}", "}", "if", "(", "state", "!=", "NO_CHARS_DECODED", "&&", "state", "!=", "PAD_FOUR_READ", ")", "throw", "new", "IOException", "(", "\"", "Invalid sequence of input characters", "\"", ")", ";", "return", "ba", ".", "toByteArray", "(", ")", ";", "}", "}" ]
Class that knows how to encode and decode Base64 values.
[ "Class", "that", "knows", "how", "to", "encode", "and", "decode", "Base64", "values", "." ]
[ "// Index of pad character in Base64EncodingString", "// Estimated output length (about 1.4x input, due to CRLF)", "// Buffer for encoded output", "// Convert groups of 3 input bytes, with pad if < 3 in final", "// Encode 1st 6-bit group", "// Encode 2nd 6-bit group", "// Encode 3rd 6-bit group", "// Encode 4th 6-bit group", "// After every MAX_GROUPS_PER_LINE groups, insert CR LF.", "// Unless this is the final line, in which case we skip that.", "// ensure Base64DecodeArray is initialized", "// Turn encoded char into decoded value", "// Handle white space and invalid characters", "// Handle valid characters", "// Test valid terminal states" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
84cc5febc9d53ef0b309f66d12ee2f83753f6fd8
WilliamInOmniguider/MyFirstLib
app/src/main/java/com/wcom/wheeltest/verticaltablayout/test/FloorFragment.java
[ "MIT" ]
Java
FloorFragment
/** * Created by wiliiamwang on 20/10/2017. */
Created by wiliiamwang on 20/10/2017.
[ "Created", "by", "wiliiamwang", "on", "20", "/", "10", "/", "2017", "." ]
public class FloorFragment extends Fragment { Context mContext; View mView; TabLayout mTL; ViewPager mVP; public static FloorFragment newInstance(NMPArrayMap<String, String> content) { FloorFragment fragment = new FloorFragment(); Bundle bundle = new Bundle(); bundle.putSerializable("content", content); fragment.setArguments(bundle); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (mView == null) { mView = inflater.inflate(R.layout.fragment_floor, null, false); NMPArrayMap<String, String> content = (NMPArrayMap<String, String>) getArguments().getSerializable("content"); // TextView tv = (TextView) mView.findViewById(R.id.fragment_floor_tv); // tv.setText(content.keyAt(0) + "\n" + content.valueAt(0)); mVP = (ViewPager) mView.findViewById(R.id.fragment_floor_vp); mVP.setAdapter(new FloorExhibitAdapter(getChildFragmentManager(), content)); mTL = (TabLayout) mView.findViewById(R.id.fragment_floor_tl); mTL.setupWithViewPager(mVP); } return mView; } class FloorExhibitAdapter extends FragmentPagerAdapter { private NMPArrayMap<String, String> mFloorDataMap; public FloorExhibitAdapter(FragmentManager fm, NMPArrayMap<String, String> floorDataMap) { super(fm); mFloorDataMap = floorDataMap; } @Override public int getCount() { return mFloorDataMap.size(); } @Override public Fragment getItem(int position) { Log.e("@W@", "floor fragment getItem position : " + position); return PagerContentFragment.newInstance(mFloorDataMap.valueAt(position)); } @Override public CharSequence getPageTitle(int position) { return mFloorDataMap.keyAt(position); } } }
[ "public", "class", "FloorFragment", "extends", "Fragment", "{", "Context", "mContext", ";", "View", "mView", ";", "TabLayout", "mTL", ";", "ViewPager", "mVP", ";", "public", "static", "FloorFragment", "newInstance", "(", "NMPArrayMap", "<", "String", ",", "String", ">", "content", ")", "{", "FloorFragment", "fragment", "=", "new", "FloorFragment", "(", ")", ";", "Bundle", "bundle", "=", "new", "Bundle", "(", ")", ";", "bundle", ".", "putSerializable", "(", "\"", "content", "\"", ",", "content", ")", ";", "fragment", ".", "setArguments", "(", "bundle", ")", ";", "return", "fragment", ";", "}", "@", "Override", "public", "void", "onAttach", "(", "Context", "context", ")", "{", "super", ".", "onAttach", "(", "context", ")", ";", "mContext", "=", "context", ";", "}", "@", "Nullable", "@", "Override", "public", "View", "onCreateView", "(", "LayoutInflater", "inflater", ",", "@", "Nullable", "ViewGroup", "container", ",", "@", "Nullable", "Bundle", "savedInstanceState", ")", "{", "if", "(", "mView", "==", "null", ")", "{", "mView", "=", "inflater", ".", "inflate", "(", "R", ".", "layout", ".", "fragment_floor", ",", "null", ",", "false", ")", ";", "NMPArrayMap", "<", "String", ",", "String", ">", "content", "=", "(", "NMPArrayMap", "<", "String", ",", "String", ">", ")", "getArguments", "(", ")", ".", "getSerializable", "(", "\"", "content", "\"", ")", ";", "mVP", "=", "(", "ViewPager", ")", "mView", ".", "findViewById", "(", "R", ".", "id", ".", "fragment_floor_vp", ")", ";", "mVP", ".", "setAdapter", "(", "new", "FloorExhibitAdapter", "(", "getChildFragmentManager", "(", ")", ",", "content", ")", ")", ";", "mTL", "=", "(", "TabLayout", ")", "mView", ".", "findViewById", "(", "R", ".", "id", ".", "fragment_floor_tl", ")", ";", "mTL", ".", "setupWithViewPager", "(", "mVP", ")", ";", "}", "return", "mView", ";", "}", "class", "FloorExhibitAdapter", "extends", "FragmentPagerAdapter", "{", "private", "NMPArrayMap", "<", "String", ",", "String", ">", "mFloorDataMap", ";", "public", "FloorExhibitAdapter", "(", "FragmentManager", "fm", ",", "NMPArrayMap", "<", "String", ",", "String", ">", "floorDataMap", ")", "{", "super", "(", "fm", ")", ";", "mFloorDataMap", "=", "floorDataMap", ";", "}", "@", "Override", "public", "int", "getCount", "(", ")", "{", "return", "mFloorDataMap", ".", "size", "(", ")", ";", "}", "@", "Override", "public", "Fragment", "getItem", "(", "int", "position", ")", "{", "Log", ".", "e", "(", "\"", "@W@", "\"", ",", "\"", "floor fragment getItem position : ", "\"", "+", "position", ")", ";", "return", "PagerContentFragment", ".", "newInstance", "(", "mFloorDataMap", ".", "valueAt", "(", "position", ")", ")", ";", "}", "@", "Override", "public", "CharSequence", "getPageTitle", "(", "int", "position", ")", "{", "return", "mFloorDataMap", ".", "keyAt", "(", "position", ")", ";", "}", "}", "}" ]
Created by wiliiamwang on 20/10/2017.
[ "Created", "by", "wiliiamwang", "on", "20", "/", "10", "/", "2017", "." ]
[ "// TextView tv = (TextView) mView.findViewById(R.id.fragment_floor_tv);", "// tv.setText(content.keyAt(0) + \"\\n\" + content.valueAt(0));" ]
[ { "param": "Fragment", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Fragment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84d3c0f08b608674dfff3bd0276c10323857c3eb
natalisso/compilers-cin
antigo/ap3/antlr-cymbol-grammar-checker-types/src/autogenerated/CymbolBaseVisitor.java
[ "MIT" ]
Java
CymbolBaseVisitor
/** * This class provides an empty implementation of {@link CymbolVisitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */
This class provides an empty implementation of CymbolVisitor, which can be extended to create a visitor which only needs to handle a subset of the available methods. @param The return type of the visit operation. Use Void for operations with no return type.
[ "This", "class", "provides", "an", "empty", "implementation", "of", "CymbolVisitor", "which", "can", "be", "extended", "to", "create", "a", "visitor", "which", "only", "needs", "to", "handle", "a", "subset", "of", "the", "available", "methods", ".", "@param", "The", "return", "type", "of", "the", "visit", "operation", ".", "Use", "Void", "for", "operations", "with", "no", "return", "type", "." ]
public class CymbolBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements CymbolVisitor<T> { /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFile(CymbolParser.FileContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitVarDecl(CymbolParser.VarDeclContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFormTypeInt(CymbolParser.FormTypeIntContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFormTypeVoid(CymbolParser.FormTypeVoidContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFuncDecl(CymbolParser.FuncDeclContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitParamTypeList(CymbolParser.ParamTypeListContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitParamType(CymbolParser.ParamTypeContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitBlock(CymbolParser.BlockContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitAssignStat(CymbolParser.AssignStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitReturnStat(CymbolParser.ReturnStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIfElseStat(CymbolParser.IfElseStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIfElseExprStat(CymbolParser.IfElseExprStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitExprStat(CymbolParser.ExprStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitExprList(CymbolParser.ExprListContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIfStat(CymbolParser.IfStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitElseStat(CymbolParser.ElseStatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitStat(CymbolParser.StatContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitSignedExpr(CymbolParser.SignedExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitFunctionCallExpr(CymbolParser.FunctionCallExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitMulDivExpr(CymbolParser.MulDivExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitComparisonExpr(CymbolParser.ComparisonExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitEqExpr(CymbolParser.EqExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitNotExpr(CymbolParser.NotExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitIntExpr(CymbolParser.IntExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitParenExpr(CymbolParser.ParenExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitAddSubExpr(CymbolParser.AddSubExprContext ctx) { return visitChildren(ctx); } /** * {@inheritDoc} * * <p>The default implementation returns the result of calling * {@link #visitChildren} on {@code ctx}.</p> */ @Override public T visitVarIdExpr(CymbolParser.VarIdExprContext ctx) { return visitChildren(ctx); } }
[ "public", "class", "CymbolBaseVisitor", "<", "T", ">", "extends", "AbstractParseTreeVisitor", "<", "T", ">", "implements", "CymbolVisitor", "<", "T", ">", "{", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitFile", "(", "CymbolParser", ".", "FileContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitVarDecl", "(", "CymbolParser", ".", "VarDeclContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitFormTypeInt", "(", "CymbolParser", ".", "FormTypeIntContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitFormTypeVoid", "(", "CymbolParser", ".", "FormTypeVoidContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitFuncDecl", "(", "CymbolParser", ".", "FuncDeclContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitParamTypeList", "(", "CymbolParser", ".", "ParamTypeListContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitParamType", "(", "CymbolParser", ".", "ParamTypeContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitBlock", "(", "CymbolParser", ".", "BlockContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitAssignStat", "(", "CymbolParser", ".", "AssignStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitReturnStat", "(", "CymbolParser", ".", "ReturnStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitIfElseStat", "(", "CymbolParser", ".", "IfElseStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitIfElseExprStat", "(", "CymbolParser", ".", "IfElseExprStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitExprStat", "(", "CymbolParser", ".", "ExprStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitExprList", "(", "CymbolParser", ".", "ExprListContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitIfStat", "(", "CymbolParser", ".", "IfStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitElseStat", "(", "CymbolParser", ".", "ElseStatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitStat", "(", "CymbolParser", ".", "StatContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitSignedExpr", "(", "CymbolParser", ".", "SignedExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitFunctionCallExpr", "(", "CymbolParser", ".", "FunctionCallExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitMulDivExpr", "(", "CymbolParser", ".", "MulDivExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitComparisonExpr", "(", "CymbolParser", ".", "ComparisonExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitEqExpr", "(", "CymbolParser", ".", "EqExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitNotExpr", "(", "CymbolParser", ".", "NotExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitIntExpr", "(", "CymbolParser", ".", "IntExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitParenExpr", "(", "CymbolParser", ".", "ParenExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitAddSubExpr", "(", "CymbolParser", ".", "AddSubExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "/**\r\n\t * {@inheritDoc}\r\n\t *\r\n\t * <p>The default implementation returns the result of calling\r\n\t * {@link #visitChildren} on {@code ctx}.</p>\r\n\t */", "@", "Override", "public", "T", "visitVarIdExpr", "(", "CymbolParser", ".", "VarIdExprContext", "ctx", ")", "{", "return", "visitChildren", "(", "ctx", ")", ";", "}", "}" ]
This class provides an empty implementation of {@link CymbolVisitor}, which can be extended to create a visitor which only needs to handle a subset of the available methods.
[ "This", "class", "provides", "an", "empty", "implementation", "of", "{", "@link", "CymbolVisitor", "}", "which", "can", "be", "extended", "to", "create", "a", "visitor", "which", "only", "needs", "to", "handle", "a", "subset", "of", "the", "available", "methods", "." ]
[]
[ { "param": "CymbolVisitor<T>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CymbolVisitor<T>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84ddc11f4d17fc4a0ca59707ffe0d9b27783a418
jvillemare/aloe-ha
GardenProject/src/main/java/udel/GardenProject/plotObjects/special/PlotBench.java
[ "MIT" ]
Java
PlotBench
/** * Place to sit. * * @version 1.0 * @author Team 0 * @see {@link udel.GardenProject.plotObjects.PlotObject} */
Place to sit.
[ "Place", "to", "sit", "." ]
public class PlotBench extends GenericSpecial implements Serializable { private static final long serialVersionUID = 1L; /** * Path to an image of a bench for window view. */ private static String windowBench = "/viewImages/bench.png"; /** * Path to an image of a bench for plot design. */ private static String plotBench = "/viewImages/plotBench.png"; /** * Name of Object */ private static String name = "Bench"; /** * Constructor. * @param x Horizontal position. * @param y Vertical position. */ public PlotBench(Model model, double x, double y) { super(model, x, y, 2.0, 5.0, windowBench, plotBench, name); } }
[ "public", "class", "PlotBench", "extends", "GenericSpecial", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n\t * Path to an image of a bench for window view.\n\t */", "private", "static", "String", "windowBench", "=", "\"", "/viewImages/bench.png", "\"", ";", "/**\n\t * Path to an image of a bench for plot design.\n\t */", "private", "static", "String", "plotBench", "=", "\"", "/viewImages/plotBench.png", "\"", ";", "/**\n * Name of Object\n */", "private", "static", "String", "name", "=", "\"", "Bench", "\"", ";", "/**\n\t * Constructor.\n\t * @param x\tHorizontal position.\n\t * @param y Vertical position.\n\t */", "public", "PlotBench", "(", "Model", "model", ",", "double", "x", ",", "double", "y", ")", "{", "super", "(", "model", ",", "x", ",", "y", ",", "2.0", ",", "5.0", ",", "windowBench", ",", "plotBench", ",", "name", ")", ";", "}", "}" ]
Place to sit.
[ "Place", "to", "sit", "." ]
[]
[ { "param": "GenericSpecial", "type": null }, { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GenericSpecial", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84de30f2031730eb39e5a4eb8fc21718989665b0
fideoman/geronimo
framework/modules/geronimo-security/src/main/java/org/apache/geronimo/security/keystore/FileKeystoreManager.java
[ "Apache-2.0" ]
Java
FileKeystoreManager
/** * An implementation of KeystoreManager that assumes every file in a specified * directory is a keystore. * * @version $Rev$ $Date$ */
An implementation of KeystoreManager that assumes every file in a specified directory is a keystore. @version $Rev$ $Date$
[ "An", "implementation", "of", "KeystoreManager", "that", "assumes", "every", "file", "in", "a", "specified", "directory", "is", "a", "keystore", ".", "@version", "$Rev$", "$Date$" ]
public class FileKeystoreManager implements KeystoreManager, GBeanLifecycle { private static final Logger log = LoggerFactory.getLogger(FileKeystoreManager.class); private File directory; private ServerInfo serverInfo; private URI configuredDir; private Collection keystores; private Kernel kernel; public FileKeystoreManager(URI keystoreDir, ServerInfo serverInfo, Collection keystores, Kernel kernel) { configuredDir = keystoreDir; this.serverInfo = serverInfo; this.keystores = keystores; this.kernel = kernel; } public void doStart() throws Exception { URI rootURI; if (serverInfo != null) { rootURI = serverInfo.resolveServer(configuredDir); } else { rootURI = configuredDir; } if (!rootURI.getScheme().equals("file")) { throw new IllegalStateException("FileKeystoreManager must have a root that's a local directory (not " + rootURI + ")"); } directory = new File(rootURI); if (!directory.exists()) { if (directory.mkdirs()) { log.warn("The keystore directory: " + directory.getAbsolutePath() + " does not exist. System automatically created one."); } } if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) { throw new IllegalStateException("FileKeystoreManager must have a root that's a valid readable directory (not " + directory.getAbsolutePath() + ")"); } log.debug("Keystore directory is " + directory.getAbsolutePath()); } public void doStop() throws Exception { } public void doFail() { } public void initializeKeystores() { getKeystores(); } public String[] listKeystoreFiles() { File[] files = directory.listFiles(); List list = new ArrayList(); for (int i = 0; i < files.length; i++) { File file = files[i]; if(file.canRead() && !file.isDirectory()) { String name = file.getName(); if (name.lastIndexOf(".") == -1) { list.add(file.getName()); } else { String type = name.substring(name.lastIndexOf(".") + 1); if (file.length()> 0){ for(String ktype : KeystoreUtil.keystoreTypes ){ if (ktype.toLowerCase().equals(type.toLowerCase())){ list.add(file.getName()); } } } else if (file.length() == 0){ for (String ktype : KeystoreUtil.emptyKeystoreTypes){ if (ktype.toLowerCase().equals(type.toLowerCase())){ list.add(file.getName()); } } } } } } return (String[]) list.toArray(new String[list.size()]); } public KeystoreInstance[] getKeystores() { String[] names = listKeystoreFiles(); KeystoreInstance[] result = new KeystoreInstance[names.length]; for (int i = 0; i < result.length; i++) { result[i] = getKeystore(names[i], null); if(result[i] == null) { return null; } } return result; } public KeystoreInstance getKeystore(String name, String type) { for (Iterator it = keystores.iterator(); it.hasNext();) { KeystoreInstance instance = (KeystoreInstance) it.next(); if(instance.getKeystoreName().equals(name)) { return instance; } } File test = new File(directory, name); if(!test.exists() || !test.canRead()) { throw new IllegalArgumentException("Cannot access keystore "+test.getAbsolutePath()+"!"); } AbstractName aName; AbstractName myName = kernel.getAbstractNameFor(this); aName = kernel.getNaming().createSiblingName(myName, name, SecurityNames.KEYSTORE_INSTANCE); GBeanData data = new GBeanData(aName, FileKeystoreInstance.getGBeanInfo()); try { String path = configuredDir.toString(); if(!path.endsWith("/")) { path += "/"; } data.setAttribute("keystorePath", new URI(path +name)); } catch (URISyntaxException e) { throw new IllegalStateException("Can't resolve keystore path: "+e.getMessage(), e); } data.setReferencePattern("ServerInfo", kernel.getAbstractNameFor(serverInfo)); data.setAttribute("keystoreName", name); if(type == null) { if(name.lastIndexOf(".") == -1) { type = KeystoreUtil.defaultType; log.warn("keystoreType for new keystore \""+name+"\" set to default type \""+type+"\"."); } else { type = name.substring(name.lastIndexOf(".")+1); log.warn("keystoreType for new keystore \""+name+"\" set to \""+type+"\" based on file extension."); } } data.setAttribute("keystoreType", type); EditableConfigurationManager mgr = ConfigurationUtil.getEditableConfigurationManager(kernel); if(mgr != null) { try { mgr.addGBeanToConfiguration(myName.getArtifact(), data, true); return (KeystoreInstance) kernel.getProxyManager().createProxy(aName, KeystoreInstance.class); } catch (InvalidConfigException e) { log.error("Should never happen", e); throw new IllegalStateException("Unable to add Keystore GBean ("+e.getMessage()+")", e); } finally { ConfigurationUtil.releaseConfigurationManager(kernel, mgr); } } else { log.warn("The ConfigurationManager in the kernel does not allow changes at runtime"); return null; } } /** * Gets a SocketFactory using one Keystore to access the private key * and another to provide the list of trusted certificate authorities. * * @param provider The SSL provider to use, or null for the default * @param protocol The SSL protocol to use * @param algorithm The SSL algorithm to use * @param trustStore The trust keystore name as provided by listKeystores. * The KeystoreInstance for this keystore must have * unlocked this key. * @param loader The class loader used to resolve factory classes. * * @return A created SSLSocketFactory item created from the KeystoreManager. * @throws KeystoreIsLocked * Occurs when the requested key keystore cannot * be used because it has not been unlocked. * @throws KeyIsLocked * Occurs when the requested private key in the key * keystore cannot be used because it has not been * unlocked. * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyStoreException * @throws KeyManagementException * @throws NoSuchProviderException */ public SSLSocketFactory createSSLFactory(String provider, String protocol, String algorithm, String trustStore, ClassLoader loader) throws KeystoreException { // typically, the keyStore and the keyAlias are not required if authentication is also not required. return createSSLFactory(provider, protocol, algorithm, null, null, trustStore, loader); } /** * Gets a SocketFactory using one Keystore to access the private key * and another to provide the list of trusted certificate authorities. * * @param provider The SSL provider to use, or null for the default * @param protocol The SSL protocol to use * @param algorithm The SSL algorithm to use * @param keyStore The key keystore name as provided by listKeystores. The * KeystoreInstance for this keystore must be unlocked. * @param keyAlias The name of the private key in the keystore. The * KeystoreInstance for this keystore must have unlocked * this key. * @param trustStore The trust keystore name as provided by listKeystores. * The KeystoreInstance for this keystore must have * unlocked this key. * @param loader The class loader used to resolve factory classes. * * @return A created SSLSocketFactory item created from the KeystoreManager. * @throws KeystoreIsLocked * Occurs when the requested key keystore cannot * be used because it has not been unlocked. * @throws KeyIsLocked * Occurs when the requested private key in the key * keystore cannot be used because it has not been * unlocked. * @throws KeystoreException */ public SSLSocketFactory createSSLFactory(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore, ClassLoader loader) throws KeystoreException { // the keyStore is optional. KeystoreInstance keyInstance = null; if (keyStore != null) { keyInstance = getKeystore(keyStore, null); if(keyInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '"+keyStore+"' is locked; please use the keystore page in the admin console to unlock it"); } if(keyInstance.isKeyLocked(keyAlias)) { throw new KeystoreIsLocked("Key '"+keyAlias+"' in keystore '"+keyStore+"' is locked; please use the keystore page in the admin console to unlock it"); } } KeystoreInstance trustInstance = trustStore == null ? null : getKeystore(trustStore, null); if(trustInstance != null && trustInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '"+trustStore+"' is locked; please use the keystore page in the admin console to unlock it"); } // OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way! try { Class cls = loader.loadClass("javax.net.ssl.SSLContext"); Object ctx = cls.getMethod("getInstance", new Class[] {String.class}).invoke(null, new Object[]{protocol}); Class kmc = Class.forName("[Ljavax.net.ssl.KeyManager;", false, loader); Class tmc = Class.forName("[Ljavax.net.ssl.TrustManager;", false, loader); Class src = loader.loadClass("java.security.SecureRandom"); cls.getMethod("init", new Class[]{kmc, tmc, src}).invoke(ctx, new Object[]{ keyInstance == null ? null : keyInstance.getKeyManager(algorithm, keyAlias, null), trustInstance == null ? null : trustInstance.getTrustManager(algorithm, null), new java.security.SecureRandom()}); Object result = cls.getMethod("getSocketFactory", new Class[0]).invoke(ctx, new Object[0]); return (SSLSocketFactory) result; } catch (Exception e) { throw new KeystoreException("Unable to create SSL Factory", e); } } /** * Gets a ServerSocketFactory using one Keystore to access the private key * and another to provide the list of trusted certificate authorities. * @param provider The SSL provider to use, or null for the default * @param protocol The SSL protocol to use * @param algorithm The SSL algorithm to use * @param keyStore The key keystore name as provided by listKeystores. The * KeystoreInstance for this keystore must be unlocked. * @param keyAlias The name of the private key in the keystore. The * KeystoreInstance for this keystore must have unlocked * this key. * @param trustStore The trust keystore name as provided by listKeystores. * The KeystoreInstance for this keystore must have * unlocked this key. * @param loader The class loader used to resolve factory classes. * * @throws KeystoreIsLocked Occurs when the requested key keystore cannot * be used because it has not been unlocked. * @throws KeyIsLocked Occurs when the requested private key in the key * keystore cannot be used because it has not been * unlocked. */ public SSLServerSocketFactory createSSLServerFactory(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore, ClassLoader loader) throws KeystoreException { SSLContext sslContext = createSSLContext(provider, protocol, algorithm, keyStore, keyAlias, trustStore, loader); // OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way! try { Object result = sslContext.getClass().getMethod("getServerSocketFactory", new Class[0]).invoke(sslContext, new Object[0]); return (SSLServerSocketFactory) result; } catch (Exception e) { throw new KeystoreException("Unable to create SSL Server Factory", e); } } /** * Gets a ServerSocketFactory using one Keystore to access the private key * and another to provide the list of trusted certificate authorities. * @param provider The SSL provider to use, or null for the default * @param protocol The SSL protocol to use * @param algorithm The SSL algorithm to use * @param keyStore The key keystore name as provided by listKeystores. The * KeystoreInstance for this keystore must be unlocked. * @param keyAlias The name of the private key in the keystore. The * KeystoreInstance for this keystore must have unlocked * this key. * @param trustStore The trust keystore name as provided by listKeystores. * The KeystoreInstance for this keystore must have * unlocked this key. * @param loader The class loader used to resolve factory classes. * * @return SSLContext using the security info provided * @throws KeystoreIsLocked Occurs when the requested key keystore cannot * be used because it has not been unlocked. * @throws KeyIsLocked Occurs when the requested private key in the key * keystore cannot be used because it has not been * unlocked. */ public SSLContext createSSLContext(String provider, String protocol, String algorithm, String keyStore, String keyAlias, String trustStore, ClassLoader loader) throws KeystoreException { KeystoreInstance keyInstance = getKeystore(keyStore, null); if(keyInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '"+keyStore+"' is locked; please use the keystore page in the admin console to unlock it"); } if(keyInstance.isKeyLocked(keyAlias)) { throw new KeystoreIsLocked("Key '"+keyAlias+"' in keystore '"+keyStore+"' is locked; please use the keystore page in the admin console to unlock it"); } KeystoreInstance trustInstance = trustStore == null ? null : getKeystore(trustStore, null); if(trustInstance != null && trustInstance.isKeystoreLocked()) { throw new KeystoreIsLocked("Keystore '"+trustStore+"' is locked; please use the keystore page in the admin console to unlock it"); } // OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way! try { Class cls = loader.loadClass("javax.net.ssl.SSLContext"); Object ctx = cls.getMethod("getInstance", new Class[] {String.class}).invoke(null, new Object[]{protocol}); Class kmc = Class.forName("[Ljavax.net.ssl.KeyManager;", false, loader); Class tmc = Class.forName("[Ljavax.net.ssl.TrustManager;", false, loader); Class src = loader.loadClass("java.security.SecureRandom"); cls.getMethod("init", new Class[]{kmc, tmc, src}).invoke(ctx, new Object[]{keyInstance.getKeyManager(algorithm, keyAlias, null), trustInstance == null ? null : trustInstance.getTrustManager(algorithm, null), new java.security.SecureRandom()}); return (SSLContext) ctx; } catch (Exception e) { throw new KeystoreException("Unable to create SSL Context", e); } } public KeystoreInstance createKeystore(String name, char[] password, String keystoreType) throws KeystoreException { // ensure there are no illegal chars in DB name InputUtils.validateSafeInput(name); File test = new File(directory, name); if(test.exists()) { throw new IllegalArgumentException("Keystore already exists "+test.getAbsolutePath()+"!"); } try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, password); OutputStream out = new BufferedOutputStream(new FileOutputStream(test)); keystore.store(out, password); out.flush(); out.close(); return getKeystore(name, keystoreType); } catch (KeyStoreException e) { throw new KeystoreException("Unable to create keystore", e); } catch (IOException e) { throw new KeystoreException("Unable to create keystore", e); } catch (NoSuchAlgorithmException e) { throw new KeystoreException("Unable to create keystore", e); } catch (CertificateException e) { throw new KeystoreException("Unable to create keystore", e); } } public KeystoreInstance[] getUnlockedKeyStores() { List results = new ArrayList(); for (Iterator it = keystores.iterator(); it.hasNext();) { KeystoreInstance instance = (KeystoreInstance) it.next(); try { if(!instance.isKeystoreLocked() && instance.getUnlockedKeys(null).length > 0) { results.add(instance); } } catch (KeystoreException e) {} } return (KeystoreInstance[]) results.toArray(new KeystoreInstance[results.size()]); } public KeystoreInstance[] getUnlockedTrustStores() { List results = new ArrayList(); for (Iterator it = keystores.iterator(); it.hasNext();) { KeystoreInstance instance = (KeystoreInstance) it.next(); try { if(!instance.isKeystoreLocked() && instance.isTrustStore(null)) { results.add(instance); } } catch (KeystoreException e) {} } return (KeystoreInstance[]) results.toArray(new KeystoreInstance[results.size()]); } public static final GBeanInfo GBEAN_INFO; static { GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(FileKeystoreManager.class); infoFactory.addAttribute("keystoreDir", URI.class, true); infoFactory.addAttribute("kernel", Kernel.class, false); infoFactory.addReference("ServerInfo", ServerInfo.class, "GBean"); infoFactory.addReference("KeystoreInstances", KeystoreInstance.class, SecurityNames.KEYSTORE_INSTANCE); infoFactory.addInterface(KeystoreManager.class); infoFactory.setConstructor(new String[]{"keystoreDir", "ServerInfo", "KeystoreInstances", "kernel"}); GBEAN_INFO = infoFactory.getBeanInfo(); } public static GBeanInfo getGBeanInfo() { return GBEAN_INFO; } // ===================== Move this to a unitiy class or something ==================== public X509Certificate generateCert(PublicKey publicKey, PrivateKey privateKey, String sigalg, int validity, String cn, String ou, String o, String l, String st, String c) throws java.security.SignatureException, java.security.InvalidKeyException { X509V1CertificateGenerator certgen = new X509V1CertificateGenerator(); // issuer dn Vector order = new Vector(); Hashtable attrmap = new Hashtable(); if (cn != null) { attrmap.put(X509Principal.CN, cn); order.add(X509Principal.CN); } if (ou != null) { attrmap.put(X509Principal.OU, ou); order.add(X509Principal.OU); } if (o != null) { attrmap.put(X509Principal.O, o); order.add(X509Principal.O); } if (l != null) { attrmap.put(X509Principal.L, l); order.add(X509Principal.L); } if (st != null) { attrmap.put(X509Principal.ST, st); order.add(X509Principal.ST); } if (c != null) { attrmap.put(X509Principal.C, c); order.add(X509Principal.C); } X509Principal issuerDN = new X509Principal(order, attrmap); certgen.setIssuerDN(issuerDN); // validity long curr = System.currentTimeMillis(); long untill = curr + (long) validity * 24 * 60 * 60 * 1000; certgen.setNotBefore(new Date(curr)); certgen.setNotAfter(new Date(untill)); // subject dn certgen.setSubjectDN(issuerDN); // public key certgen.setPublicKey(publicKey); // signature alg certgen.setSignatureAlgorithm(sigalg); // serial number certgen.setSerialNumber(new BigInteger(String.valueOf(curr))); // make certificate return certgen.generateX509Certificate(privateKey); } }
[ "public", "class", "FileKeystoreManager", "implements", "KeystoreManager", ",", "GBeanLifecycle", "{", "private", "static", "final", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "FileKeystoreManager", ".", "class", ")", ";", "private", "File", "directory", ";", "private", "ServerInfo", "serverInfo", ";", "private", "URI", "configuredDir", ";", "private", "Collection", "keystores", ";", "private", "Kernel", "kernel", ";", "public", "FileKeystoreManager", "(", "URI", "keystoreDir", ",", "ServerInfo", "serverInfo", ",", "Collection", "keystores", ",", "Kernel", "kernel", ")", "{", "configuredDir", "=", "keystoreDir", ";", "this", ".", "serverInfo", "=", "serverInfo", ";", "this", ".", "keystores", "=", "keystores", ";", "this", ".", "kernel", "=", "kernel", ";", "}", "public", "void", "doStart", "(", ")", "throws", "Exception", "{", "URI", "rootURI", ";", "if", "(", "serverInfo", "!=", "null", ")", "{", "rootURI", "=", "serverInfo", ".", "resolveServer", "(", "configuredDir", ")", ";", "}", "else", "{", "rootURI", "=", "configuredDir", ";", "}", "if", "(", "!", "rootURI", ".", "getScheme", "(", ")", ".", "equals", "(", "\"", "file", "\"", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "FileKeystoreManager must have a root that's a local directory (not ", "\"", "+", "rootURI", "+", "\"", ")", "\"", ")", ";", "}", "directory", "=", "new", "File", "(", "rootURI", ")", ";", "if", "(", "!", "directory", ".", "exists", "(", ")", ")", "{", "if", "(", "directory", ".", "mkdirs", "(", ")", ")", "{", "log", ".", "warn", "(", "\"", "The keystore directory: ", "\"", "+", "directory", ".", "getAbsolutePath", "(", ")", "+", "\"", " does not exist. System automatically created one.", "\"", ")", ";", "}", "}", "if", "(", "!", "directory", ".", "exists", "(", ")", "||", "!", "directory", ".", "isDirectory", "(", ")", "||", "!", "directory", ".", "canRead", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "FileKeystoreManager must have a root that's a valid readable directory (not ", "\"", "+", "directory", ".", "getAbsolutePath", "(", ")", "+", "\"", ")", "\"", ")", ";", "}", "log", ".", "debug", "(", "\"", "Keystore directory is ", "\"", "+", "directory", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "public", "void", "doStop", "(", ")", "throws", "Exception", "{", "}", "public", "void", "doFail", "(", ")", "{", "}", "public", "void", "initializeKeystores", "(", ")", "{", "getKeystores", "(", ")", ";", "}", "public", "String", "[", "]", "listKeystoreFiles", "(", ")", "{", "File", "[", "]", "files", "=", "directory", ".", "listFiles", "(", ")", ";", "List", "list", "=", "new", "ArrayList", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "File", "file", "=", "files", "[", "i", "]", ";", "if", "(", "file", ".", "canRead", "(", ")", "&&", "!", "file", ".", "isDirectory", "(", ")", ")", "{", "String", "name", "=", "file", ".", "getName", "(", ")", ";", "if", "(", "name", ".", "lastIndexOf", "(", "\"", ".", "\"", ")", "==", "-", "1", ")", "{", "list", ".", "add", "(", "file", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "String", "type", "=", "name", ".", "substring", "(", "name", ".", "lastIndexOf", "(", "\"", ".", "\"", ")", "+", "1", ")", ";", "if", "(", "file", ".", "length", "(", ")", ">", "0", ")", "{", "for", "(", "String", "ktype", ":", "KeystoreUtil", ".", "keystoreTypes", ")", "{", "if", "(", "ktype", ".", "toLowerCase", "(", ")", ".", "equals", "(", "type", ".", "toLowerCase", "(", ")", ")", ")", "{", "list", ".", "add", "(", "file", ".", "getName", "(", ")", ")", ";", "}", "}", "}", "else", "if", "(", "file", ".", "length", "(", ")", "==", "0", ")", "{", "for", "(", "String", "ktype", ":", "KeystoreUtil", ".", "emptyKeystoreTypes", ")", "{", "if", "(", "ktype", ".", "toLowerCase", "(", ")", ".", "equals", "(", "type", ".", "toLowerCase", "(", ")", ")", ")", "{", "list", ".", "add", "(", "file", ".", "getName", "(", ")", ")", ";", "}", "}", "}", "}", "}", "}", "return", "(", "String", "[", "]", ")", "list", ".", "toArray", "(", "new", "String", "[", "list", ".", "size", "(", ")", "]", ")", ";", "}", "public", "KeystoreInstance", "[", "]", "getKeystores", "(", ")", "{", "String", "[", "]", "names", "=", "listKeystoreFiles", "(", ")", ";", "KeystoreInstance", "[", "]", "result", "=", "new", "KeystoreInstance", "[", "names", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "getKeystore", "(", "names", "[", "i", "]", ",", "null", ")", ";", "if", "(", "result", "[", "i", "]", "==", "null", ")", "{", "return", "null", ";", "}", "}", "return", "result", ";", "}", "public", "KeystoreInstance", "getKeystore", "(", "String", "name", ",", "String", "type", ")", "{", "for", "(", "Iterator", "it", "=", "keystores", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "KeystoreInstance", "instance", "=", "(", "KeystoreInstance", ")", "it", ".", "next", "(", ")", ";", "if", "(", "instance", ".", "getKeystoreName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "return", "instance", ";", "}", "}", "File", "test", "=", "new", "File", "(", "directory", ",", "name", ")", ";", "if", "(", "!", "test", ".", "exists", "(", ")", "||", "!", "test", ".", "canRead", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Cannot access keystore ", "\"", "+", "test", ".", "getAbsolutePath", "(", ")", "+", "\"", "!", "\"", ")", ";", "}", "AbstractName", "aName", ";", "AbstractName", "myName", "=", "kernel", ".", "getAbstractNameFor", "(", "this", ")", ";", "aName", "=", "kernel", ".", "getNaming", "(", ")", ".", "createSiblingName", "(", "myName", ",", "name", ",", "SecurityNames", ".", "KEYSTORE_INSTANCE", ")", ";", "GBeanData", "data", "=", "new", "GBeanData", "(", "aName", ",", "FileKeystoreInstance", ".", "getGBeanInfo", "(", ")", ")", ";", "try", "{", "String", "path", "=", "configuredDir", ".", "toString", "(", ")", ";", "if", "(", "!", "path", ".", "endsWith", "(", "\"", "/", "\"", ")", ")", "{", "path", "+=", "\"", "/", "\"", ";", "}", "data", ".", "setAttribute", "(", "\"", "keystorePath", "\"", ",", "new", "URI", "(", "path", "+", "name", ")", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "Can't resolve keystore path: ", "\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "data", ".", "setReferencePattern", "(", "\"", "ServerInfo", "\"", ",", "kernel", ".", "getAbstractNameFor", "(", "serverInfo", ")", ")", ";", "data", ".", "setAttribute", "(", "\"", "keystoreName", "\"", ",", "name", ")", ";", "if", "(", "type", "==", "null", ")", "{", "if", "(", "name", ".", "lastIndexOf", "(", "\"", ".", "\"", ")", "==", "-", "1", ")", "{", "type", "=", "KeystoreUtil", ".", "defaultType", ";", "log", ".", "warn", "(", "\"", "keystoreType for new keystore ", "\\\"", "\"", "+", "name", "+", "\"", "\\\"", " set to default type ", "\\\"", "\"", "+", "type", "+", "\"", "\\\"", ".", "\"", ")", ";", "}", "else", "{", "type", "=", "name", ".", "substring", "(", "name", ".", "lastIndexOf", "(", "\"", ".", "\"", ")", "+", "1", ")", ";", "log", ".", "warn", "(", "\"", "keystoreType for new keystore ", "\\\"", "\"", "+", "name", "+", "\"", "\\\"", " set to ", "\\\"", "\"", "+", "type", "+", "\"", "\\\"", " based on file extension.", "\"", ")", ";", "}", "}", "data", ".", "setAttribute", "(", "\"", "keystoreType", "\"", ",", "type", ")", ";", "EditableConfigurationManager", "mgr", "=", "ConfigurationUtil", ".", "getEditableConfigurationManager", "(", "kernel", ")", ";", "if", "(", "mgr", "!=", "null", ")", "{", "try", "{", "mgr", ".", "addGBeanToConfiguration", "(", "myName", ".", "getArtifact", "(", ")", ",", "data", ",", "true", ")", ";", "return", "(", "KeystoreInstance", ")", "kernel", ".", "getProxyManager", "(", ")", ".", "createProxy", "(", "aName", ",", "KeystoreInstance", ".", "class", ")", ";", "}", "catch", "(", "InvalidConfigException", "e", ")", "{", "log", ".", "error", "(", "\"", "Should never happen", "\"", ",", "e", ")", ";", "throw", "new", "IllegalStateException", "(", "\"", "Unable to add Keystore GBean (", "\"", "+", "e", ".", "getMessage", "(", ")", "+", "\"", ")", "\"", ",", "e", ")", ";", "}", "finally", "{", "ConfigurationUtil", ".", "releaseConfigurationManager", "(", "kernel", ",", "mgr", ")", ";", "}", "}", "else", "{", "log", ".", "warn", "(", "\"", "The ConfigurationManager in the kernel does not allow changes at runtime", "\"", ")", ";", "return", "null", ";", "}", "}", "/**\n * Gets a SocketFactory using one Keystore to access the private key\n * and another to provide the list of trusted certificate authorities.\n *\n * @param provider The SSL provider to use, or null for the default\n * @param protocol The SSL protocol to use\n * @param algorithm The SSL algorithm to use\n * @param trustStore The trust keystore name as provided by listKeystores.\n * The KeystoreInstance for this keystore must have\n * unlocked this key.\n * @param loader The class loader used to resolve factory classes.\n *\n * @return A created SSLSocketFactory item created from the KeystoreManager.\n * @throws KeystoreIsLocked\n * Occurs when the requested key keystore cannot\n * be used because it has not been unlocked.\n * @throws KeyIsLocked\n * Occurs when the requested private key in the key\n * keystore cannot be used because it has not been\n * unlocked.\n * @throws NoSuchAlgorithmException\n * @throws UnrecoverableKeyException\n * @throws KeyStoreException\n * @throws KeyManagementException\n * @throws NoSuchProviderException\n */", "public", "SSLSocketFactory", "createSSLFactory", "(", "String", "provider", ",", "String", "protocol", ",", "String", "algorithm", ",", "String", "trustStore", ",", "ClassLoader", "loader", ")", "throws", "KeystoreException", "{", "return", "createSSLFactory", "(", "provider", ",", "protocol", ",", "algorithm", ",", "null", ",", "null", ",", "trustStore", ",", "loader", ")", ";", "}", "/**\n * Gets a SocketFactory using one Keystore to access the private key\n * and another to provide the list of trusted certificate authorities.\n *\n * @param provider The SSL provider to use, or null for the default\n * @param protocol The SSL protocol to use\n * @param algorithm The SSL algorithm to use\n * @param keyStore The key keystore name as provided by listKeystores. The\n * KeystoreInstance for this keystore must be unlocked.\n * @param keyAlias The name of the private key in the keystore. The\n * KeystoreInstance for this keystore must have unlocked\n * this key.\n * @param trustStore The trust keystore name as provided by listKeystores.\n * The KeystoreInstance for this keystore must have\n * unlocked this key.\n * @param loader The class loader used to resolve factory classes.\n *\n * @return A created SSLSocketFactory item created from the KeystoreManager.\n * @throws KeystoreIsLocked\n * Occurs when the requested key keystore cannot\n * be used because it has not been unlocked.\n * @throws KeyIsLocked\n * Occurs when the requested private key in the key\n * keystore cannot be used because it has not been\n * unlocked.\n * @throws KeystoreException\n */", "public", "SSLSocketFactory", "createSSLFactory", "(", "String", "provider", ",", "String", "protocol", ",", "String", "algorithm", ",", "String", "keyStore", ",", "String", "keyAlias", ",", "String", "trustStore", ",", "ClassLoader", "loader", ")", "throws", "KeystoreException", "{", "KeystoreInstance", "keyInstance", "=", "null", ";", "if", "(", "keyStore", "!=", "null", ")", "{", "keyInstance", "=", "getKeystore", "(", "keyStore", ",", "null", ")", ";", "if", "(", "keyInstance", ".", "isKeystoreLocked", "(", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Keystore '", "\"", "+", "keyStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "if", "(", "keyInstance", ".", "isKeyLocked", "(", "keyAlias", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Key '", "\"", "+", "keyAlias", "+", "\"", "' in keystore '", "\"", "+", "keyStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "}", "KeystoreInstance", "trustInstance", "=", "trustStore", "==", "null", "?", "null", ":", "getKeystore", "(", "trustStore", ",", "null", ")", ";", "if", "(", "trustInstance", "!=", "null", "&&", "trustInstance", ".", "isKeystoreLocked", "(", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Keystore '", "\"", "+", "trustStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "try", "{", "Class", "cls", "=", "loader", ".", "loadClass", "(", "\"", "javax.net.ssl.SSLContext", "\"", ")", ";", "Object", "ctx", "=", "cls", ".", "getMethod", "(", "\"", "getInstance", "\"", ",", "new", "Class", "[", "]", "{", "String", ".", "class", "}", ")", ".", "invoke", "(", "null", ",", "new", "Object", "[", "]", "{", "protocol", "}", ")", ";", "Class", "kmc", "=", "Class", ".", "forName", "(", "\"", "[Ljavax.net.ssl.KeyManager;", "\"", ",", "false", ",", "loader", ")", ";", "Class", "tmc", "=", "Class", ".", "forName", "(", "\"", "[Ljavax.net.ssl.TrustManager;", "\"", ",", "false", ",", "loader", ")", ";", "Class", "src", "=", "loader", ".", "loadClass", "(", "\"", "java.security.SecureRandom", "\"", ")", ";", "cls", ".", "getMethod", "(", "\"", "init", "\"", ",", "new", "Class", "[", "]", "{", "kmc", ",", "tmc", ",", "src", "}", ")", ".", "invoke", "(", "ctx", ",", "new", "Object", "[", "]", "{", "keyInstance", "==", "null", "?", "null", ":", "keyInstance", ".", "getKeyManager", "(", "algorithm", ",", "keyAlias", ",", "null", ")", ",", "trustInstance", "==", "null", "?", "null", ":", "trustInstance", ".", "getTrustManager", "(", "algorithm", ",", "null", ")", ",", "new", "java", ".", "security", ".", "SecureRandom", "(", ")", "}", ")", ";", "Object", "result", "=", "cls", ".", "getMethod", "(", "\"", "getSocketFactory", "\"", ",", "new", "Class", "[", "0", "]", ")", ".", "invoke", "(", "ctx", ",", "new", "Object", "[", "0", "]", ")", ";", "return", "(", "SSLSocketFactory", ")", "result", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create SSL Factory", "\"", ",", "e", ")", ";", "}", "}", "/**\n * Gets a ServerSocketFactory using one Keystore to access the private key\n * and another to provide the list of trusted certificate authorities.\n * @param provider The SSL provider to use, or null for the default\n * @param protocol The SSL protocol to use\n * @param algorithm The SSL algorithm to use\n * @param keyStore The key keystore name as provided by listKeystores. The\n * KeystoreInstance for this keystore must be unlocked.\n * @param keyAlias The name of the private key in the keystore. The\n * KeystoreInstance for this keystore must have unlocked\n * this key.\n * @param trustStore The trust keystore name as provided by listKeystores.\n * The KeystoreInstance for this keystore must have\n * unlocked this key.\n * @param loader The class loader used to resolve factory classes.\n *\n * @throws KeystoreIsLocked Occurs when the requested key keystore cannot\n * be used because it has not been unlocked.\n * @throws KeyIsLocked Occurs when the requested private key in the key\n * keystore cannot be used because it has not been\n * unlocked.\n */", "public", "SSLServerSocketFactory", "createSSLServerFactory", "(", "String", "provider", ",", "String", "protocol", ",", "String", "algorithm", ",", "String", "keyStore", ",", "String", "keyAlias", ",", "String", "trustStore", ",", "ClassLoader", "loader", ")", "throws", "KeystoreException", "{", "SSLContext", "sslContext", "=", "createSSLContext", "(", "provider", ",", "protocol", ",", "algorithm", ",", "keyStore", ",", "keyAlias", ",", "trustStore", ",", "loader", ")", ";", "try", "{", "Object", "result", "=", "sslContext", ".", "getClass", "(", ")", ".", "getMethod", "(", "\"", "getServerSocketFactory", "\"", ",", "new", "Class", "[", "0", "]", ")", ".", "invoke", "(", "sslContext", ",", "new", "Object", "[", "0", "]", ")", ";", "return", "(", "SSLServerSocketFactory", ")", "result", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create SSL Server Factory", "\"", ",", "e", ")", ";", "}", "}", "/**\n * Gets a ServerSocketFactory using one Keystore to access the private key\n * and another to provide the list of trusted certificate authorities.\n * @param provider The SSL provider to use, or null for the default\n * @param protocol The SSL protocol to use\n * @param algorithm The SSL algorithm to use\n * @param keyStore The key keystore name as provided by listKeystores. The\n * KeystoreInstance for this keystore must be unlocked.\n * @param keyAlias The name of the private key in the keystore. The\n * KeystoreInstance for this keystore must have unlocked\n * this key.\n * @param trustStore The trust keystore name as provided by listKeystores.\n * The KeystoreInstance for this keystore must have\n * unlocked this key.\n * @param loader The class loader used to resolve factory classes.\n *\n * @return SSLContext using the security info provided\n * @throws KeystoreIsLocked Occurs when the requested key keystore cannot\n * be used because it has not been unlocked.\n * @throws KeyIsLocked Occurs when the requested private key in the key\n * keystore cannot be used because it has not been\n * unlocked.\n */", "public", "SSLContext", "createSSLContext", "(", "String", "provider", ",", "String", "protocol", ",", "String", "algorithm", ",", "String", "keyStore", ",", "String", "keyAlias", ",", "String", "trustStore", ",", "ClassLoader", "loader", ")", "throws", "KeystoreException", "{", "KeystoreInstance", "keyInstance", "=", "getKeystore", "(", "keyStore", ",", "null", ")", ";", "if", "(", "keyInstance", ".", "isKeystoreLocked", "(", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Keystore '", "\"", "+", "keyStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "if", "(", "keyInstance", ".", "isKeyLocked", "(", "keyAlias", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Key '", "\"", "+", "keyAlias", "+", "\"", "' in keystore '", "\"", "+", "keyStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "KeystoreInstance", "trustInstance", "=", "trustStore", "==", "null", "?", "null", ":", "getKeystore", "(", "trustStore", ",", "null", ")", ";", "if", "(", "trustInstance", "!=", "null", "&&", "trustInstance", ".", "isKeystoreLocked", "(", ")", ")", "{", "throw", "new", "KeystoreIsLocked", "(", "\"", "Keystore '", "\"", "+", "trustStore", "+", "\"", "' is locked; please use the keystore page in the admin console to unlock it", "\"", ")", ";", "}", "try", "{", "Class", "cls", "=", "loader", ".", "loadClass", "(", "\"", "javax.net.ssl.SSLContext", "\"", ")", ";", "Object", "ctx", "=", "cls", ".", "getMethod", "(", "\"", "getInstance", "\"", ",", "new", "Class", "[", "]", "{", "String", ".", "class", "}", ")", ".", "invoke", "(", "null", ",", "new", "Object", "[", "]", "{", "protocol", "}", ")", ";", "Class", "kmc", "=", "Class", ".", "forName", "(", "\"", "[Ljavax.net.ssl.KeyManager;", "\"", ",", "false", ",", "loader", ")", ";", "Class", "tmc", "=", "Class", ".", "forName", "(", "\"", "[Ljavax.net.ssl.TrustManager;", "\"", ",", "false", ",", "loader", ")", ";", "Class", "src", "=", "loader", ".", "loadClass", "(", "\"", "java.security.SecureRandom", "\"", ")", ";", "cls", ".", "getMethod", "(", "\"", "init", "\"", ",", "new", "Class", "[", "]", "{", "kmc", ",", "tmc", ",", "src", "}", ")", ".", "invoke", "(", "ctx", ",", "new", "Object", "[", "]", "{", "keyInstance", ".", "getKeyManager", "(", "algorithm", ",", "keyAlias", ",", "null", ")", ",", "trustInstance", "==", "null", "?", "null", ":", "trustInstance", ".", "getTrustManager", "(", "algorithm", ",", "null", ")", ",", "new", "java", ".", "security", ".", "SecureRandom", "(", ")", "}", ")", ";", "return", "(", "SSLContext", ")", "ctx", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create SSL Context", "\"", ",", "e", ")", ";", "}", "}", "public", "KeystoreInstance", "createKeystore", "(", "String", "name", ",", "char", "[", "]", "password", ",", "String", "keystoreType", ")", "throws", "KeystoreException", "{", "InputUtils", ".", "validateSafeInput", "(", "name", ")", ";", "File", "test", "=", "new", "File", "(", "directory", ",", "name", ")", ";", "if", "(", "test", ".", "exists", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Keystore already exists ", "\"", "+", "test", ".", "getAbsolutePath", "(", ")", "+", "\"", "!", "\"", ")", ";", "}", "try", "{", "KeyStore", "keystore", "=", "KeyStore", ".", "getInstance", "(", "keystoreType", ")", ";", "keystore", ".", "load", "(", "null", ",", "password", ")", ";", "OutputStream", "out", "=", "new", "BufferedOutputStream", "(", "new", "FileOutputStream", "(", "test", ")", ")", ";", "keystore", ".", "store", "(", "out", ",", "password", ")", ";", "out", ".", "flush", "(", ")", ";", "out", ".", "close", "(", ")", ";", "return", "getKeystore", "(", "name", ",", "keystoreType", ")", ";", "}", "catch", "(", "KeyStoreException", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create keystore", "\"", ",", "e", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create keystore", "\"", ",", "e", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create keystore", "\"", ",", "e", ")", ";", "}", "catch", "(", "CertificateException", "e", ")", "{", "throw", "new", "KeystoreException", "(", "\"", "Unable to create keystore", "\"", ",", "e", ")", ";", "}", "}", "public", "KeystoreInstance", "[", "]", "getUnlockedKeyStores", "(", ")", "{", "List", "results", "=", "new", "ArrayList", "(", ")", ";", "for", "(", "Iterator", "it", "=", "keystores", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "KeystoreInstance", "instance", "=", "(", "KeystoreInstance", ")", "it", ".", "next", "(", ")", ";", "try", "{", "if", "(", "!", "instance", ".", "isKeystoreLocked", "(", ")", "&&", "instance", ".", "getUnlockedKeys", "(", "null", ")", ".", "length", ">", "0", ")", "{", "results", ".", "add", "(", "instance", ")", ";", "}", "}", "catch", "(", "KeystoreException", "e", ")", "{", "}", "}", "return", "(", "KeystoreInstance", "[", "]", ")", "results", ".", "toArray", "(", "new", "KeystoreInstance", "[", "results", ".", "size", "(", ")", "]", ")", ";", "}", "public", "KeystoreInstance", "[", "]", "getUnlockedTrustStores", "(", ")", "{", "List", "results", "=", "new", "ArrayList", "(", ")", ";", "for", "(", "Iterator", "it", "=", "keystores", ".", "iterator", "(", ")", ";", "it", ".", "hasNext", "(", ")", ";", ")", "{", "KeystoreInstance", "instance", "=", "(", "KeystoreInstance", ")", "it", ".", "next", "(", ")", ";", "try", "{", "if", "(", "!", "instance", ".", "isKeystoreLocked", "(", ")", "&&", "instance", ".", "isTrustStore", "(", "null", ")", ")", "{", "results", ".", "add", "(", "instance", ")", ";", "}", "}", "catch", "(", "KeystoreException", "e", ")", "{", "}", "}", "return", "(", "KeystoreInstance", "[", "]", ")", "results", ".", "toArray", "(", "new", "KeystoreInstance", "[", "results", ".", "size", "(", ")", "]", ")", ";", "}", "public", "static", "final", "GBeanInfo", "GBEAN_INFO", ";", "static", "{", "GBeanInfoBuilder", "infoFactory", "=", "GBeanInfoBuilder", ".", "createStatic", "(", "FileKeystoreManager", ".", "class", ")", ";", "infoFactory", ".", "addAttribute", "(", "\"", "keystoreDir", "\"", ",", "URI", ".", "class", ",", "true", ")", ";", "infoFactory", ".", "addAttribute", "(", "\"", "kernel", "\"", ",", "Kernel", ".", "class", ",", "false", ")", ";", "infoFactory", ".", "addReference", "(", "\"", "ServerInfo", "\"", ",", "ServerInfo", ".", "class", ",", "\"", "GBean", "\"", ")", ";", "infoFactory", ".", "addReference", "(", "\"", "KeystoreInstances", "\"", ",", "KeystoreInstance", ".", "class", ",", "SecurityNames", ".", "KEYSTORE_INSTANCE", ")", ";", "infoFactory", ".", "addInterface", "(", "KeystoreManager", ".", "class", ")", ";", "infoFactory", ".", "setConstructor", "(", "new", "String", "[", "]", "{", "\"", "keystoreDir", "\"", ",", "\"", "ServerInfo", "\"", ",", "\"", "KeystoreInstances", "\"", ",", "\"", "kernel", "\"", "}", ")", ";", "GBEAN_INFO", "=", "infoFactory", ".", "getBeanInfo", "(", ")", ";", "}", "public", "static", "GBeanInfo", "getGBeanInfo", "(", ")", "{", "return", "GBEAN_INFO", ";", "}", "public", "X509Certificate", "generateCert", "(", "PublicKey", "publicKey", ",", "PrivateKey", "privateKey", ",", "String", "sigalg", ",", "int", "validity", ",", "String", "cn", ",", "String", "ou", ",", "String", "o", ",", "String", "l", ",", "String", "st", ",", "String", "c", ")", "throws", "java", ".", "security", ".", "SignatureException", ",", "java", ".", "security", ".", "InvalidKeyException", "{", "X509V1CertificateGenerator", "certgen", "=", "new", "X509V1CertificateGenerator", "(", ")", ";", "Vector", "order", "=", "new", "Vector", "(", ")", ";", "Hashtable", "attrmap", "=", "new", "Hashtable", "(", ")", ";", "if", "(", "cn", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "CN", ",", "cn", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "CN", ")", ";", "}", "if", "(", "ou", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "OU", ",", "ou", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "OU", ")", ";", "}", "if", "(", "o", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "O", ",", "o", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "O", ")", ";", "}", "if", "(", "l", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "L", ",", "l", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "L", ")", ";", "}", "if", "(", "st", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "ST", ",", "st", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "ST", ")", ";", "}", "if", "(", "c", "!=", "null", ")", "{", "attrmap", ".", "put", "(", "X509Principal", ".", "C", ",", "c", ")", ";", "order", ".", "add", "(", "X509Principal", ".", "C", ")", ";", "}", "X509Principal", "issuerDN", "=", "new", "X509Principal", "(", "order", ",", "attrmap", ")", ";", "certgen", ".", "setIssuerDN", "(", "issuerDN", ")", ";", "long", "curr", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "untill", "=", "curr", "+", "(", "long", ")", "validity", "*", "24", "*", "60", "*", "60", "*", "1000", ";", "certgen", ".", "setNotBefore", "(", "new", "Date", "(", "curr", ")", ")", ";", "certgen", ".", "setNotAfter", "(", "new", "Date", "(", "untill", ")", ")", ";", "certgen", ".", "setSubjectDN", "(", "issuerDN", ")", ";", "certgen", ".", "setPublicKey", "(", "publicKey", ")", ";", "certgen", ".", "setSignatureAlgorithm", "(", "sigalg", ")", ";", "certgen", ".", "setSerialNumber", "(", "new", "BigInteger", "(", "String", ".", "valueOf", "(", "curr", ")", ")", ")", ";", "return", "certgen", ".", "generateX509Certificate", "(", "privateKey", ")", ";", "}", "}" ]
An implementation of KeystoreManager that assumes every file in a specified directory is a keystore.
[ "An", "implementation", "of", "KeystoreManager", "that", "assumes", "every", "file", "in", "a", "specified", "directory", "is", "a", "keystore", "." ]
[ "// typically, the keyStore and the keyAlias are not required if authentication is also not required.", "// the keyStore is optional.", "// OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way!", "// OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way!", "// OMG this hurts, but it causes ClassCastExceptions elsewhere unless done this way!", "// ensure there are no illegal chars in DB name", "// ===================== Move this to a unitiy class or something ====================", "// issuer dn", "// validity", "// subject dn", "// public key", "// signature alg", "// serial number", "// make certificate" ]
[ { "param": "KeystoreManager, GBeanLifecycle", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "KeystoreManager, GBeanLifecycle", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84e30f72396d21365a9b428c85ea2a7ada74e455
TagsRocks/osrs-server-1
toolkit/src/main/java/nl/bartpelle/veteres/toolkit/dec/impl/expr/VarpExpr.java
[ "MIT" ]
Java
VarpExpr
/** * Created by bart on 7/20/15. */
Created by bart on 7/20/15.
[ "Created", "by", "bart", "on", "7", "/", "20", "/", "15", "." ]
public class VarpExpr extends Expr { private int value; public VarpExpr(Expr parent, int value) { super(parent, Type.INT); this.value = value; } public int value() { return value; } public void toCode(CodePrinter printer) { printer.print("varp_" + String.valueOf(value)); } }
[ "public", "class", "VarpExpr", "extends", "Expr", "{", "private", "int", "value", ";", "public", "VarpExpr", "(", "Expr", "parent", ",", "int", "value", ")", "{", "super", "(", "parent", ",", "Type", ".", "INT", ")", ";", "this", ".", "value", "=", "value", ";", "}", "public", "int", "value", "(", ")", "{", "return", "value", ";", "}", "public", "void", "toCode", "(", "CodePrinter", "printer", ")", "{", "printer", ".", "print", "(", "\"", "varp_", "\"", "+", "String", ".", "valueOf", "(", "value", ")", ")", ";", "}", "}" ]
Created by bart on 7/20/15.
[ "Created", "by", "bart", "on", "7", "/", "20", "/", "15", "." ]
[]
[ { "param": "Expr", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Expr", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84ef86a4a63cdfd91218255f7fc1b3d6d2c17c59
sghill/msl
core/src/main/java/com/netflix/msl/entityauth/PresharedAuthenticationData.java
[ "Apache-2.0" ]
Java
PresharedAuthenticationData
/** * <p>Preshared keys entity authentication data.</p> * * <p> * {@code { * "#mandatory" : [ "identity" ], * "identity" : "string" * }} where: * <ul> * <li>{@code identity} is the entity identity</li> * </ul></p> * * @author Wesley Miaw <[email protected]> */
Preshared keys entity authentication data. @author Wesley Miaw
[ "Preshared", "keys", "entity", "authentication", "data", ".", "@author", "Wesley", "Miaw" ]
public class PresharedAuthenticationData extends EntityAuthenticationData { /** Key entity identity. */ private static final String KEY_IDENTITY = "identity"; /** * Construct a new preshared keys authentication data instance from the * specified entity identity. * * @param identity the entity identity. */ public PresharedAuthenticationData(final String identity) { super(EntityAuthenticationScheme.PSK); this.identity = identity; } /** * Construct a new preshared keys authentication data instance from the * provided MSL object. * * @param presharedAuthMo the authentication data MSL object. * @throws MslEncodingException if there is an error parsing the entity * authentication data. */ PresharedAuthenticationData(final MslObject presharedAuthMo) throws MslEncodingException { super(EntityAuthenticationScheme.PSK); try { identity = presharedAuthMo.getString(KEY_IDENTITY); } catch (final MslEncoderException e) { throw new MslEncodingException(MslError.MSL_PARSE_ERROR, "psk authdata " + presharedAuthMo, e); } } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity() */ @Override public String getIdentity() { return identity; } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat) */ @Override public MslObject getAuthData(final MslEncoderFactory encoder, final MslEncoderFormat format) { final MslObject mo = encoder.createObject(); mo.put(KEY_IDENTITY, identity); return mo; } /** Entity identity. */ private final String identity; /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (obj == this) return true; if (!(obj instanceof PresharedAuthenticationData)) return false; final PresharedAuthenticationData that = (PresharedAuthenticationData)obj; return super.equals(obj) && this.identity.equals(that.identity); } /* (non-Javadoc) * @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode() */ @Override public int hashCode() { return super.hashCode() ^ identity.hashCode(); } }
[ "public", "class", "PresharedAuthenticationData", "extends", "EntityAuthenticationData", "{", "/** Key entity identity. */", "private", "static", "final", "String", "KEY_IDENTITY", "=", "\"", "identity", "\"", ";", "/**\n * Construct a new preshared keys authentication data instance from the\n * specified entity identity.\n * \n * @param identity the entity identity.\n */", "public", "PresharedAuthenticationData", "(", "final", "String", "identity", ")", "{", "super", "(", "EntityAuthenticationScheme", ".", "PSK", ")", ";", "this", ".", "identity", "=", "identity", ";", "}", "/**\n * Construct a new preshared keys authentication data instance from the\n * provided MSL object.\n * \n * @param presharedAuthMo the authentication data MSL object.\n * @throws MslEncodingException if there is an error parsing the entity\n * authentication data.\n */", "PresharedAuthenticationData", "(", "final", "MslObject", "presharedAuthMo", ")", "throws", "MslEncodingException", "{", "super", "(", "EntityAuthenticationScheme", ".", "PSK", ")", ";", "try", "{", "identity", "=", "presharedAuthMo", ".", "getString", "(", "KEY_IDENTITY", ")", ";", "}", "catch", "(", "final", "MslEncoderException", "e", ")", "{", "throw", "new", "MslEncodingException", "(", "MslError", ".", "MSL_PARSE_ERROR", ",", "\"", "psk authdata ", "\"", "+", "presharedAuthMo", ",", "e", ")", ";", "}", "}", "/* (non-Javadoc)\n * @see com.netflix.msl.entityauth.EntityAuthenticationData#getIdentity()\n */", "@", "Override", "public", "String", "getIdentity", "(", ")", "{", "return", "identity", ";", "}", "/* (non-Javadoc)\n * @see com.netflix.msl.entityauth.EntityAuthenticationData#getAuthData(com.netflix.msl.io.MslEncoderFactory, com.netflix.msl.io.MslEncoderFormat)\n */", "@", "Override", "public", "MslObject", "getAuthData", "(", "final", "MslEncoderFactory", "encoder", ",", "final", "MslEncoderFormat", "format", ")", "{", "final", "MslObject", "mo", "=", "encoder", ".", "createObject", "(", ")", ";", "mo", ".", "put", "(", "KEY_IDENTITY", ",", "identity", ")", ";", "return", "mo", ";", "}", "/** Entity identity. */", "private", "final", "String", "identity", ";", "/* (non-Javadoc)\n * @see com.netflix.msl.entityauth.EntityAuthenticationData#equals(java.lang.Object)\n */", "@", "Override", "public", "boolean", "equals", "(", "final", "Object", "obj", ")", "{", "if", "(", "obj", "==", "this", ")", "return", "true", ";", "if", "(", "!", "(", "obj", "instanceof", "PresharedAuthenticationData", ")", ")", "return", "false", ";", "final", "PresharedAuthenticationData", "that", "=", "(", "PresharedAuthenticationData", ")", "obj", ";", "return", "super", ".", "equals", "(", "obj", ")", "&&", "this", ".", "identity", ".", "equals", "(", "that", ".", "identity", ")", ";", "}", "/* (non-Javadoc)\n * @see com.netflix.msl.entityauth.EntityAuthenticationData#hashCode()\n */", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "super", ".", "hashCode", "(", ")", "^", "identity", ".", "hashCode", "(", ")", ";", "}", "}" ]
<p>Preshared keys entity authentication data.</p>
[ "<p", ">", "Preshared", "keys", "entity", "authentication", "data", ".", "<", "/", "p", ">" ]
[]
[ { "param": "EntityAuthenticationData", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EntityAuthenticationData", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84f0082c5447d2447bac5d80a60fd52cf6ca58be
pjfanning/curvesapi
src/main/java/com/graphbuilder/curve/BSpline.java
[ "BSD-3-Clause" ]
Java
BSpline
/** <p>General non-rational B-Spline implementation where the degree can be specified. <p>For the B-Spline, there are 3 types of knot-vectors, uniform clamped, uniform unclamped, and non-uniform. A uniform knot-vector means that the knots are equally spaced. A clamped knot-vector means that the first k-knots and last k-knots are repeated, where k is the degree + 1. Non-uniform means that the knot-values have no specific properties. For all 3 types, the knot-values must be non-decreasing. <p>Here are some examples of uniform clamped knot vectors for degree 3: <pre> number of control points = 4: [0, 0, 0, 0, 1, 1, 1, 1] number of control points = 7: [0, 0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1, 1] </pre> <p>The following is a figure of a B-Spline generated using a uniform clamped knot vector: <p><center><img align="center" src="doc-files/bspline1.gif"/></center> <p>Here are some examples of uniform unclamped knot vectors for degree 3: <pre> number of control points = 4: [0, 0.14, 0.29, 0.43, 0.57, 0.71, 0.86, 1] (about) number of control points = 7: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] </pre> <p>The following is a figure of a B-Spline generated using a uniform unclamped knot vector: <p><center><img align="center" src="doc-files/bspline2.gif"/></center> <p>Note: Although the knot-values in the examples are between 0 and 1, this is not a requirement. <p>When the knot-vector is uniform clamped, the default interval is [0, 1]. When the knot-vector is uniform unclamped, the default interval is [grad * degree, 1 - grad * degree], where grad is the gradient or the knot-span. Specifying the knotVectorType as UNIFORM_CLAMPED or UNIFORM_UNCLAMPED means that the internal knot-vector will not be used. <p>Note: The computation required is O(2^degree) or exponential. Increasing the degree by 1 means that twice as many computations are done. */
General non-rational B-Spline implementation where the degree can be specified. For the B-Spline, there are 3 types of knot-vectors, uniform clamped, uniform unclamped, and non-uniform. A uniform knot-vector means that the knots are equally spaced. A clamped knot-vector means that the first k-knots and last k-knots are repeated, where k is the degree + 1. Non-uniform means that the knot-values have no specific properties. For all 3 types, the knot-values must be non-decreasing. Here are some examples of uniform clamped knot vectors for degree 3. The following is a figure of a B-Spline generated using a uniform clamped knot vector. Here are some examples of uniform unclamped knot vectors for degree 3. The following is a figure of a B-Spline generated using a uniform unclamped knot vector. Note: Although the knot-values in the examples are between 0 and 1, this is not a requirement. When the knot-vector is uniform clamped, the default interval is [0, 1]. When the knot-vector is uniform unclamped, the default interval is [grad * degree, 1 - grad * degree], where grad is the gradient or the knot-span. Specifying the knotVectorType as UNIFORM_CLAMPED or UNIFORM_UNCLAMPED means that the internal knot-vector will not be used. Note: The computation required is O(2^degree) or exponential. Increasing the degree by 1 means that twice as many computations are done.
[ "General", "non", "-", "rational", "B", "-", "Spline", "implementation", "where", "the", "degree", "can", "be", "specified", ".", "For", "the", "B", "-", "Spline", "there", "are", "3", "types", "of", "knot", "-", "vectors", "uniform", "clamped", "uniform", "unclamped", "and", "non", "-", "uniform", ".", "A", "uniform", "knot", "-", "vector", "means", "that", "the", "knots", "are", "equally", "spaced", ".", "A", "clamped", "knot", "-", "vector", "means", "that", "the", "first", "k", "-", "knots", "and", "last", "k", "-", "knots", "are", "repeated", "where", "k", "is", "the", "degree", "+", "1", ".", "Non", "-", "uniform", "means", "that", "the", "knot", "-", "values", "have", "no", "specific", "properties", ".", "For", "all", "3", "types", "the", "knot", "-", "values", "must", "be", "non", "-", "decreasing", ".", "Here", "are", "some", "examples", "of", "uniform", "clamped", "knot", "vectors", "for", "degree", "3", ".", "The", "following", "is", "a", "figure", "of", "a", "B", "-", "Spline", "generated", "using", "a", "uniform", "clamped", "knot", "vector", ".", "Here", "are", "some", "examples", "of", "uniform", "unclamped", "knot", "vectors", "for", "degree", "3", ".", "The", "following", "is", "a", "figure", "of", "a", "B", "-", "Spline", "generated", "using", "a", "uniform", "unclamped", "knot", "vector", ".", "Note", ":", "Although", "the", "knot", "-", "values", "in", "the", "examples", "are", "between", "0", "and", "1", "this", "is", "not", "a", "requirement", ".", "When", "the", "knot", "-", "vector", "is", "uniform", "clamped", "the", "default", "interval", "is", "[", "0", "1", "]", ".", "When", "the", "knot", "-", "vector", "is", "uniform", "unclamped", "the", "default", "interval", "is", "[", "grad", "*", "degree", "1", "-", "grad", "*", "degree", "]", "where", "grad", "is", "the", "gradient", "or", "the", "knot", "-", "span", ".", "Specifying", "the", "knotVectorType", "as", "UNIFORM_CLAMPED", "or", "UNIFORM_UNCLAMPED", "means", "that", "the", "internal", "knot", "-", "vector", "will", "not", "be", "used", ".", "Note", ":", "The", "computation", "required", "is", "O", "(", "2^degree", ")", "or", "exponential", ".", "Increasing", "the", "degree", "by", "1", "means", "that", "twice", "as", "many", "computations", "are", "done", "." ]
public class BSpline extends ParametricCurve { public static final int UNIFORM_CLAMPED = 0; public static final int UNIFORM_UNCLAMPED = 1; public static final int NON_UNIFORM = 2; private static final ThreadLocal<SharedData> SHARED_DATA = new ThreadLocal<SharedData>(){ protected SharedData initialValue() { return new SharedData(); } }; private final SharedData sharedData = SHARED_DATA.get(); private static class SharedData { private int[] a = new int[0]; // counter used for the a-function values (required length >= degree) private int[] c = new int[0]; // counter used for bit patterns (required length >= degree) private double[] knot = new double[0]; // (required length >= numPts + degree) } private ValueVector knotVector = new ValueVector(new double[] { 0, 0, 0, 0, 1, 1, 1, 1 }, 8); private double t_min = 0.0; private double t_max = 1.0; private int sampleLimit = 1; private int degree = 4; // the internal degree variable is always 1 plus the specified degree private int knotVectorType = UNIFORM_CLAMPED; private boolean useDefaultInterval = true; public BSpline(ControlPath cp, GroupIterator gi) { super(cp, gi); } protected void eval(double[] p) { int dim = p.length - 1; double t = p[dim]; int numPts = gi.getGroupSize(); gi.set(0,0); for (int i = 0; i < numPts; i++) { double w = N(t, i); //double w = N(t, i, degree); double[] loc = cp.getPoint(gi.next()).getLocation(); for (int j = 0; j < dim; j++) p[j] += (loc[j] * w); //pt[i][j] * w); } } /** Specifies the interval that the curve should define itself on. The default interval is [0.0, 1.0]. When the knot-vector type is one of UNIFORM_CLAMPED or UNIFORM_UNCLAMPED and the useDefaultInterval flag is true, then these values will not be used. @throws IllegalArgumentException If t_min > t_max. @see #t_min() @see #t_max() */ public void setInterval(double t_min, double t_max) { if (t_min > t_max) throw new IllegalArgumentException("t_min <= t_max required."); this.t_min = t_min; this.t_max = t_max; } /** Returns the starting interval value. @see #setInterval(double, double) @see #t_max() */ public double t_min() { return t_min; } /** Returns the finishing interval value. @see #setInterval(double, double) @see #t_min() */ public double t_max() { return t_max; } public int getSampleLimit() { return sampleLimit; } /** Sets the sample-limit. For more information on the sample-limit, see the BinaryCurveApproximationAlgorithm class. The default sample-limit is 1. @throws IllegalArgumentException If sample-limit < 0. @see com.graphbuilder.curve.BinaryCurveApproximationAlgorithm @see #getSampleLimit() */ public void setSampleLimit(int limit) { if (limit < 0) throw new IllegalArgumentException("Sample-limit >= 0 required."); sampleLimit = limit; } /** Returns the degree of the curve. @see #setDegree(int) */ public int getDegree() { return degree - 1; } /** Sets the degree of the curve. The degree specifies how many controls points have influence when computing a single point on the curve. Specifically, degree + 1 control points are used. The degree must be greater than 0. A degree of 1 is linear, 2 is quadratic, 3 is cubic, etc. Warning: Increasing the degree by 1 doubles the number of computations required. The default degree is 3 (cubic). @see #getDegree() @throws IllegalArgumentException If degree <= 0. */ public void setDegree(int d) { if (d <= 0) throw new IllegalArgumentException("Degree > 0 required."); degree = d + 1; } /** Returns the knot-vector for this curve. @see #setKnotVector(ValueVector) */ public ValueVector getKnotVector() { return knotVector; } /** Sets the knot-vector for this curve. When the knot-vector type is one of UNIFORM_CLAMPED or UNIFORM_UNCLAMPED then the values in the knot-vector will not be used. @see #getKnotVector() @throws IllegalArgumentException If the value-vector is null. */ public void setKnotVector(ValueVector v) { if (v == null) throw new IllegalArgumentException("Knot-vector cannot be null."); knotVector = v; } /** Returns the value of the useDefaultInterval flag. @see #setUseDefaultInterval(boolean) */ public boolean getUseDefaultInterval() { return useDefaultInterval; } /** Sets the value of the useDefaultInterval flag. When the knot-vector type is one of UNIFORM_CLAMPED or UNIFORM_UNCLAMPED and the useDefaultInterval flag is true, then default values will be computed for t_min and t_max. Otherwise t_min and t_max are used as the interval. @see #getUseDefaultInterval() */ public void setUseDefaultInterval(boolean b) { useDefaultInterval = b; } /** Returns the type of knot-vector to use. @see #setKnotVectorType(int) */ public int getKnotVectorType() { return knotVectorType; } /** Sets the type of knot-vector to use. There are 3 types, UNIFORM_CLAMPED, UNIFORM_UNCLAMPED and NON_UNIFORM. NON_UNIFORM can be thought of as user specified. UNIFORM_CLAMPED and UNIFORM_UNCLAMPED are standard knot-vectors for the B-Spline. @see #getKnotVectorType() @throws IllegalArgumentException If the knot-vector type is unknown. */ public void setKnotVectorType(int type) { if (type < 0 || type > 2) throw new IllegalArgumentException("Unknown knot-vector type."); knotVectorType = type; } /** There are two types of requirements for this curve, common requirements and requirements that depend on the knotVectorType. The common requirements are that the group-iterator must be in range and the number of points (group size) must be greater than the degree. If the knot-vector type is NON_UNIFORM (user specified) then there are additional requirements, otherwise there are no additional requirements. The additional requirements when the knotVectorType is NON_UNIFORM are that the internal-knot vector must have an exact size of degree + numPts + 1, where degree is specified by the setDegree method and numPts is the group size. Also, the knot-vector values must be non-decreasing. If any of these requirements are not met, then IllegalArgumentException is thrown */ public void appendTo(MultiPath mp) { if (!gi.isInRange(0, cp.numPoints())) throw new IllegalArgumentException("Group iterator not in range"); int numPts = gi.getGroupSize(); int f = numPts - degree; if (f < 0) throw new IllegalArgumentException("group iterator size - degree < 0"); int x = numPts + degree; if (sharedData.knot.length < x) sharedData.knot = new double[2 * x]; double t1 = t_min; double t2 = t_max; if (knotVectorType == NON_UNIFORM) { if (knotVector.size() != x) throw new IllegalArgumentException("knotVector.size(" + knotVector.size() + ") != " + x); sharedData.knot[0] = knotVector.get(0); for (int i = 1; i < x; i++) { sharedData.knot[i] = knotVector.get(i); if (sharedData.knot[i] < sharedData.knot[i-1]) throw new IllegalArgumentException("Knot not in sorted order! (knot[" + i + "] < knot[" + i + "-1])"); } } else if (knotVectorType == UNIFORM_UNCLAMPED) { double grad = 1.0 / (x - 1); for (int i = 0; i < x; i++) sharedData.knot[i] = i * grad; if (useDefaultInterval) { t1 = (degree - 1) * grad; t2 = 1.0 - (degree - 1) * grad; } } else if (knotVectorType == UNIFORM_CLAMPED) { double grad = 1.0 / (f + 1); for (int i = 0; i < degree; i++) sharedData.knot[i] = 0; int j = degree; for (int i = 1; i <= f; i++) sharedData.knot[j++] = i * grad; for (int i = j; i < x; i++) sharedData.knot[i] = 1.0; if (useDefaultInterval) { t1 = 0.0; t2 = 1.0; } } if (sharedData.a.length < degree) { sharedData.a = new int[2 * degree]; sharedData.c = new int[2 * degree]; } double[] p = new double[mp.getDimension() + 1]; p[mp.getDimension()] = t1; eval(p); if (connect) mp.lineTo(p); else mp.moveTo(p); BinaryCurveApproximationAlgorithm.genPts(this, t1, t2, mp); } /** Non-recursive implementation of the N-function. */ protected double N(double t, int i) { double d = 0; for (int j = 0; j < degree; j++) { double t1 = sharedData.knot[i+j]; double t2 = sharedData.knot[i+j+1]; if (t >= t1 && t <= t2 && t1 != t2) { int dm2 = degree - 2; for (int k = degree - j - 1; k >= 0; k--) sharedData.a[k] = 0; if (j > 0) { for (int k = 0; k < j; k++) sharedData.c[k] = k; sharedData.c[j] = Integer.MAX_VALUE; } else { sharedData.c[0] = dm2; sharedData.c[1] = degree; } int z = 0; while (true) { if (sharedData.c[z] < sharedData.c[z+1] - 1) { double e = 1.0; int bc = 0; int y = dm2 - j; int p = j - 1; for (int m = dm2, n = degree; m >= 0; m--, n--) { if (p >= 0 && sharedData.c[p] == m) { int w = i + bc; double kd = sharedData.knot[w+n]; e *= (kd - t) / (kd - sharedData.knot[w+1]); bc++; p--; } else { int w = i + sharedData.a[y]; double kw = sharedData.knot[w]; e *= (t - kw) / (sharedData.knot[w+n-1] - kw); y--; } } // this code updates the a-counter if (j > 0) { int g = 0; boolean reset = false; while (true) { sharedData.a[g]++; if (sharedData.a[g] > j) { g++; reset = true; } else { if (reset) { for (int h = g - 1; h >= 0; h--) sharedData.a[h] = sharedData.a[g]; } break; } } } d += e; // this code updates the bit-counter sharedData.c[z]++; if (sharedData.c[z] > dm2) break; for (int k = 0; k < z; k++) sharedData.c[k] = k; z = 0; } else { z++; } } break; // required to prevent spikes } } return d; } /* The recursive implementation of the N-function (not used) is below. In addition to being slower, the recursive implementation of the N-function has another problem which relates to the base case. Note: the reason the recursive implementation is slower is because there are a lot of repetitive calculations. Some definitions of the N-function give the base case as t >= knot[i] && t < knot[i+1] or t > knot[i] && t <= knot[i+1]. To see why this is a problem, consider evaluating t on the range [0, 1] with the Bezier Curve knot vector [0,0,0,...,1,1,1]. Then, trying to evaluate t == 1 or t == 0 won't work. Changing the base case to the one below (with equal signs on both comparisons) leads to a problem known as spikes. A curve will have spikes at places where t falls on a knot because when equality is used on both comparisons, the value of t will have 2 regions of influence. */ /*private double N(double t, int i, int k) { if (k == 1) { if (t >= knot[i] && t <= knot[i+1] && knot[i] != knot[i+1]) return 1.0; return 0.0; } double n1 = N(t, i, k-1); double n2 = N(t, i+1, k-1); double a = 0.0; double b = 0.0; if (n1 != 0) a = (t - knot[i]) / (knot[i+k-1] - knot[i]); if (n2 != 0) b = (knot[i+k] - t) / (knot[i+k] - knot[i+1]); return a * n1 + b * n2; }*/ public void resetMemory() { if (sharedData.a.length > 0) { sharedData.a = new int[0]; sharedData.c = new int[0]; } if (sharedData.knot.length > 0) sharedData.knot = new double[0]; } }
[ "public", "class", "BSpline", "extends", "ParametricCurve", "{", "public", "static", "final", "int", "UNIFORM_CLAMPED", "=", "0", ";", "public", "static", "final", "int", "UNIFORM_UNCLAMPED", "=", "1", ";", "public", "static", "final", "int", "NON_UNIFORM", "=", "2", ";", "private", "static", "final", "ThreadLocal", "<", "SharedData", ">", "SHARED_DATA", "=", "new", "ThreadLocal", "<", "SharedData", ">", "(", ")", "{", "protected", "SharedData", "initialValue", "(", ")", "{", "return", "new", "SharedData", "(", ")", ";", "}", "}", ";", "private", "final", "SharedData", "sharedData", "=", "SHARED_DATA", ".", "get", "(", ")", ";", "private", "static", "class", "SharedData", "{", "private", "int", "[", "]", "a", "=", "new", "int", "[", "0", "]", ";", "private", "int", "[", "]", "c", "=", "new", "int", "[", "0", "]", ";", "private", "double", "[", "]", "knot", "=", "new", "double", "[", "0", "]", ";", "}", "private", "ValueVector", "knotVector", "=", "new", "ValueVector", "(", "new", "double", "[", "]", "{", "0", ",", "0", ",", "0", ",", "0", ",", "1", ",", "1", ",", "1", ",", "1", "}", ",", "8", ")", ";", "private", "double", "t_min", "=", "0.0", ";", "private", "double", "t_max", "=", "1.0", ";", "private", "int", "sampleLimit", "=", "1", ";", "private", "int", "degree", "=", "4", ";", "private", "int", "knotVectorType", "=", "UNIFORM_CLAMPED", ";", "private", "boolean", "useDefaultInterval", "=", "true", ";", "public", "BSpline", "(", "ControlPath", "cp", ",", "GroupIterator", "gi", ")", "{", "super", "(", "cp", ",", "gi", ")", ";", "}", "protected", "void", "eval", "(", "double", "[", "]", "p", ")", "{", "int", "dim", "=", "p", ".", "length", "-", "1", ";", "double", "t", "=", "p", "[", "dim", "]", ";", "int", "numPts", "=", "gi", ".", "getGroupSize", "(", ")", ";", "gi", ".", "set", "(", "0", ",", "0", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numPts", ";", "i", "++", ")", "{", "double", "w", "=", "N", "(", "t", ",", "i", ")", ";", "double", "[", "]", "loc", "=", "cp", ".", "getPoint", "(", "gi", ".", "next", "(", ")", ")", ".", "getLocation", "(", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "dim", ";", "j", "++", ")", "p", "[", "j", "]", "+=", "(", "loc", "[", "j", "]", "*", "w", ")", ";", "}", "}", "/**\r\n\tSpecifies the interval that the curve should define itself on. The default interval is [0.0, 1.0].\r\n\tWhen the knot-vector type is one of UNIFORM_CLAMPED or UNIFORM_UNCLAMPED and the useDefaultInterval\r\n\tflag is true, then these values will not be used.\r\n\r\n\t@throws IllegalArgumentException If t_min > t_max.\r\n\t@see #t_min()\r\n\t@see #t_max()\r\n\t*/", "public", "void", "setInterval", "(", "double", "t_min", ",", "double", "t_max", ")", "{", "if", "(", "t_min", ">", "t_max", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "t_min <= t_max required.", "\"", ")", ";", "this", ".", "t_min", "=", "t_min", ";", "this", ".", "t_max", "=", "t_max", ";", "}", "/**\r\n\tReturns the starting interval value.\r\n\r\n\t@see #setInterval(double, double)\r\n\t@see #t_max()\r\n\t*/", "public", "double", "t_min", "(", ")", "{", "return", "t_min", ";", "}", "/**\r\n\tReturns the finishing interval value.\r\n\r\n\t@see #setInterval(double, double)\r\n\t@see #t_min()\r\n\t*/", "public", "double", "t_max", "(", ")", "{", "return", "t_max", ";", "}", "public", "int", "getSampleLimit", "(", ")", "{", "return", "sampleLimit", ";", "}", "/**\r\n\tSets the sample-limit. For more information on the sample-limit, see the\r\n\tBinaryCurveApproximationAlgorithm class. The default sample-limit is 1.\r\n\r\n\t@throws IllegalArgumentException If sample-limit < 0.\r\n\t@see com.graphbuilder.curve.BinaryCurveApproximationAlgorithm\r\n\t@see #getSampleLimit()\r\n\t*/", "public", "void", "setSampleLimit", "(", "int", "limit", ")", "{", "if", "(", "limit", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Sample-limit >= 0 required.", "\"", ")", ";", "sampleLimit", "=", "limit", ";", "}", "/**\r\n\tReturns the degree of the curve.\r\n\r\n\t@see #setDegree(int)\r\n\t*/", "public", "int", "getDegree", "(", ")", "{", "return", "degree", "-", "1", ";", "}", "/**\r\n\tSets the degree of the curve. The degree specifies how many controls points have influence\r\n\twhen computing a single point on the curve. Specifically, degree + 1 control points are used.\r\n\tThe degree must be greater than 0. A degree of 1 is linear, 2 is quadratic, 3 is cubic, etc.\r\n\tWarning: Increasing the degree by 1 doubles the number of computations required. The default\r\n\tdegree is 3 (cubic).\r\n\r\n\t@see #getDegree()\r\n\t@throws IllegalArgumentException If degree <= 0.\r\n\t*/", "public", "void", "setDegree", "(", "int", "d", ")", "{", "if", "(", "d", "<=", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Degree > 0 required.", "\"", ")", ";", "degree", "=", "d", "+", "1", ";", "}", "/**\r\n\tReturns the knot-vector for this curve.\r\n\r\n\t@see #setKnotVector(ValueVector)\r\n\t*/", "public", "ValueVector", "getKnotVector", "(", ")", "{", "return", "knotVector", ";", "}", "/**\r\n\tSets the knot-vector for this curve. When the knot-vector type is one of UNIFORM_CLAMPED or\r\n\tUNIFORM_UNCLAMPED then the values in the knot-vector will not be used.\r\n\r\n\t@see #getKnotVector()\r\n\t@throws IllegalArgumentException If the value-vector is null.\r\n\t*/", "public", "void", "setKnotVector", "(", "ValueVector", "v", ")", "{", "if", "(", "v", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Knot-vector cannot be null.", "\"", ")", ";", "knotVector", "=", "v", ";", "}", "/**\r\n\tReturns the value of the useDefaultInterval flag.\r\n\r\n\t@see #setUseDefaultInterval(boolean)\r\n\t*/", "public", "boolean", "getUseDefaultInterval", "(", ")", "{", "return", "useDefaultInterval", ";", "}", "/**\r\n\tSets the value of the useDefaultInterval flag. When the knot-vector type is one of UNIFORM_CLAMPED or\r\n\tUNIFORM_UNCLAMPED and the useDefaultInterval flag is true, then default values will be computed for\r\n\tt_min and t_max. Otherwise t_min and t_max are used as the interval.\r\n\r\n\t@see #getUseDefaultInterval()\r\n\t*/", "public", "void", "setUseDefaultInterval", "(", "boolean", "b", ")", "{", "useDefaultInterval", "=", "b", ";", "}", "/**\r\n\tReturns the type of knot-vector to use.\r\n\r\n\t@see #setKnotVectorType(int)\r\n\t*/", "public", "int", "getKnotVectorType", "(", ")", "{", "return", "knotVectorType", ";", "}", "/**\r\n\tSets the type of knot-vector to use. There are 3 types, UNIFORM_CLAMPED, UNIFORM_UNCLAMPED and NON_UNIFORM.\r\n\tNON_UNIFORM can be thought of as user specified. UNIFORM_CLAMPED and UNIFORM_UNCLAMPED are standard\r\n\tknot-vectors for the B-Spline.\r\n\r\n\t@see #getKnotVectorType()\r\n\t@throws IllegalArgumentException If the knot-vector type is unknown.\r\n\t*/", "public", "void", "setKnotVectorType", "(", "int", "type", ")", "{", "if", "(", "type", "<", "0", "||", "type", ">", "2", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Unknown knot-vector type.", "\"", ")", ";", "knotVectorType", "=", "type", ";", "}", "/**\r\n\tThere are two types of requirements for this curve, common requirements and requirements that depend on the\r\n\tknotVectorType. The common requirements are that the group-iterator must be in range and the number of\r\n\tpoints (group size) must be greater than the degree. If the knot-vector type is NON_UNIFORM (user specified)\r\n\tthen there are additional requirements, otherwise there are no additional requirements.\r\n\r\n\tThe additional requirements when the knotVectorType is NON_UNIFORM are that the internal-knot vector must have\r\n\tan exact size of degree + numPts + 1, where degree is specified by the setDegree method and numPts is the\r\n\tgroup size. Also, the knot-vector values must be non-decreasing.\r\n\r\n\tIf any of these requirements are not met, then IllegalArgumentException is thrown\r\n\t*/", "public", "void", "appendTo", "(", "MultiPath", "mp", ")", "{", "if", "(", "!", "gi", ".", "isInRange", "(", "0", ",", "cp", ".", "numPoints", "(", ")", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Group iterator not in range", "\"", ")", ";", "int", "numPts", "=", "gi", ".", "getGroupSize", "(", ")", ";", "int", "f", "=", "numPts", "-", "degree", ";", "if", "(", "f", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "group iterator size - degree < 0", "\"", ")", ";", "int", "x", "=", "numPts", "+", "degree", ";", "if", "(", "sharedData", ".", "knot", ".", "length", "<", "x", ")", "sharedData", ".", "knot", "=", "new", "double", "[", "2", "*", "x", "]", ";", "double", "t1", "=", "t_min", ";", "double", "t2", "=", "t_max", ";", "if", "(", "knotVectorType", "==", "NON_UNIFORM", ")", "{", "if", "(", "knotVector", ".", "size", "(", ")", "!=", "x", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "knotVector.size(", "\"", "+", "knotVector", ".", "size", "(", ")", "+", "\"", ") != ", "\"", "+", "x", ")", ";", "sharedData", ".", "knot", "[", "0", "]", "=", "knotVector", ".", "get", "(", "0", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "x", ";", "i", "++", ")", "{", "sharedData", ".", "knot", "[", "i", "]", "=", "knotVector", ".", "get", "(", "i", ")", ";", "if", "(", "sharedData", ".", "knot", "[", "i", "]", "<", "sharedData", ".", "knot", "[", "i", "-", "1", "]", ")", "throw", "new", "IllegalArgumentException", "(", "\"", "Knot not in sorted order! (knot[", "\"", "+", "i", "+", "\"", "] < knot[", "\"", "+", "i", "+", "\"", "-1])", "\"", ")", ";", "}", "}", "else", "if", "(", "knotVectorType", "==", "UNIFORM_UNCLAMPED", ")", "{", "double", "grad", "=", "1.0", "/", "(", "x", "-", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "x", ";", "i", "++", ")", "sharedData", ".", "knot", "[", "i", "]", "=", "i", "*", "grad", ";", "if", "(", "useDefaultInterval", ")", "{", "t1", "=", "(", "degree", "-", "1", ")", "*", "grad", ";", "t2", "=", "1.0", "-", "(", "degree", "-", "1", ")", "*", "grad", ";", "}", "}", "else", "if", "(", "knotVectorType", "==", "UNIFORM_CLAMPED", ")", "{", "double", "grad", "=", "1.0", "/", "(", "f", "+", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "degree", ";", "i", "++", ")", "sharedData", ".", "knot", "[", "i", "]", "=", "0", ";", "int", "j", "=", "degree", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<=", "f", ";", "i", "++", ")", "sharedData", ".", "knot", "[", "j", "++", "]", "=", "i", "*", "grad", ";", "for", "(", "int", "i", "=", "j", ";", "i", "<", "x", ";", "i", "++", ")", "sharedData", ".", "knot", "[", "i", "]", "=", "1.0", ";", "if", "(", "useDefaultInterval", ")", "{", "t1", "=", "0.0", ";", "t2", "=", "1.0", ";", "}", "}", "if", "(", "sharedData", ".", "a", ".", "length", "<", "degree", ")", "{", "sharedData", ".", "a", "=", "new", "int", "[", "2", "*", "degree", "]", ";", "sharedData", ".", "c", "=", "new", "int", "[", "2", "*", "degree", "]", ";", "}", "double", "[", "]", "p", "=", "new", "double", "[", "mp", ".", "getDimension", "(", ")", "+", "1", "]", ";", "p", "[", "mp", ".", "getDimension", "(", ")", "]", "=", "t1", ";", "eval", "(", "p", ")", ";", "if", "(", "connect", ")", "mp", ".", "lineTo", "(", "p", ")", ";", "else", "mp", ".", "moveTo", "(", "p", ")", ";", "BinaryCurveApproximationAlgorithm", ".", "genPts", "(", "this", ",", "t1", ",", "t2", ",", "mp", ")", ";", "}", "/**\r\n\tNon-recursive implementation of the N-function.\r\n\t*/", "protected", "double", "N", "(", "double", "t", ",", "int", "i", ")", "{", "double", "d", "=", "0", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "degree", ";", "j", "++", ")", "{", "double", "t1", "=", "sharedData", ".", "knot", "[", "i", "+", "j", "]", ";", "double", "t2", "=", "sharedData", ".", "knot", "[", "i", "+", "j", "+", "1", "]", ";", "if", "(", "t", ">=", "t1", "&&", "t", "<=", "t2", "&&", "t1", "!=", "t2", ")", "{", "int", "dm2", "=", "degree", "-", "2", ";", "for", "(", "int", "k", "=", "degree", "-", "j", "-", "1", ";", "k", ">=", "0", ";", "k", "--", ")", "sharedData", ".", "a", "[", "k", "]", "=", "0", ";", "if", "(", "j", ">", "0", ")", "{", "for", "(", "int", "k", "=", "0", ";", "k", "<", "j", ";", "k", "++", ")", "sharedData", ".", "c", "[", "k", "]", "=", "k", ";", "sharedData", ".", "c", "[", "j", "]", "=", "Integer", ".", "MAX_VALUE", ";", "}", "else", "{", "sharedData", ".", "c", "[", "0", "]", "=", "dm2", ";", "sharedData", ".", "c", "[", "1", "]", "=", "degree", ";", "}", "int", "z", "=", "0", ";", "while", "(", "true", ")", "{", "if", "(", "sharedData", ".", "c", "[", "z", "]", "<", "sharedData", ".", "c", "[", "z", "+", "1", "]", "-", "1", ")", "{", "double", "e", "=", "1.0", ";", "int", "bc", "=", "0", ";", "int", "y", "=", "dm2", "-", "j", ";", "int", "p", "=", "j", "-", "1", ";", "for", "(", "int", "m", "=", "dm2", ",", "n", "=", "degree", ";", "m", ">=", "0", ";", "m", "--", ",", "n", "--", ")", "{", "if", "(", "p", ">=", "0", "&&", "sharedData", ".", "c", "[", "p", "]", "==", "m", ")", "{", "int", "w", "=", "i", "+", "bc", ";", "double", "kd", "=", "sharedData", ".", "knot", "[", "w", "+", "n", "]", ";", "e", "*=", "(", "kd", "-", "t", ")", "/", "(", "kd", "-", "sharedData", ".", "knot", "[", "w", "+", "1", "]", ")", ";", "bc", "++", ";", "p", "--", ";", "}", "else", "{", "int", "w", "=", "i", "+", "sharedData", ".", "a", "[", "y", "]", ";", "double", "kw", "=", "sharedData", ".", "knot", "[", "w", "]", ";", "e", "*=", "(", "t", "-", "kw", ")", "/", "(", "sharedData", ".", "knot", "[", "w", "+", "n", "-", "1", "]", "-", "kw", ")", ";", "y", "--", ";", "}", "}", "if", "(", "j", ">", "0", ")", "{", "int", "g", "=", "0", ";", "boolean", "reset", "=", "false", ";", "while", "(", "true", ")", "{", "sharedData", ".", "a", "[", "g", "]", "++", ";", "if", "(", "sharedData", ".", "a", "[", "g", "]", ">", "j", ")", "{", "g", "++", ";", "reset", "=", "true", ";", "}", "else", "{", "if", "(", "reset", ")", "{", "for", "(", "int", "h", "=", "g", "-", "1", ";", "h", ">=", "0", ";", "h", "--", ")", "sharedData", ".", "a", "[", "h", "]", "=", "sharedData", ".", "a", "[", "g", "]", ";", "}", "break", ";", "}", "}", "}", "d", "+=", "e", ";", "sharedData", ".", "c", "[", "z", "]", "++", ";", "if", "(", "sharedData", ".", "c", "[", "z", "]", ">", "dm2", ")", "break", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "z", ";", "k", "++", ")", "sharedData", ".", "c", "[", "k", "]", "=", "k", ";", "z", "=", "0", ";", "}", "else", "{", "z", "++", ";", "}", "}", "break", ";", "}", "}", "return", "d", ";", "}", "/*\r\n\tThe recursive implementation of the N-function (not used) is below. In addition to being\r\n\tslower, the recursive implementation of the N-function has another problem which relates to\r\n\tthe base case. Note: the reason the recursive implementation is slower is because there\r\n\tare a lot of repetitive calculations.\r\n\r\n\tSome definitions of the N-function give the base case as t >= knot[i] && t < knot[i+1] or\r\n\tt > knot[i] && t <= knot[i+1]. To see why this is a problem, consider evaluating t on the\r\n\trange [0, 1] with the Bezier Curve knot vector [0,0,0,...,1,1,1]. Then, trying to evaluate\r\n\tt == 1 or t == 0 won't work. Changing the base case to the one below (with equal signs on\r\n\tboth comparisons) leads to a problem known as spikes. A curve will have spikes\tat places\r\n\twhere t falls on a knot because when equality is used on both comparisons, the value of t\r\n\twill have 2 regions of influence.\r\n\t*/", "/*private double N(double t, int i, int k) {\r\n\t\tif (k == 1) {\r\n\t\t\tif (t >= knot[i] && t <= knot[i+1] && knot[i] != knot[i+1]) return 1.0;\r\n\t\t\treturn 0.0;\r\n\t\t}\r\n\r\n\t\tdouble n1 = N(t, i, k-1);\r\n\t\tdouble n2 = N(t, i+1, k-1);\r\n\r\n\t\tdouble a = 0.0;\r\n\t\tdouble b = 0.0;\r\n\r\n\t\tif (n1 != 0) a = (t - knot[i]) / (knot[i+k-1] - knot[i]);\r\n\t\tif (n2 != 0) b = (knot[i+k] - t) / (knot[i+k] - knot[i+1]);\r\n\r\n\t\treturn a * n1 + b * n2;\r\n\t}*/", "public", "void", "resetMemory", "(", ")", "{", "if", "(", "sharedData", ".", "a", ".", "length", ">", "0", ")", "{", "sharedData", ".", "a", "=", "new", "int", "[", "0", "]", ";", "sharedData", ".", "c", "=", "new", "int", "[", "0", "]", ";", "}", "if", "(", "sharedData", ".", "knot", ".", "length", ">", "0", ")", "sharedData", ".", "knot", "=", "new", "double", "[", "0", "]", ";", "}", "}" ]
<p>General non-rational B-Spline implementation where the degree can be specified.
[ "<p", ">", "General", "non", "-", "rational", "B", "-", "Spline", "implementation", "where", "the", "degree", "can", "be", "specified", "." ]
[ "// counter used for the a-function values (required length >= degree)\r", "// counter used for bit patterns (required length >= degree)\r", "// (required length >= numPts + degree)\r", "// the internal degree variable is always 1 plus the specified degree\r", "//double w = N(t, i, degree);\r", "//pt[i][j] * w);\r", "// this code updates the a-counter\r", "// this code updates the bit-counter\r", "// required to prevent spikes\r" ]
[ { "param": "ParametricCurve", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ParametricCurve", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84f2fe58deef6842c83b1b0a0279aac22d3bae15
aTiKhan/nuxeo
modules/platform/nuxeo-automation/nuxeo-automation-core/src/main/java/org/nuxeo/ecm/automation/core/rendering/FreemarkerRender.java
[ "Apache-2.0" ]
Java
FreemarkerRender
/** * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> */
@author Bogdan Stefanescu
[ "@author", "Bogdan", "Stefanescu" ]
public class FreemarkerRender extends FreemarkerEngine implements Renderer { public FreemarkerRender() { setResourceLocator(new ResourceLocator() { @Override public URL getResourceURL(String key) { try { if (key.startsWith(Renderer.TEMPLATE_PREFIX)) { return Framework.getService(ResourceService.class).getResource( key.substring(Renderer.TEMPLATE_PREFIX.length())); } else { return new URL(key); } } catch (MalformedURLException e) { return null; } } @Override public File getResourceFile(String key) { return null; } }); } public void renderContent(String content, Object ctx, Writer writer) throws IOException, TemplateException { StringReader reader = new StringReader(content); Template tpl = new Template("@inline", reader, getConfiguration(), "UTF-8"); Environment env = tpl.createProcessingEnvironment(ctx, writer, getObjectWrapper()); env.process(); } @Override public String render(String uriOrContent, Map<String, Object> root) throws RenderingException, TemplateException, IOException { if (root.get("Document") != null) { // mvel wrapper not supported in freemarker root.put("Document", root.get("This")); } StringWriter result = new StringWriter(); if (uriOrContent.startsWith(Renderer.TEMPLATE_PREFIX)) { render(uriOrContent, root, result); } else { renderContent(uriOrContent, root, result); } return result.getBuffer().toString(); } }
[ "public", "class", "FreemarkerRender", "extends", "FreemarkerEngine", "implements", "Renderer", "{", "public", "FreemarkerRender", "(", ")", "{", "setResourceLocator", "(", "new", "ResourceLocator", "(", ")", "{", "@", "Override", "public", "URL", "getResourceURL", "(", "String", "key", ")", "{", "try", "{", "if", "(", "key", ".", "startsWith", "(", "Renderer", ".", "TEMPLATE_PREFIX", ")", ")", "{", "return", "Framework", ".", "getService", "(", "ResourceService", ".", "class", ")", ".", "getResource", "(", "key", ".", "substring", "(", "Renderer", ".", "TEMPLATE_PREFIX", ".", "length", "(", ")", ")", ")", ";", "}", "else", "{", "return", "new", "URL", "(", "key", ")", ";", "}", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "return", "null", ";", "}", "}", "@", "Override", "public", "File", "getResourceFile", "(", "String", "key", ")", "{", "return", "null", ";", "}", "}", ")", ";", "}", "public", "void", "renderContent", "(", "String", "content", ",", "Object", "ctx", ",", "Writer", "writer", ")", "throws", "IOException", ",", "TemplateException", "{", "StringReader", "reader", "=", "new", "StringReader", "(", "content", ")", ";", "Template", "tpl", "=", "new", "Template", "(", "\"", "@inline", "\"", ",", "reader", ",", "getConfiguration", "(", ")", ",", "\"", "UTF-8", "\"", ")", ";", "Environment", "env", "=", "tpl", ".", "createProcessingEnvironment", "(", "ctx", ",", "writer", ",", "getObjectWrapper", "(", ")", ")", ";", "env", ".", "process", "(", ")", ";", "}", "@", "Override", "public", "String", "render", "(", "String", "uriOrContent", ",", "Map", "<", "String", ",", "Object", ">", "root", ")", "throws", "RenderingException", ",", "TemplateException", ",", "IOException", "{", "if", "(", "root", ".", "get", "(", "\"", "Document", "\"", ")", "!=", "null", ")", "{", "root", ".", "put", "(", "\"", "Document", "\"", ",", "root", ".", "get", "(", "\"", "This", "\"", ")", ")", ";", "}", "StringWriter", "result", "=", "new", "StringWriter", "(", ")", ";", "if", "(", "uriOrContent", ".", "startsWith", "(", "Renderer", ".", "TEMPLATE_PREFIX", ")", ")", "{", "render", "(", "uriOrContent", ",", "root", ",", "result", ")", ";", "}", "else", "{", "renderContent", "(", "uriOrContent", ",", "root", ",", "result", ")", ";", "}", "return", "result", ".", "getBuffer", "(", ")", ".", "toString", "(", ")", ";", "}", "}" ]
@author <a href="mailto:[email protected]">Bogdan Stefanescu</a>
[ "@author", "<a", "href", "=", "\"", "mailto", ":", "bs@nuxeo", ".", "com", "\"", ">", "Bogdan", "Stefanescu<", "/", "a", ">" ]
[ "// mvel wrapper not supported in freemarker" ]
[ { "param": "FreemarkerEngine", "type": null }, { "param": "Renderer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FreemarkerEngine", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Renderer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
84fe92ea55bcbfecae925925247a7de0a38a3b28
contextshuffling/flowable-engine
modules/flowable-app-engine-rest/src/main/java/org/flowable/app/rest/AppRestResponseFactory.java
[ "Apache-2.0" ]
Java
AppRestResponseFactory
/** * @author Tijs Rademakers */
@author Tijs Rademakers
[ "@author", "Tijs", "Rademakers" ]
public class AppRestResponseFactory { public AppDefinitionResponse createAppDefinitionResponse(AppDefinition appDefinition) { return createAppDefinitionResponse(appDefinition, createUrlBuilder()); } public AppDefinitionResponse createAppDefinitionResponse(AppDefinition appDefinition, AppRestUrlBuilder urlBuilder) { AppDefinitionResponse response = new AppDefinitionResponse(appDefinition); response.setUrl(urlBuilder.buildUrl(AppRestUrls.URL_APP_DEFINITION, appDefinition.getId())); return response; } public List<AppDefinitionResponse> createAppDefinitionResponseList(List<AppDefinition> appDefinitions) { AppRestUrlBuilder urlBuilder = createUrlBuilder(); List<AppDefinitionResponse> responseList = new ArrayList<>(); for (AppDefinition appDefinition : appDefinitions) { responseList.add(createAppDefinitionResponse(appDefinition, urlBuilder)); } return responseList; } public List<AppDeploymentResponse> createAppDeploymentResponseList(List<AppDeployment> deployments) { AppRestUrlBuilder urlBuilder = createUrlBuilder(); List<AppDeploymentResponse> responseList = new ArrayList<>(); for (AppDeployment deployment : deployments) { responseList.add(createAppDeploymentResponse(deployment, urlBuilder)); } return responseList; } public AppDeploymentResponse createAppDeploymentResponse(AppDeployment deployment) { return createAppDeploymentResponse(deployment, createUrlBuilder()); } public AppDeploymentResponse createAppDeploymentResponse(AppDeployment deployment, AppRestUrlBuilder urlBuilder) { return new AppDeploymentResponse(deployment, urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT, deployment.getId())); } public List<AppDeploymentResourceResponse> createDeploymentResourceResponseList(String deploymentId, List<String> resourceList, ContentTypeResolver contentTypeResolver) { AppRestUrlBuilder urlBuilder = createUrlBuilder(); // Add additional metadata to the artifact-strings before returning List<AppDeploymentResourceResponse> responseList = new ArrayList<>(); for (String resourceId : resourceList) { String contentType = null; if (resourceId.toLowerCase().endsWith(".app")) { contentType = ContentType.APPLICATION_JSON.getMimeType(); } else { contentType = contentTypeResolver.resolveContentType(resourceId); } responseList.add(createDeploymentResourceResponse(deploymentId, resourceId, contentType, urlBuilder)); } return responseList; } public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType) { return createDeploymentResourceResponse(deploymentId, resourceId, contentType, createUrlBuilder()); } public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType, AppRestUrlBuilder urlBuilder) { // Create URL's String resourceUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE, deploymentId, resourceId); String resourceContentUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE_CONTENT, deploymentId, resourceId); // Determine type String type = "resource"; if (resourceId.endsWith(".app")) { type = "appDefinition"; } return new AppDeploymentResourceResponse(resourceId, resourceUrl, resourceContentUrl, contentType, type); } protected AppRestUrlBuilder createUrlBuilder() { return AppRestUrlBuilder.fromCurrentRequest(); } }
[ "public", "class", "AppRestResponseFactory", "{", "public", "AppDefinitionResponse", "createAppDefinitionResponse", "(", "AppDefinition", "appDefinition", ")", "{", "return", "createAppDefinitionResponse", "(", "appDefinition", ",", "createUrlBuilder", "(", ")", ")", ";", "}", "public", "AppDefinitionResponse", "createAppDefinitionResponse", "(", "AppDefinition", "appDefinition", ",", "AppRestUrlBuilder", "urlBuilder", ")", "{", "AppDefinitionResponse", "response", "=", "new", "AppDefinitionResponse", "(", "appDefinition", ")", ";", "response", ".", "setUrl", "(", "urlBuilder", ".", "buildUrl", "(", "AppRestUrls", ".", "URL_APP_DEFINITION", ",", "appDefinition", ".", "getId", "(", ")", ")", ")", ";", "return", "response", ";", "}", "public", "List", "<", "AppDefinitionResponse", ">", "createAppDefinitionResponseList", "(", "List", "<", "AppDefinition", ">", "appDefinitions", ")", "{", "AppRestUrlBuilder", "urlBuilder", "=", "createUrlBuilder", "(", ")", ";", "List", "<", "AppDefinitionResponse", ">", "responseList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "AppDefinition", "appDefinition", ":", "appDefinitions", ")", "{", "responseList", ".", "add", "(", "createAppDefinitionResponse", "(", "appDefinition", ",", "urlBuilder", ")", ")", ";", "}", "return", "responseList", ";", "}", "public", "List", "<", "AppDeploymentResponse", ">", "createAppDeploymentResponseList", "(", "List", "<", "AppDeployment", ">", "deployments", ")", "{", "AppRestUrlBuilder", "urlBuilder", "=", "createUrlBuilder", "(", ")", ";", "List", "<", "AppDeploymentResponse", ">", "responseList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "AppDeployment", "deployment", ":", "deployments", ")", "{", "responseList", ".", "add", "(", "createAppDeploymentResponse", "(", "deployment", ",", "urlBuilder", ")", ")", ";", "}", "return", "responseList", ";", "}", "public", "AppDeploymentResponse", "createAppDeploymentResponse", "(", "AppDeployment", "deployment", ")", "{", "return", "createAppDeploymentResponse", "(", "deployment", ",", "createUrlBuilder", "(", ")", ")", ";", "}", "public", "AppDeploymentResponse", "createAppDeploymentResponse", "(", "AppDeployment", "deployment", ",", "AppRestUrlBuilder", "urlBuilder", ")", "{", "return", "new", "AppDeploymentResponse", "(", "deployment", ",", "urlBuilder", ".", "buildUrl", "(", "AppRestUrls", ".", "URL_DEPLOYMENT", ",", "deployment", ".", "getId", "(", ")", ")", ")", ";", "}", "public", "List", "<", "AppDeploymentResourceResponse", ">", "createDeploymentResourceResponseList", "(", "String", "deploymentId", ",", "List", "<", "String", ">", "resourceList", ",", "ContentTypeResolver", "contentTypeResolver", ")", "{", "AppRestUrlBuilder", "urlBuilder", "=", "createUrlBuilder", "(", ")", ";", "List", "<", "AppDeploymentResourceResponse", ">", "responseList", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "String", "resourceId", ":", "resourceList", ")", "{", "String", "contentType", "=", "null", ";", "if", "(", "resourceId", ".", "toLowerCase", "(", ")", ".", "endsWith", "(", "\"", ".app", "\"", ")", ")", "{", "contentType", "=", "ContentType", ".", "APPLICATION_JSON", ".", "getMimeType", "(", ")", ";", "}", "else", "{", "contentType", "=", "contentTypeResolver", ".", "resolveContentType", "(", "resourceId", ")", ";", "}", "responseList", ".", "add", "(", "createDeploymentResourceResponse", "(", "deploymentId", ",", "resourceId", ",", "contentType", ",", "urlBuilder", ")", ")", ";", "}", "return", "responseList", ";", "}", "public", "AppDeploymentResourceResponse", "createDeploymentResourceResponse", "(", "String", "deploymentId", ",", "String", "resourceId", ",", "String", "contentType", ")", "{", "return", "createDeploymentResourceResponse", "(", "deploymentId", ",", "resourceId", ",", "contentType", ",", "createUrlBuilder", "(", ")", ")", ";", "}", "public", "AppDeploymentResourceResponse", "createDeploymentResourceResponse", "(", "String", "deploymentId", ",", "String", "resourceId", ",", "String", "contentType", ",", "AppRestUrlBuilder", "urlBuilder", ")", "{", "String", "resourceUrl", "=", "urlBuilder", ".", "buildUrl", "(", "AppRestUrls", ".", "URL_DEPLOYMENT_RESOURCE", ",", "deploymentId", ",", "resourceId", ")", ";", "String", "resourceContentUrl", "=", "urlBuilder", ".", "buildUrl", "(", "AppRestUrls", ".", "URL_DEPLOYMENT_RESOURCE_CONTENT", ",", "deploymentId", ",", "resourceId", ")", ";", "String", "type", "=", "\"", "resource", "\"", ";", "if", "(", "resourceId", ".", "endsWith", "(", "\"", ".app", "\"", ")", ")", "{", "type", "=", "\"", "appDefinition", "\"", ";", "}", "return", "new", "AppDeploymentResourceResponse", "(", "resourceId", ",", "resourceUrl", ",", "resourceContentUrl", ",", "contentType", ",", "type", ")", ";", "}", "protected", "AppRestUrlBuilder", "createUrlBuilder", "(", ")", "{", "return", "AppRestUrlBuilder", ".", "fromCurrentRequest", "(", ")", ";", "}", "}" ]
@author Tijs Rademakers
[ "@author", "Tijs", "Rademakers" ]
[ "// Add additional metadata to the artifact-strings before returning", "// Create URL's", "// Determine type" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
1700bd0872a662ce84cd2d130db2d96057387deb
qwc/cmdlineoptions
java/src/to/mmo/cmdlineoptions/CmdOptions.java
[ "BSD-2-Clause" ]
Java
CmdOptions
/** * Written by Marcel M. Otte, (c) 2013 For use under the BSD 2-clause License, * or in other words: Do what you want with it as long as you leave all * copyright notices where they are and don't bother me when you break your pc. * :) */
Written by Marcel M. Otte, (c) 2013 For use under the BSD 2-clause License, or in other words: Do what you want with it as long as you leave all copyright notices where they are and don't bother me when you break your pc.
[ "Written", "by", "Marcel", "M", ".", "Otte", "(", "c", ")", "2013", "For", "use", "under", "the", "BSD", "2", "-", "clause", "License", "or", "in", "other", "words", ":", "Do", "what", "you", "want", "with", "it", "as", "long", "as", "you", "leave", "all", "copyright", "notices", "where", "they", "are", "and", "don", "'", "t", "bother", "me", "when", "you", "break", "your", "pc", "." ]
public class CmdOptions { private static CmdOptions instance; private static String optionChar; private HashMap<String, CommandLineOption> options; private boolean showOptions; private boolean combineSwitches; private boolean dontQuitOnError; private CmdOptions() { optionChar = "-"; this.setSwitchCombination(false); this.setShowOptions(false); this.setDontQuitOnError(false); options = new HashMap<String, CommandLineOption>(); this.createOption("help") .setDescription( "Show all possible options and their parameters.") .addLongCommand("--help").addCommand("-h").addCommand("-?"); } public static CmdOptions i() { if (instance == null) { instance = new CmdOptions(); } return instance; } public void setSwitchCombination(boolean on) { this.combineSwitches = on; } @SuppressWarnings("static-access") public void setOptionCharacter(String c) { this.optionChar = c; } public void setDontQuitOnError(boolean set) { this.dontQuitOnError = set; } public void setShowOptions(boolean show) { this.showOptions = show; } public void setHelpGeneration(boolean on) { if (!on) { options.remove("help"); } } public CommandLineOption createOption(String name) { CommandLineOption o = new CommandLineOption(name); this.options.put(name, o); return o; } public CommandLineOption getBareOption(String name) { return options.get(name); } public String[] get(String name) { return getOption(name); } public String get(String name, int index) { String[] values = getOption(name); if (values.length > index && index > 0) { return values[index]; } return null; } public String[] getOption(String name) { if (options.get(name).getValues().size() > 0) return options.get(name).getValues().toArray(new String[0]); else if (options.get(name).getDefaultParameter().size() > 0) return options.get(name).getDefaultParameter() .toArray(new String[0]); return null; } public List<String> getValuesAsList(String name) { if (options.get(name).getValues().size() > 0) { return options.get(name).getValues(); } return null; } public Integer[] getOptionAsInt(String name) { if (options.get(name).getValues().size() > 0) { ArrayList<Integer> list = new ArrayList<Integer>(); for (String o : options.get(name).getValues()) { list.add(Integer.parseInt(o)); } return list.toArray(new Integer[0]); } else if (options.get(name).getDefaultParameter().size() > 0) { ArrayList<Integer> list = new ArrayList<Integer>(); for (String o : options.get(name).getDefaultParameter()) { list.add(Integer.parseInt(o)); } return list.toArray(new Integer[0]); } return null; } public Integer getOptionAsInt(String name, int index) { Integer[] array = getOptionAsInt(name); if (index >= 0 && index < array.length) { return array[index]; } return null; } public Double[] getOptionAsDouble(String name) { if (options.get(name).getValues().size() > 0) { ArrayList<Double> list = new ArrayList<Double>(); for (String o : options.get(name).getValues()) { list.add(Double.parseDouble(o)); } return list.toArray(new Double[0]); } else if (options.get(name).getDefaultParameter().size() > 0) { ArrayList<Double> list = new ArrayList<Double>(); for (String o : options.get(name).getDefaultParameter()) { list.add(Double.parseDouble(o)); } return list.toArray(new Double[0]); } return null; } public Double getOptionAsDouble(String name, int index) { Double[] array = getOptionAsDouble(name); if (index >= 0 && index < array.length) { return array[index]; } return null; } public boolean isSet(String option) { return options.get(option).isSet(); } public boolean isSet(String option, String parameter) { return this.getValuesAsList(option).contains(parameter); } public void resetValues() { for (CommandLineOption o : options.values()) { o.getValues().clear(); } } public void reset() { options.clear(); } public String toString(boolean help) { StringBuilder b = new StringBuilder(); if (help) { b.append("Possible options:\n"); } b.append("-options\n"); CommandLineOption[] vars = options.values().toArray( new CommandLineOption[0]); Arrays.sort(vars, new Comparator<CommandLineOption>() { @Override public int compare(CommandLineOption o1, CommandLineOption o2) { return o1.getName().compareTo(o2.getName()); } }); for (CommandLineOption o : vars) { b.append("\t").append(o.toString(help)).append("\n"); } b.append("/options\n"); return b.toString(); } private Integer[] getIndices(String[] args) { List<Integer> indices = new ArrayList<Integer>(); for (int i = 0; i < args.length; ++i) { if (args[i].startsWith(optionChar)) { indices.add(i); } } return indices.toArray(new Integer[0]); } private CommandLineOption getOptionByCommand(String cmd) { for (CommandLineOption o : this.options.values()) { for (String s : o.getCmd()) { if (cmd.equals(s)) { return o; } } for (String s : o.getCmdLong()) { if (cmd.equals(s)) { return o; } } } return null; } private boolean cmdExists(String cmd) { return getOptionByCommand(cmd) != null; } private boolean switchExists(char c) { for (CommandLineOption op : this.options.values()) { for (String s : op.getCmd()) { if (s.toCharArray()[0] == c) { return true; } } } return false; } private CommandLineOption[] getOptionBySwitches(String switches) { List<CommandLineOption> o = new ArrayList<CommandLineOption>(); for (CommandLineOption op : this.options.values()) { for (String s : op.getCmd()) { for (char c : switches.toCharArray()) { if (s.toCharArray()[0] == c) { o.add(op); } } } } return o.toArray(new CommandLineOption[0]); } public int parse(String[] args) { int exit = 0; // get indices Integer[] indices = getIndices(args); // check for correct options boolean ok = true; for (Integer i : indices) { String o = args[i].replace(optionChar, ""); if (!cmdExists(o)) { if (this.combineSwitches) { for (char c : o.toCharArray()) { if (!switchExists(c)) { System.err.println("Unrecognized switch '" + c + "'"); ok = false; } } } else { System.err.println("Unrecognized option '" + o + "'"); ok = false; } } } // quit if there are unknown options if (!ok && exit == 0) { exit = 1; } // now parse CommandLineOption op; for (int a = 0; a < indices.length; ++a) { String o = args[indices[a]].replace(optionChar, ""); op = this.getOptionByCommand(o); if (op == null) { if (this.combineSwitches) { CommandLineOption[] mop = getOptionBySwitches(o); for (CommandLineOption opt : mop) { opt.setSet(true); } } continue; } // the option is set! op.setSet(true); // are there parameters? if (indices[a] < args.length - 1 && a < indices.length - 1 && indices[a + 1] - indices[a] > 1) { // parameters between options for (int b = indices[a] + 1; b < indices[a + 1]; ++b) { op.getValues().add(args[b]); } } else if (a == indices.length - 1 && args.length - 1 > indices[a]) { // parameters at the last option for (int b = indices[a] + 1; b < args.length; ++b) { op.getValues().add(args[b]); } } } // check for possible parameters for (CommandLineOption o : options.values()) { for (String s : o.getValues()) { if (o.getPossibleParams().size() > 0 && !o.getPossibleParams().contains(s)) { System.err.println("Parameter \"" + s + "\" for Option \"" + o.getName() + "\" not allowed!"); ok = false; } } } if (!ok && exit == 0) { exit = 2; } // check parameter counts for (CommandLineOption o : options.values()) { if (o.getValues().size() < o.getMinParameters() && o.getMinParameters() != 0 || o.getValues().size() > o.getMaxParameters() && o.getMaxParameters() != 0 || o.getStepSizeParameters() != 0 && o.getValues().size() % o.getStepSizeParameters() != 0) { System.err.println(o.getName() + ": Parameter count not correct! Check help."); exit = 3; } } // set default for that options that aren't set for (CommandLineOption o : options.values()) { if (!o.isSet() && o.isRequired()) { System.err .println(o.getName() + " (" + o.getName() + "): has no default parameter and has to be set on commandline!"); exit = 4; } if (!o.isSet() && o.getDefaultParameter().size() != 0) o.getValues().addAll(o.getDefaultParameter()); } if (options.get("help").isSet() || exit > 0) { System.out.println(this.toString(true)); if (!this.dontQuitOnError) System.exit(exit); } if (this.showOptions) { System.out.println(this.toString(false)); } return exit; } public static String getOptionChar() { return optionChar; } }
[ "public", "class", "CmdOptions", "{", "private", "static", "CmdOptions", "instance", ";", "private", "static", "String", "optionChar", ";", "private", "HashMap", "<", "String", ",", "CommandLineOption", ">", "options", ";", "private", "boolean", "showOptions", ";", "private", "boolean", "combineSwitches", ";", "private", "boolean", "dontQuitOnError", ";", "private", "CmdOptions", "(", ")", "{", "optionChar", "=", "\"", "-", "\"", ";", "this", ".", "setSwitchCombination", "(", "false", ")", ";", "this", ".", "setShowOptions", "(", "false", ")", ";", "this", ".", "setDontQuitOnError", "(", "false", ")", ";", "options", "=", "new", "HashMap", "<", "String", ",", "CommandLineOption", ">", "(", ")", ";", "this", ".", "createOption", "(", "\"", "help", "\"", ")", ".", "setDescription", "(", "\"", "Show all possible options and their parameters.", "\"", ")", ".", "addLongCommand", "(", "\"", "--help", "\"", ")", ".", "addCommand", "(", "\"", "-h", "\"", ")", ".", "addCommand", "(", "\"", "-?", "\"", ")", ";", "}", "public", "static", "CmdOptions", "i", "(", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "instance", "=", "new", "CmdOptions", "(", ")", ";", "}", "return", "instance", ";", "}", "public", "void", "setSwitchCombination", "(", "boolean", "on", ")", "{", "this", ".", "combineSwitches", "=", "on", ";", "}", "@", "SuppressWarnings", "(", "\"", "static-access", "\"", ")", "public", "void", "setOptionCharacter", "(", "String", "c", ")", "{", "this", ".", "optionChar", "=", "c", ";", "}", "public", "void", "setDontQuitOnError", "(", "boolean", "set", ")", "{", "this", ".", "dontQuitOnError", "=", "set", ";", "}", "public", "void", "setShowOptions", "(", "boolean", "show", ")", "{", "this", ".", "showOptions", "=", "show", ";", "}", "public", "void", "setHelpGeneration", "(", "boolean", "on", ")", "{", "if", "(", "!", "on", ")", "{", "options", ".", "remove", "(", "\"", "help", "\"", ")", ";", "}", "}", "public", "CommandLineOption", "createOption", "(", "String", "name", ")", "{", "CommandLineOption", "o", "=", "new", "CommandLineOption", "(", "name", ")", ";", "this", ".", "options", ".", "put", "(", "name", ",", "o", ")", ";", "return", "o", ";", "}", "public", "CommandLineOption", "getBareOption", "(", "String", "name", ")", "{", "return", "options", ".", "get", "(", "name", ")", ";", "}", "public", "String", "[", "]", "get", "(", "String", "name", ")", "{", "return", "getOption", "(", "name", ")", ";", "}", "public", "String", "get", "(", "String", "name", ",", "int", "index", ")", "{", "String", "[", "]", "values", "=", "getOption", "(", "name", ")", ";", "if", "(", "values", ".", "length", ">", "index", "&&", "index", ">", "0", ")", "{", "return", "values", "[", "index", "]", ";", "}", "return", "null", ";", "}", "public", "String", "[", "]", "getOption", "(", "String", "name", ")", "{", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ".", "size", "(", ")", ">", "0", ")", "return", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "else", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ".", "size", "(", ")", ">", "0", ")", "return", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "return", "null", ";", "}", "public", "List", "<", "String", ">", "getValuesAsList", "(", "String", "name", ")", "{", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "return", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ";", "}", "return", "null", ";", "}", "public", "Integer", "[", "]", "getOptionAsInt", "(", "String", "name", ")", "{", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "ArrayList", "<", "Integer", ">", "list", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "String", "o", ":", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ")", "{", "list", ".", "add", "(", "Integer", ".", "parseInt", "(", "o", ")", ")", ";", "}", "return", "list", ".", "toArray", "(", "new", "Integer", "[", "0", "]", ")", ";", "}", "else", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "ArrayList", "<", "Integer", ">", "list", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "String", "o", ":", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ")", "{", "list", ".", "add", "(", "Integer", ".", "parseInt", "(", "o", ")", ")", ";", "}", "return", "list", ".", "toArray", "(", "new", "Integer", "[", "0", "]", ")", ";", "}", "return", "null", ";", "}", "public", "Integer", "getOptionAsInt", "(", "String", "name", ",", "int", "index", ")", "{", "Integer", "[", "]", "array", "=", "getOptionAsInt", "(", "name", ")", ";", "if", "(", "index", ">=", "0", "&&", "index", "<", "array", ".", "length", ")", "{", "return", "array", "[", "index", "]", ";", "}", "return", "null", ";", "}", "public", "Double", "[", "]", "getOptionAsDouble", "(", "String", "name", ")", "{", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "ArrayList", "<", "Double", ">", "list", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "for", "(", "String", "o", ":", "options", ".", "get", "(", "name", ")", ".", "getValues", "(", ")", ")", "{", "list", ".", "add", "(", "Double", ".", "parseDouble", "(", "o", ")", ")", ";", "}", "return", "list", ".", "toArray", "(", "new", "Double", "[", "0", "]", ")", ";", "}", "else", "if", "(", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ".", "size", "(", ")", ">", "0", ")", "{", "ArrayList", "<", "Double", ">", "list", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "for", "(", "String", "o", ":", "options", ".", "get", "(", "name", ")", ".", "getDefaultParameter", "(", ")", ")", "{", "list", ".", "add", "(", "Double", ".", "parseDouble", "(", "o", ")", ")", ";", "}", "return", "list", ".", "toArray", "(", "new", "Double", "[", "0", "]", ")", ";", "}", "return", "null", ";", "}", "public", "Double", "getOptionAsDouble", "(", "String", "name", ",", "int", "index", ")", "{", "Double", "[", "]", "array", "=", "getOptionAsDouble", "(", "name", ")", ";", "if", "(", "index", ">=", "0", "&&", "index", "<", "array", ".", "length", ")", "{", "return", "array", "[", "index", "]", ";", "}", "return", "null", ";", "}", "public", "boolean", "isSet", "(", "String", "option", ")", "{", "return", "options", ".", "get", "(", "option", ")", ".", "isSet", "(", ")", ";", "}", "public", "boolean", "isSet", "(", "String", "option", ",", "String", "parameter", ")", "{", "return", "this", ".", "getValuesAsList", "(", "option", ")", ".", "contains", "(", "parameter", ")", ";", "}", "public", "void", "resetValues", "(", ")", "{", "for", "(", "CommandLineOption", "o", ":", "options", ".", "values", "(", ")", ")", "{", "o", ".", "getValues", "(", ")", ".", "clear", "(", ")", ";", "}", "}", "public", "void", "reset", "(", ")", "{", "options", ".", "clear", "(", ")", ";", "}", "public", "String", "toString", "(", "boolean", "help", ")", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "help", ")", "{", "b", ".", "append", "(", "\"", "Possible options:", "\\n", "\"", ")", ";", "}", "b", ".", "append", "(", "\"", "-options", "\\n", "\"", ")", ";", "CommandLineOption", "[", "]", "vars", "=", "options", ".", "values", "(", ")", ".", "toArray", "(", "new", "CommandLineOption", "[", "0", "]", ")", ";", "Arrays", ".", "sort", "(", "vars", ",", "new", "Comparator", "<", "CommandLineOption", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "CommandLineOption", "o1", ",", "CommandLineOption", "o2", ")", "{", "return", "o1", ".", "getName", "(", ")", ".", "compareTo", "(", "o2", ".", "getName", "(", ")", ")", ";", "}", "}", ")", ";", "for", "(", "CommandLineOption", "o", ":", "vars", ")", "{", "b", ".", "append", "(", "\"", "\\t", "\"", ")", ".", "append", "(", "o", ".", "toString", "(", "help", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "b", ".", "append", "(", "\"", "/options", "\\n", "\"", ")", ";", "return", "b", ".", "toString", "(", ")", ";", "}", "private", "Integer", "[", "]", "getIndices", "(", "String", "[", "]", "args", ")", "{", "List", "<", "Integer", ">", "indices", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "++", "i", ")", "{", "if", "(", "args", "[", "i", "]", ".", "startsWith", "(", "optionChar", ")", ")", "{", "indices", ".", "add", "(", "i", ")", ";", "}", "}", "return", "indices", ".", "toArray", "(", "new", "Integer", "[", "0", "]", ")", ";", "}", "private", "CommandLineOption", "getOptionByCommand", "(", "String", "cmd", ")", "{", "for", "(", "CommandLineOption", "o", ":", "this", ".", "options", ".", "values", "(", ")", ")", "{", "for", "(", "String", "s", ":", "o", ".", "getCmd", "(", ")", ")", "{", "if", "(", "cmd", ".", "equals", "(", "s", ")", ")", "{", "return", "o", ";", "}", "}", "for", "(", "String", "s", ":", "o", ".", "getCmdLong", "(", ")", ")", "{", "if", "(", "cmd", ".", "equals", "(", "s", ")", ")", "{", "return", "o", ";", "}", "}", "}", "return", "null", ";", "}", "private", "boolean", "cmdExists", "(", "String", "cmd", ")", "{", "return", "getOptionByCommand", "(", "cmd", ")", "!=", "null", ";", "}", "private", "boolean", "switchExists", "(", "char", "c", ")", "{", "for", "(", "CommandLineOption", "op", ":", "this", ".", "options", ".", "values", "(", ")", ")", "{", "for", "(", "String", "s", ":", "op", ".", "getCmd", "(", ")", ")", "{", "if", "(", "s", ".", "toCharArray", "(", ")", "[", "0", "]", "==", "c", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}", "private", "CommandLineOption", "[", "]", "getOptionBySwitches", "(", "String", "switches", ")", "{", "List", "<", "CommandLineOption", ">", "o", "=", "new", "ArrayList", "<", "CommandLineOption", ">", "(", ")", ";", "for", "(", "CommandLineOption", "op", ":", "this", ".", "options", ".", "values", "(", ")", ")", "{", "for", "(", "String", "s", ":", "op", ".", "getCmd", "(", ")", ")", "{", "for", "(", "char", "c", ":", "switches", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "s", ".", "toCharArray", "(", ")", "[", "0", "]", "==", "c", ")", "{", "o", ".", "add", "(", "op", ")", ";", "}", "}", "}", "}", "return", "o", ".", "toArray", "(", "new", "CommandLineOption", "[", "0", "]", ")", ";", "}", "public", "int", "parse", "(", "String", "[", "]", "args", ")", "{", "int", "exit", "=", "0", ";", "Integer", "[", "]", "indices", "=", "getIndices", "(", "args", ")", ";", "boolean", "ok", "=", "true", ";", "for", "(", "Integer", "i", ":", "indices", ")", "{", "String", "o", "=", "args", "[", "i", "]", ".", "replace", "(", "optionChar", ",", "\"", "\"", ")", ";", "if", "(", "!", "cmdExists", "(", "o", ")", ")", "{", "if", "(", "this", ".", "combineSwitches", ")", "{", "for", "(", "char", "c", ":", "o", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "!", "switchExists", "(", "c", ")", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Unrecognized switch '", "\"", "+", "c", "+", "\"", "'", "\"", ")", ";", "ok", "=", "false", ";", "}", "}", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"", "Unrecognized option '", "\"", "+", "o", "+", "\"", "'", "\"", ")", ";", "ok", "=", "false", ";", "}", "}", "}", "if", "(", "!", "ok", "&&", "exit", "==", "0", ")", "{", "exit", "=", "1", ";", "}", "CommandLineOption", "op", ";", "for", "(", "int", "a", "=", "0", ";", "a", "<", "indices", ".", "length", ";", "++", "a", ")", "{", "String", "o", "=", "args", "[", "indices", "[", "a", "]", "]", ".", "replace", "(", "optionChar", ",", "\"", "\"", ")", ";", "op", "=", "this", ".", "getOptionByCommand", "(", "o", ")", ";", "if", "(", "op", "==", "null", ")", "{", "if", "(", "this", ".", "combineSwitches", ")", "{", "CommandLineOption", "[", "]", "mop", "=", "getOptionBySwitches", "(", "o", ")", ";", "for", "(", "CommandLineOption", "opt", ":", "mop", ")", "{", "opt", ".", "setSet", "(", "true", ")", ";", "}", "}", "continue", ";", "}", "op", ".", "setSet", "(", "true", ")", ";", "if", "(", "indices", "[", "a", "]", "<", "args", ".", "length", "-", "1", "&&", "a", "<", "indices", ".", "length", "-", "1", "&&", "indices", "[", "a", "+", "1", "]", "-", "indices", "[", "a", "]", ">", "1", ")", "{", "for", "(", "int", "b", "=", "indices", "[", "a", "]", "+", "1", ";", "b", "<", "indices", "[", "a", "+", "1", "]", ";", "++", "b", ")", "{", "op", ".", "getValues", "(", ")", ".", "add", "(", "args", "[", "b", "]", ")", ";", "}", "}", "else", "if", "(", "a", "==", "indices", ".", "length", "-", "1", "&&", "args", ".", "length", "-", "1", ">", "indices", "[", "a", "]", ")", "{", "for", "(", "int", "b", "=", "indices", "[", "a", "]", "+", "1", ";", "b", "<", "args", ".", "length", ";", "++", "b", ")", "{", "op", ".", "getValues", "(", ")", ".", "add", "(", "args", "[", "b", "]", ")", ";", "}", "}", "}", "for", "(", "CommandLineOption", "o", ":", "options", ".", "values", "(", ")", ")", "{", "for", "(", "String", "s", ":", "o", ".", "getValues", "(", ")", ")", "{", "if", "(", "o", ".", "getPossibleParams", "(", ")", ".", "size", "(", ")", ">", "0", "&&", "!", "o", ".", "getPossibleParams", "(", ")", ".", "contains", "(", "s", ")", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Parameter ", "\\\"", "\"", "+", "s", "+", "\"", "\\\"", " for Option ", "\\\"", "\"", "+", "o", ".", "getName", "(", ")", "+", "\"", "\\\"", " not allowed!", "\"", ")", ";", "ok", "=", "false", ";", "}", "}", "}", "if", "(", "!", "ok", "&&", "exit", "==", "0", ")", "{", "exit", "=", "2", ";", "}", "for", "(", "CommandLineOption", "o", ":", "options", ".", "values", "(", ")", ")", "{", "if", "(", "o", ".", "getValues", "(", ")", ".", "size", "(", ")", "<", "o", ".", "getMinParameters", "(", ")", "&&", "o", ".", "getMinParameters", "(", ")", "!=", "0", "||", "o", ".", "getValues", "(", ")", ".", "size", "(", ")", ">", "o", ".", "getMaxParameters", "(", ")", "&&", "o", ".", "getMaxParameters", "(", ")", "!=", "0", "||", "o", ".", "getStepSizeParameters", "(", ")", "!=", "0", "&&", "o", ".", "getValues", "(", ")", ".", "size", "(", ")", "%", "o", ".", "getStepSizeParameters", "(", ")", "!=", "0", ")", "{", "System", ".", "err", ".", "println", "(", "o", ".", "getName", "(", ")", "+", "\"", ": Parameter count not correct! Check help.", "\"", ")", ";", "exit", "=", "3", ";", "}", "}", "for", "(", "CommandLineOption", "o", ":", "options", ".", "values", "(", ")", ")", "{", "if", "(", "!", "o", ".", "isSet", "(", ")", "&&", "o", ".", "isRequired", "(", ")", ")", "{", "System", ".", "err", ".", "println", "(", "o", ".", "getName", "(", ")", "+", "\"", " (", "\"", "+", "o", ".", "getName", "(", ")", "+", "\"", "): has no default parameter and has to be set on commandline!", "\"", ")", ";", "exit", "=", "4", ";", "}", "if", "(", "!", "o", ".", "isSet", "(", ")", "&&", "o", ".", "getDefaultParameter", "(", ")", ".", "size", "(", ")", "!=", "0", ")", "o", ".", "getValues", "(", ")", ".", "addAll", "(", "o", ".", "getDefaultParameter", "(", ")", ")", ";", "}", "if", "(", "options", ".", "get", "(", "\"", "help", "\"", ")", ".", "isSet", "(", ")", "||", "exit", ">", "0", ")", "{", "System", ".", "out", ".", "println", "(", "this", ".", "toString", "(", "true", ")", ")", ";", "if", "(", "!", "this", ".", "dontQuitOnError", ")", "System", ".", "exit", "(", "exit", ")", ";", "}", "if", "(", "this", ".", "showOptions", ")", "{", "System", ".", "out", ".", "println", "(", "this", ".", "toString", "(", "false", ")", ")", ";", "}", "return", "exit", ";", "}", "public", "static", "String", "getOptionChar", "(", ")", "{", "return", "optionChar", ";", "}", "}" ]
Written by Marcel M. Otte, (c) 2013 For use under the BSD 2-clause License, or in other words: Do what you want with it as long as you leave all copyright notices where they are and don't bother me when you break your pc.
[ "Written", "by", "Marcel", "M", ".", "Otte", "(", "c", ")", "2013", "For", "use", "under", "the", "BSD", "2", "-", "clause", "License", "or", "in", "other", "words", ":", "Do", "what", "you", "want", "with", "it", "as", "long", "as", "you", "leave", "all", "copyright", "notices", "where", "they", "are", "and", "don", "'", "t", "bother", "me", "when", "you", "break", "your", "pc", "." ]
[ "// get indices", "// check for correct options", "// quit if there are unknown options", "// now parse", "// the option is set!", "// are there parameters?", "// parameters between options", "// parameters at the last option", "// check for possible parameters", "// check parameter counts", "// set default for that options that aren't set" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
1701531405d9f792ef3a91366d2e079aecd97d1c
comalat/comalat-android-app
app/src/main/java/org/sakaiproject/api/json/JsonWriter.java
[ "ECL-2.0" ]
Java
JsonWriter
/** * Created by vasilis on 1/13/16. * this is the json writes for updates (PUT calls) */
Created by vasilis on 1/13/16. this is the json writes for updates (PUT calls)
[ "Created", "by", "vasilis", "on", "1", "/", "13", "/", "16", ".", "this", "is", "the", "json", "writes", "for", "updates", "(", "PUT", "calls", ")" ]
public class JsonWriter { Context context; /** * the JsonWriter constructor * * @param context the context */ public JsonWriter(Context context) { this.context = context; } public static String updateUserAccountJson(Context context, String name, String surname, String email, String pass) throws IOException { Gson gson = new Gson(); if (ActionsHelper.createDirIfNotExists(context, User.getUserEid() + File.separator + "user")) { String userDataJson = ActionsHelper.readJsonFile(context, "fullUserDataJson", User.getUserEid() + File.separator + "user"); UserData userData = gson.fromJson(userDataJson, UserData.class); userData.setFirstName(name); userData.setLastName(surname); userData.setEmail(email); if (pass != null) userData.setPassword(pass); return gson.toJson(userData); } return null; } public String updateUserProfileInfo() { JSONObject root = new JSONObject(); try { root.put("academicProfileUrl", Profile.getAcademicProfileUrl()); root.put("birthday", Profile.getBirthday()); root.put("birthdayDisplay", Profile.getBirthdayDisplay()); root.put("businessBiography", Profile.getBusinessBiography()); // TODO: change the value with the list from the profile class root.put("companyProfiles", JSONObject.NULL); root.put("course", Profile.getCourse()); if (Profile.getDateOfBirth() != null) { JSONObject dateOfBirth = new JSONObject(); dateOfBirth.put("date", Profile.getDateOfBirth().getDate()); dateOfBirth.put("day", Profile.getDateOfBirth().getDay()); dateOfBirth.put("month", Profile.getDateOfBirth().getMonth()); dateOfBirth.put("time", Profile.getDateOfBirth().getTime()); dateOfBirth.put("timezoneOffset", Profile.getDateOfBirth().getTimezoneOffset()); dateOfBirth.put("year", Profile.getDateOfBirth().getYear()); root.put("dateOfBirth", dateOfBirth); } root.put("department", Profile.getDepartment()); root.put("displayName", Profile.getDisplayName()); root.put("email", User.getEmail()); root.put("facsimile", Profile.getFacsimile()); root.put("favouriteBooks", Profile.getFavouriteBooks()); root.put("favouriteMovies", Profile.getFavouriteMovies()); root.put("favouriteQuotes", Profile.getFavouriteQuotes()); root.put("favouriteTvShows", Profile.getFavouriteTvShows()); root.put("homepage", Profile.getHomepage()); root.put("homephone", Profile.getHomephone()); root.put("imageThumbUrl", Profile.getImageThumbUrl()); root.put("imageUrl", Profile.getImageUrl()); root.put("mobilephone", Profile.getMobilephone()); root.put("nickname", Profile.getNickname()); root.put("personalSummary", Profile.getPersonalSummary()); root.put("position", Profile.getPosition()); // TODO: change the value with the map from the profile class root.put("props", JSONObject.NULL); root.put("publications", Profile.getPublications()); root.put("room", Profile.getRoom()); root.put("school", Profile.getSchool()); root.put("socialInfo", Profile.getSocialInfo()); root.put("staffProfile", Profile.getStaffProfile()); // if(Profile.getStatus() != null) { // JSONObject status = new JSONObject(); // root.put("status", status); // } // TODO: has to change with the status object root.put("status", JSONObject.NULL); root.put("subjects", Profile.getSubjects()); root.put("universityProfileUrl", Profile.getUniversityProfileUrl()); root.put("userUuid", User.getUserId()); root.put("workphone", Profile.getWorkphone()); root.put("locked", Profile.isLocked()); root.put("entityReference", "/profile/" + User.getUserEid()); root.put("entityURL", context.getResources().getString(R.string.url) + "/profile/" + User.getUserEid()); root.put("entityId", User.getUserEid()); } catch (JSONException e) { e.printStackTrace(); } return root.toString(); } }
[ "public", "class", "JsonWriter", "{", "Context", "context", ";", "/**\n * the JsonWriter constructor\n *\n * @param context the context\n */", "public", "JsonWriter", "(", "Context", "context", ")", "{", "this", ".", "context", "=", "context", ";", "}", "public", "static", "String", "updateUserAccountJson", "(", "Context", "context", ",", "String", "name", ",", "String", "surname", ",", "String", "email", ",", "String", "pass", ")", "throws", "IOException", "{", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "if", "(", "ActionsHelper", ".", "createDirIfNotExists", "(", "context", ",", "User", ".", "getUserEid", "(", ")", "+", "File", ".", "separator", "+", "\"", "user", "\"", ")", ")", "{", "String", "userDataJson", "=", "ActionsHelper", ".", "readJsonFile", "(", "context", ",", "\"", "fullUserDataJson", "\"", ",", "User", ".", "getUserEid", "(", ")", "+", "File", ".", "separator", "+", "\"", "user", "\"", ")", ";", "UserData", "userData", "=", "gson", ".", "fromJson", "(", "userDataJson", ",", "UserData", ".", "class", ")", ";", "userData", ".", "setFirstName", "(", "name", ")", ";", "userData", ".", "setLastName", "(", "surname", ")", ";", "userData", ".", "setEmail", "(", "email", ")", ";", "if", "(", "pass", "!=", "null", ")", "userData", ".", "setPassword", "(", "pass", ")", ";", "return", "gson", ".", "toJson", "(", "userData", ")", ";", "}", "return", "null", ";", "}", "public", "String", "updateUserProfileInfo", "(", ")", "{", "JSONObject", "root", "=", "new", "JSONObject", "(", ")", ";", "try", "{", "root", ".", "put", "(", "\"", "academicProfileUrl", "\"", ",", "Profile", ".", "getAcademicProfileUrl", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "birthday", "\"", ",", "Profile", ".", "getBirthday", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "birthdayDisplay", "\"", ",", "Profile", ".", "getBirthdayDisplay", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "businessBiography", "\"", ",", "Profile", ".", "getBusinessBiography", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "companyProfiles", "\"", ",", "JSONObject", ".", "NULL", ")", ";", "root", ".", "put", "(", "\"", "course", "\"", ",", "Profile", ".", "getCourse", "(", ")", ")", ";", "if", "(", "Profile", ".", "getDateOfBirth", "(", ")", "!=", "null", ")", "{", "JSONObject", "dateOfBirth", "=", "new", "JSONObject", "(", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "date", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getDate", "(", ")", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "day", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getDay", "(", ")", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "month", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getMonth", "(", ")", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "time", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getTime", "(", ")", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "timezoneOffset", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getTimezoneOffset", "(", ")", ")", ";", "dateOfBirth", ".", "put", "(", "\"", "year", "\"", ",", "Profile", ".", "getDateOfBirth", "(", ")", ".", "getYear", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "dateOfBirth", "\"", ",", "dateOfBirth", ")", ";", "}", "root", ".", "put", "(", "\"", "department", "\"", ",", "Profile", ".", "getDepartment", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "displayName", "\"", ",", "Profile", ".", "getDisplayName", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "email", "\"", ",", "User", ".", "getEmail", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "facsimile", "\"", ",", "Profile", ".", "getFacsimile", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "favouriteBooks", "\"", ",", "Profile", ".", "getFavouriteBooks", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "favouriteMovies", "\"", ",", "Profile", ".", "getFavouriteMovies", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "favouriteQuotes", "\"", ",", "Profile", ".", "getFavouriteQuotes", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "favouriteTvShows", "\"", ",", "Profile", ".", "getFavouriteTvShows", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "homepage", "\"", ",", "Profile", ".", "getHomepage", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "homephone", "\"", ",", "Profile", ".", "getHomephone", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "imageThumbUrl", "\"", ",", "Profile", ".", "getImageThumbUrl", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "imageUrl", "\"", ",", "Profile", ".", "getImageUrl", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "mobilephone", "\"", ",", "Profile", ".", "getMobilephone", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "nickname", "\"", ",", "Profile", ".", "getNickname", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "personalSummary", "\"", ",", "Profile", ".", "getPersonalSummary", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "position", "\"", ",", "Profile", ".", "getPosition", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "props", "\"", ",", "JSONObject", ".", "NULL", ")", ";", "root", ".", "put", "(", "\"", "publications", "\"", ",", "Profile", ".", "getPublications", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "room", "\"", ",", "Profile", ".", "getRoom", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "school", "\"", ",", "Profile", ".", "getSchool", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "socialInfo", "\"", ",", "Profile", ".", "getSocialInfo", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "staffProfile", "\"", ",", "Profile", ".", "getStaffProfile", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "status", "\"", ",", "JSONObject", ".", "NULL", ")", ";", "root", ".", "put", "(", "\"", "subjects", "\"", ",", "Profile", ".", "getSubjects", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "universityProfileUrl", "\"", ",", "Profile", ".", "getUniversityProfileUrl", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "userUuid", "\"", ",", "User", ".", "getUserId", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "workphone", "\"", ",", "Profile", ".", "getWorkphone", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "locked", "\"", ",", "Profile", ".", "isLocked", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "entityReference", "\"", ",", "\"", "/profile/", "\"", "+", "User", ".", "getUserEid", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "entityURL", "\"", ",", "context", ".", "getResources", "(", ")", ".", "getString", "(", "R", ".", "string", ".", "url", ")", "+", "\"", "/profile/", "\"", "+", "User", ".", "getUserEid", "(", ")", ")", ";", "root", ".", "put", "(", "\"", "entityId", "\"", ",", "User", ".", "getUserEid", "(", ")", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "root", ".", "toString", "(", ")", ";", "}", "}" ]
Created by vasilis on 1/13/16.
[ "Created", "by", "vasilis", "on", "1", "/", "13", "/", "16", "." ]
[ "// TODO: change the value with the list from the profile class", "// TODO: change the value with the map from the profile class", "// if(Profile.getStatus() != null) {", "// JSONObject status = new JSONObject();", "// root.put(\"status\", status);", "// }", "// TODO: has to change with the status object" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
170195537681e679a726b5cce92d9321d04dec81
ffang/quarkus
extensions/cxf-jaxrs/deployment/src/main/java/io/quarkus/cxf/jaxrs/deployment/CxfJaxrsServerConfigBuildItem.java
[ "Apache-2.0" ]
Java
CxfJaxrsServerConfigBuildItem
/** * A build item that represents the configuration of the CXF JAXRS server. */
A build item that represents the configuration of the CXF JAXRS server.
[ "A", "build", "item", "that", "represents", "the", "configuration", "of", "the", "CXF", "JAXRS", "server", "." ]
public final class CxfJaxrsServerConfigBuildItem extends SimpleBuildItem { private final String path; private final Map<String, String> initParameters; public CxfJaxrsServerConfigBuildItem(String path, Map<String, String> initParameters) { this.path = path; this.initParameters = initParameters; } public String getPath() { return path; } public Map<String, String> getInitParameters() { return initParameters; } }
[ "public", "final", "class", "CxfJaxrsServerConfigBuildItem", "extends", "SimpleBuildItem", "{", "private", "final", "String", "path", ";", "private", "final", "Map", "<", "String", ",", "String", ">", "initParameters", ";", "public", "CxfJaxrsServerConfigBuildItem", "(", "String", "path", ",", "Map", "<", "String", ",", "String", ">", "initParameters", ")", "{", "this", ".", "path", "=", "path", ";", "this", ".", "initParameters", "=", "initParameters", ";", "}", "public", "String", "getPath", "(", ")", "{", "return", "path", ";", "}", "public", "Map", "<", "String", ",", "String", ">", "getInitParameters", "(", ")", "{", "return", "initParameters", ";", "}", "}" ]
A build item that represents the configuration of the CXF JAXRS server.
[ "A", "build", "item", "that", "represents", "the", "configuration", "of", "the", "CXF", "JAXRS", "server", "." ]
[]
[ { "param": "SimpleBuildItem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SimpleBuildItem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
17076f41b6f2b9ce74a17b52fda13adeb4263e1d
RootServices/otter
otter/src/main/java/net/tokensmith/otter/gateway/servlet/translator/HttpServletRequestTranslator.java
[ "MIT" ]
Java
HttpServletRequestTranslator
/** * Translator for a HttpServletRequest to a Otter Request */
Translator for a HttpServletRequest to a Otter Request
[ "Translator", "for", "a", "HttpServletRequest", "to", "a", "Otter", "Request" ]
public class HttpServletRequestTranslator { protected static Logger LOGGER = LoggerFactory.getLogger(HttpServletRequestTranslator.class); private static String PARAM_DELIMITER = "?"; private static String EMPTY = ""; private HttpServletRequestCookieTranslator httpServletCookieTranslator; private HttpServletRequestHeaderTranslator httpServletRequestHeaderTranslator; private QueryStringToMap queryStringToMap; private MimeTypeTranslator mimeTypeTranslator; // used to ensure http only is set on incoming cookies private Map<String, CookieConfig> cookieConfigs; public HttpServletRequestTranslator(HttpServletRequestCookieTranslator httpServletCookieTranslator, HttpServletRequestHeaderTranslator httpServletRequestHeaderTranslator, QueryStringToMap queryStringToMap, MimeTypeTranslator mimeTypeTranslator, Map<String, CookieConfig> cookieConfigs) { this.httpServletCookieTranslator = httpServletCookieTranslator; this.httpServletRequestHeaderTranslator = httpServletRequestHeaderTranslator; this.queryStringToMap = queryStringToMap; this.mimeTypeTranslator = mimeTypeTranslator; this.cookieConfigs = cookieConfigs; } public Ask from(HttpServletRequest containerRequest, byte[] containerBody) throws IOException { Method method = Method.valueOf(containerRequest.getMethod()); String pathWithParams = containerRequest.getRequestURI() + queryStringForUrl(containerRequest.getQueryString()); Map<String, Cookie> otterCookies = from(containerRequest.getCookies()); Map<String, String> headers = httpServletRequestHeaderTranslator.from(containerRequest); Optional<String> queryString = Optional.ofNullable(containerRequest.getQueryString()); Map<String, List<String>> queryParams = queryStringToMap.run(queryString); MimeType contentType = mimeTypeTranslator.to(containerRequest.getContentType()); String acceptFrom = containerRequest.getHeader(Header.ACCEPT.getValue()); MimeType acceptTo = mimeTypeTranslator.to(acceptFrom); Map<String, List<String>> formData = new HashMap<>(); Optional<byte[]> body = Optional.empty(); if (isForm(method, contentType)) { String form = new String(containerBody); formData = queryStringToMap.run(Optional.of(form)); } else if (method == Method.POST || method == Method.PUT || method == Method.PATCH && !isForm(method, contentType)) { body = Optional.of(containerBody); } String ipAddress = containerRequest.getRemoteAddr(); return new AskBuilder() .matcher(Optional.empty()) .method(method) .scheme(containerRequest.getScheme()) .authority(containerRequest.getServerName()) .port(containerRequest.getServerPort()) .pathWithParams(pathWithParams) .contentType(contentType) .accept(acceptTo) .cookies(otterCookies) .headers(headers) .queryParams(queryParams) .formData(formData) .body(body) .csrfChallenge(Optional.empty()) .ipAddress(ipAddress) .build(); } protected Map<String, Cookie> from(javax.servlet.http.Cookie[] containerCookies) { Map<String, Cookie> otterCookies = new HashMap<>(); if (Objects.nonNull(containerCookies)) { // throw away duplicate cookies.. idk why duplicates occur. for (javax.servlet.http.Cookie cookie : containerCookies) { Cookie candidate = httpServletCookieTranslator.from(cookie); Cookie existing = otterCookies.get(candidate.getName()); if (Objects.nonNull(existing) && existing.equals(candidate)) { LOGGER.debug("Found a duplicate cookie, {}, ignoring it.", existing.getName()); } else { // ensure http only is set - some ajax wont pass this is.. idk why CookieConfig expectedConfig = cookieConfigs.get(candidate.getName()); if (Objects.nonNull(expectedConfig)) { if (!expectedConfig.getHttpOnly().equals(candidate.isHttpOnly())) { // force it to the default then. LOGGER.debug("httpOnly is being overriden for cookie, {}. expected {}, actual {}", candidate.getName(), expectedConfig.getHttpOnly(), candidate.isHttpOnly()); candidate.setHttpOnly(expectedConfig.getHttpOnly()); } } otterCookies.put(candidate.getName(), candidate); } } } return otterCookies; } protected Boolean isForm(Method method, MimeType contentType) { return method == Method.POST && TopLevelType.APPLICATION.toString().equals(contentType.getType()) && SubType.FORM.toString().equals(contentType.getSubType()); } protected String queryStringForUrl(String queryString) { String queryStringForUrl; if (Objects.nonNull(queryString)) { queryStringForUrl = PARAM_DELIMITER + queryString; } else { queryStringForUrl = EMPTY; } return queryStringForUrl; } }
[ "public", "class", "HttpServletRequestTranslator", "{", "protected", "static", "Logger", "LOGGER", "=", "LoggerFactory", ".", "getLogger", "(", "HttpServletRequestTranslator", ".", "class", ")", ";", "private", "static", "String", "PARAM_DELIMITER", "=", "\"", "?", "\"", ";", "private", "static", "String", "EMPTY", "=", "\"", "\"", ";", "private", "HttpServletRequestCookieTranslator", "httpServletCookieTranslator", ";", "private", "HttpServletRequestHeaderTranslator", "httpServletRequestHeaderTranslator", ";", "private", "QueryStringToMap", "queryStringToMap", ";", "private", "MimeTypeTranslator", "mimeTypeTranslator", ";", "private", "Map", "<", "String", ",", "CookieConfig", ">", "cookieConfigs", ";", "public", "HttpServletRequestTranslator", "(", "HttpServletRequestCookieTranslator", "httpServletCookieTranslator", ",", "HttpServletRequestHeaderTranslator", "httpServletRequestHeaderTranslator", ",", "QueryStringToMap", "queryStringToMap", ",", "MimeTypeTranslator", "mimeTypeTranslator", ",", "Map", "<", "String", ",", "CookieConfig", ">", "cookieConfigs", ")", "{", "this", ".", "httpServletCookieTranslator", "=", "httpServletCookieTranslator", ";", "this", ".", "httpServletRequestHeaderTranslator", "=", "httpServletRequestHeaderTranslator", ";", "this", ".", "queryStringToMap", "=", "queryStringToMap", ";", "this", ".", "mimeTypeTranslator", "=", "mimeTypeTranslator", ";", "this", ".", "cookieConfigs", "=", "cookieConfigs", ";", "}", "public", "Ask", "from", "(", "HttpServletRequest", "containerRequest", ",", "byte", "[", "]", "containerBody", ")", "throws", "IOException", "{", "Method", "method", "=", "Method", ".", "valueOf", "(", "containerRequest", ".", "getMethod", "(", ")", ")", ";", "String", "pathWithParams", "=", "containerRequest", ".", "getRequestURI", "(", ")", "+", "queryStringForUrl", "(", "containerRequest", ".", "getQueryString", "(", ")", ")", ";", "Map", "<", "String", ",", "Cookie", ">", "otterCookies", "=", "from", "(", "containerRequest", ".", "getCookies", "(", ")", ")", ";", "Map", "<", "String", ",", "String", ">", "headers", "=", "httpServletRequestHeaderTranslator", ".", "from", "(", "containerRequest", ")", ";", "Optional", "<", "String", ">", "queryString", "=", "Optional", ".", "ofNullable", "(", "containerRequest", ".", "getQueryString", "(", ")", ")", ";", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "queryParams", "=", "queryStringToMap", ".", "run", "(", "queryString", ")", ";", "MimeType", "contentType", "=", "mimeTypeTranslator", ".", "to", "(", "containerRequest", ".", "getContentType", "(", ")", ")", ";", "String", "acceptFrom", "=", "containerRequest", ".", "getHeader", "(", "Header", ".", "ACCEPT", ".", "getValue", "(", ")", ")", ";", "MimeType", "acceptTo", "=", "mimeTypeTranslator", ".", "to", "(", "acceptFrom", ")", ";", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "formData", "=", "new", "HashMap", "<", ">", "(", ")", ";", "Optional", "<", "byte", "[", "]", ">", "body", "=", "Optional", ".", "empty", "(", ")", ";", "if", "(", "isForm", "(", "method", ",", "contentType", ")", ")", "{", "String", "form", "=", "new", "String", "(", "containerBody", ")", ";", "formData", "=", "queryStringToMap", ".", "run", "(", "Optional", ".", "of", "(", "form", ")", ")", ";", "}", "else", "if", "(", "method", "==", "Method", ".", "POST", "||", "method", "==", "Method", ".", "PUT", "||", "method", "==", "Method", ".", "PATCH", "&&", "!", "isForm", "(", "method", ",", "contentType", ")", ")", "{", "body", "=", "Optional", ".", "of", "(", "containerBody", ")", ";", "}", "String", "ipAddress", "=", "containerRequest", ".", "getRemoteAddr", "(", ")", ";", "return", "new", "AskBuilder", "(", ")", ".", "matcher", "(", "Optional", ".", "empty", "(", ")", ")", ".", "method", "(", "method", ")", ".", "scheme", "(", "containerRequest", ".", "getScheme", "(", ")", ")", ".", "authority", "(", "containerRequest", ".", "getServerName", "(", ")", ")", ".", "port", "(", "containerRequest", ".", "getServerPort", "(", ")", ")", ".", "pathWithParams", "(", "pathWithParams", ")", ".", "contentType", "(", "contentType", ")", ".", "accept", "(", "acceptTo", ")", ".", "cookies", "(", "otterCookies", ")", ".", "headers", "(", "headers", ")", ".", "queryParams", "(", "queryParams", ")", ".", "formData", "(", "formData", ")", ".", "body", "(", "body", ")", ".", "csrfChallenge", "(", "Optional", ".", "empty", "(", ")", ")", ".", "ipAddress", "(", "ipAddress", ")", ".", "build", "(", ")", ";", "}", "protected", "Map", "<", "String", ",", "Cookie", ">", "from", "(", "javax", ".", "servlet", ".", "http", ".", "Cookie", "[", "]", "containerCookies", ")", "{", "Map", "<", "String", ",", "Cookie", ">", "otterCookies", "=", "new", "HashMap", "<", ">", "(", ")", ";", "if", "(", "Objects", ".", "nonNull", "(", "containerCookies", ")", ")", "{", "for", "(", "javax", ".", "servlet", ".", "http", ".", "Cookie", "cookie", ":", "containerCookies", ")", "{", "Cookie", "candidate", "=", "httpServletCookieTranslator", ".", "from", "(", "cookie", ")", ";", "Cookie", "existing", "=", "otterCookies", ".", "get", "(", "candidate", ".", "getName", "(", ")", ")", ";", "if", "(", "Objects", ".", "nonNull", "(", "existing", ")", "&&", "existing", ".", "equals", "(", "candidate", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"", "Found a duplicate cookie, {}, ignoring it.", "\"", ",", "existing", ".", "getName", "(", ")", ")", ";", "}", "else", "{", "CookieConfig", "expectedConfig", "=", "cookieConfigs", ".", "get", "(", "candidate", ".", "getName", "(", ")", ")", ";", "if", "(", "Objects", ".", "nonNull", "(", "expectedConfig", ")", ")", "{", "if", "(", "!", "expectedConfig", ".", "getHttpOnly", "(", ")", ".", "equals", "(", "candidate", ".", "isHttpOnly", "(", ")", ")", ")", "{", "LOGGER", ".", "debug", "(", "\"", "httpOnly is being overriden for cookie, {}. expected {}, actual {}", "\"", ",", "candidate", ".", "getName", "(", ")", ",", "expectedConfig", ".", "getHttpOnly", "(", ")", ",", "candidate", ".", "isHttpOnly", "(", ")", ")", ";", "candidate", ".", "setHttpOnly", "(", "expectedConfig", ".", "getHttpOnly", "(", ")", ")", ";", "}", "}", "otterCookies", ".", "put", "(", "candidate", ".", "getName", "(", ")", ",", "candidate", ")", ";", "}", "}", "}", "return", "otterCookies", ";", "}", "protected", "Boolean", "isForm", "(", "Method", "method", ",", "MimeType", "contentType", ")", "{", "return", "method", "==", "Method", ".", "POST", "&&", "TopLevelType", ".", "APPLICATION", ".", "toString", "(", ")", ".", "equals", "(", "contentType", ".", "getType", "(", ")", ")", "&&", "SubType", ".", "FORM", ".", "toString", "(", ")", ".", "equals", "(", "contentType", ".", "getSubType", "(", ")", ")", ";", "}", "protected", "String", "queryStringForUrl", "(", "String", "queryString", ")", "{", "String", "queryStringForUrl", ";", "if", "(", "Objects", ".", "nonNull", "(", "queryString", ")", ")", "{", "queryStringForUrl", "=", "PARAM_DELIMITER", "+", "queryString", ";", "}", "else", "{", "queryStringForUrl", "=", "EMPTY", ";", "}", "return", "queryStringForUrl", ";", "}", "}" ]
Translator for a HttpServletRequest to a Otter Request
[ "Translator", "for", "a", "HttpServletRequest", "to", "a", "Otter", "Request" ]
[ "// used to ensure http only is set on incoming cookies", "// throw away duplicate cookies.. idk why duplicates occur.", "// ensure http only is set - some ajax wont pass this is.. idk why", "// force it to the default then." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
1707ddbde8888582ab611792924b46fa04e0ad92
tt-gf/ant-ivy
src/java/org/apache/ivy/ant/IvyCacheFileset.java
[ "Apache-2.0" ]
Java
IvyCacheFileset
/** * Creates an ant fileset consisting in all artifacts found during a resolve. Note that this task * is not compatible with the useOrigin mode. */
Creates an ant fileset consisting in all artifacts found during a resolve. Note that this task is not compatible with the useOrigin mode.
[ "Creates", "an", "ant", "fileset", "consisting", "in", "all", "artifacts", "found", "during", "a", "resolve", ".", "Note", "that", "this", "task", "is", "not", "compatible", "with", "the", "useOrigin", "mode", "." ]
public class IvyCacheFileset extends IvyCacheTask { private String setid; public String getSetid() { return setid; } public void setSetid(String id) { setid = id; } public void setUseOrigin(boolean useOrigin) { if (useOrigin) { throw new UnsupportedOperationException( "the cachefileset task does not support the useOrigin mode, since filesets " + "require to have only one root directory. Please use the the " + "cachepath task instead"); } } public void doExecute() throws BuildException { prepareAndCheck(); if (setid == null) { throw new BuildException("setid is required in ivy cachefileset"); } try { final List<ArtifactDownloadReport> artifactDownloadReports = getArtifactReports(); if (artifactDownloadReports.isEmpty()) { // generate an empty fileset final FileSet emptyFileSet = new EmptyFileSet(); emptyFileSet.setProject(getProject()); getProject().addReference(setid, emptyFileSet); return; } // find a common base dir of the resolved artifacts final File baseDir = this.requireCommonBaseDir(artifactDownloadReports); final FileSet fileset = new FileSet(); fileset.setDir(baseDir); fileset.setProject(getProject()); // enroll each of the artifact files into the fileset for (final ArtifactDownloadReport artifactDownloadReport : artifactDownloadReports) { if (artifactDownloadReport.getLocalFile() == null) { continue; } final NameEntry ne = fileset.createInclude(); ne.setName(getPath(baseDir, artifactDownloadReport.getLocalFile())); } getProject().addReference(setid, fileset); } catch (Exception ex) { throw new BuildException("impossible to build ivy cache fileset: " + ex, ex); } } /** * Returns a common base directory, determined from the * {@link ArtifactDownloadReport#getLocalFile() local files} of the passed * <code>artifactDownloadReports</code>. If no common base directory can be determined, this * method throws a {@link BuildException} * * @param artifactDownloadReports The artifact download reports for which the common base * directory of the artifacts has to be determined * @return File */ File requireCommonBaseDir(final List<ArtifactDownloadReport> artifactDownloadReports) { File base = null; for (final ArtifactDownloadReport artifactDownloadReport : artifactDownloadReports) { if (artifactDownloadReport.getLocalFile() == null) { continue; } if (base == null) { // use the parent dir of the artifact as the base base = artifactDownloadReport.getLocalFile().getParentFile().getAbsoluteFile(); } else { // try and find a common base directory between the current base // directory and the artifact's file base = getBaseDir(base, artifactDownloadReport.getLocalFile()); if (base == null) { // fail fast - we couldn't determine a common base directory, throw an error throw new BuildException("Cannot find a common base directory, from resolved " + "artifacts, for generating a cache fileset"); } } } if (base == null) { // finally, we couldn't determine a common base directory, throw an error throw new BuildException("Cannot find a common base directory, from resolved " + "artifacts, for generating a cache fileset"); } return base; } /** * Returns the path of the file relative to the given base directory. * * @param base * the parent directory to which the file must be evaluated. * @param file * the file for which the path should be returned * @return the path of the file relative to the given base directory. */ private String getPath(File base, File file) { String absoluteBasePath = base.getAbsolutePath(); int beginIndex = absoluteBasePath.length(); // checks if the basePath ends with the file separator (which can for instance // happen if the basePath is the root on unix) if (!absoluteBasePath.endsWith(File.separator)) { beginIndex++; // skip the separator char as well } return file.getAbsolutePath().substring(beginIndex); } /** * Returns the common base directory between the passed <code>file1</code> and * <code>file2</code>. * <p> * The returned base directory will be a parent of both the <code>file1</code> and * <code>file2</code> or it will be <code>null</code>. * </p> * * @param file1 * One of the files, for which the common base directory is being sought, may be null. * @param file2 * The other file for which the common base directory should be returned, may be null. * @return the common base directory between a <code>file1</code> and <code>file2</code>. Returns * null if no common base directory could be determined or if either <code>file1</code> * or <code>file2</code> is null */ File getBaseDir(final File file1, final File file2) { if (file1 == null || file2 == null) { return null; } final Iterator<File> file1Parents = getParents(file1).iterator(); final Iterator<File> file2Parents = getParents(file2.getAbsoluteFile()).iterator(); File result = null; while (file1Parents.hasNext() && file2Parents.hasNext()) { File next = file1Parents.next(); if (next.equals(file2Parents.next())) { result = next; } else { break; } } return result; } /** * @return a list of files, starting with the root and ending with the file itself */ private LinkedList<File> getParents(File file) { LinkedList<File> r = new LinkedList<>(); while (file != null) { r.addFirst(file); file = file.getParentFile(); } return r; } private static class EmptyFileSet extends FileSet { private DirectoryScanner ds = new EmptyDirectoryScanner(); public Iterator<Resource> iterator() { return new EmptyIterator<>(); } public Object clone() { return new EmptyFileSet(); } public int size() { return 0; } public DirectoryScanner getDirectoryScanner(Project project) { return ds; } } private static class EmptyIterator<T> implements Iterator<T> { public boolean hasNext() { return false; } public T next() { throw new NoSuchElementException("EmptyFileSet Iterator"); } public void remove() { throw new IllegalStateException("EmptyFileSet Iterator"); } } private static class EmptyDirectoryScanner extends DirectoryScanner { public String[] getIncludedFiles() { return new String[0]; } } }
[ "public", "class", "IvyCacheFileset", "extends", "IvyCacheTask", "{", "private", "String", "setid", ";", "public", "String", "getSetid", "(", ")", "{", "return", "setid", ";", "}", "public", "void", "setSetid", "(", "String", "id", ")", "{", "setid", "=", "id", ";", "}", "public", "void", "setUseOrigin", "(", "boolean", "useOrigin", ")", "{", "if", "(", "useOrigin", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"", "the cachefileset task does not support the useOrigin mode, since filesets ", "\"", "+", "\"", "require to have only one root directory. Please use the the ", "\"", "+", "\"", "cachepath task instead", "\"", ")", ";", "}", "}", "public", "void", "doExecute", "(", ")", "throws", "BuildException", "{", "prepareAndCheck", "(", ")", ";", "if", "(", "setid", "==", "null", ")", "{", "throw", "new", "BuildException", "(", "\"", "setid is required in ivy cachefileset", "\"", ")", ";", "}", "try", "{", "final", "List", "<", "ArtifactDownloadReport", ">", "artifactDownloadReports", "=", "getArtifactReports", "(", ")", ";", "if", "(", "artifactDownloadReports", ".", "isEmpty", "(", ")", ")", "{", "final", "FileSet", "emptyFileSet", "=", "new", "EmptyFileSet", "(", ")", ";", "emptyFileSet", ".", "setProject", "(", "getProject", "(", ")", ")", ";", "getProject", "(", ")", ".", "addReference", "(", "setid", ",", "emptyFileSet", ")", ";", "return", ";", "}", "final", "File", "baseDir", "=", "this", ".", "requireCommonBaseDir", "(", "artifactDownloadReports", ")", ";", "final", "FileSet", "fileset", "=", "new", "FileSet", "(", ")", ";", "fileset", ".", "setDir", "(", "baseDir", ")", ";", "fileset", ".", "setProject", "(", "getProject", "(", ")", ")", ";", "for", "(", "final", "ArtifactDownloadReport", "artifactDownloadReport", ":", "artifactDownloadReports", ")", "{", "if", "(", "artifactDownloadReport", ".", "getLocalFile", "(", ")", "==", "null", ")", "{", "continue", ";", "}", "final", "NameEntry", "ne", "=", "fileset", ".", "createInclude", "(", ")", ";", "ne", ".", "setName", "(", "getPath", "(", "baseDir", ",", "artifactDownloadReport", ".", "getLocalFile", "(", ")", ")", ")", ";", "}", "getProject", "(", ")", ".", "addReference", "(", "setid", ",", "fileset", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "BuildException", "(", "\"", "impossible to build ivy cache fileset: ", "\"", "+", "ex", ",", "ex", ")", ";", "}", "}", "/**\n * Returns a common base directory, determined from the\n * {@link ArtifactDownloadReport#getLocalFile() local files} of the passed\n * <code>artifactDownloadReports</code>. If no common base directory can be determined, this\n * method throws a {@link BuildException}\n *\n * @param artifactDownloadReports The artifact download reports for which the common base\n * directory of the artifacts has to be determined\n * @return File\n */", "File", "requireCommonBaseDir", "(", "final", "List", "<", "ArtifactDownloadReport", ">", "artifactDownloadReports", ")", "{", "File", "base", "=", "null", ";", "for", "(", "final", "ArtifactDownloadReport", "artifactDownloadReport", ":", "artifactDownloadReports", ")", "{", "if", "(", "artifactDownloadReport", ".", "getLocalFile", "(", ")", "==", "null", ")", "{", "continue", ";", "}", "if", "(", "base", "==", "null", ")", "{", "base", "=", "artifactDownloadReport", ".", "getLocalFile", "(", ")", ".", "getParentFile", "(", ")", ".", "getAbsoluteFile", "(", ")", ";", "}", "else", "{", "base", "=", "getBaseDir", "(", "base", ",", "artifactDownloadReport", ".", "getLocalFile", "(", ")", ")", ";", "if", "(", "base", "==", "null", ")", "{", "throw", "new", "BuildException", "(", "\"", "Cannot find a common base directory, from resolved ", "\"", "+", "\"", "artifacts, for generating a cache fileset", "\"", ")", ";", "}", "}", "}", "if", "(", "base", "==", "null", ")", "{", "throw", "new", "BuildException", "(", "\"", "Cannot find a common base directory, from resolved ", "\"", "+", "\"", "artifacts, for generating a cache fileset", "\"", ")", ";", "}", "return", "base", ";", "}", "/**\n * Returns the path of the file relative to the given base directory.\n *\n * @param base\n * the parent directory to which the file must be evaluated.\n * @param file\n * the file for which the path should be returned\n * @return the path of the file relative to the given base directory.\n */", "private", "String", "getPath", "(", "File", "base", ",", "File", "file", ")", "{", "String", "absoluteBasePath", "=", "base", ".", "getAbsolutePath", "(", ")", ";", "int", "beginIndex", "=", "absoluteBasePath", ".", "length", "(", ")", ";", "if", "(", "!", "absoluteBasePath", ".", "endsWith", "(", "File", ".", "separator", ")", ")", "{", "beginIndex", "++", ";", "}", "return", "file", ".", "getAbsolutePath", "(", ")", ".", "substring", "(", "beginIndex", ")", ";", "}", "/**\n * Returns the common base directory between the passed <code>file1</code> and\n * <code>file2</code>.\n * <p>\n * The returned base directory will be a parent of both the <code>file1</code> and\n * <code>file2</code> or it will be <code>null</code>.\n * </p>\n *\n * @param file1\n * One of the files, for which the common base directory is being sought, may be null.\n * @param file2\n * The other file for which the common base directory should be returned, may be null.\n * @return the common base directory between a <code>file1</code> and <code>file2</code>. Returns\n * null if no common base directory could be determined or if either <code>file1</code>\n * or <code>file2</code> is null\n */", "File", "getBaseDir", "(", "final", "File", "file1", ",", "final", "File", "file2", ")", "{", "if", "(", "file1", "==", "null", "||", "file2", "==", "null", ")", "{", "return", "null", ";", "}", "final", "Iterator", "<", "File", ">", "file1Parents", "=", "getParents", "(", "file1", ")", ".", "iterator", "(", ")", ";", "final", "Iterator", "<", "File", ">", "file2Parents", "=", "getParents", "(", "file2", ".", "getAbsoluteFile", "(", ")", ")", ".", "iterator", "(", ")", ";", "File", "result", "=", "null", ";", "while", "(", "file1Parents", ".", "hasNext", "(", ")", "&&", "file2Parents", ".", "hasNext", "(", ")", ")", "{", "File", "next", "=", "file1Parents", ".", "next", "(", ")", ";", "if", "(", "next", ".", "equals", "(", "file2Parents", ".", "next", "(", ")", ")", ")", "{", "result", "=", "next", ";", "}", "else", "{", "break", ";", "}", "}", "return", "result", ";", "}", "/**\n * @return a list of files, starting with the root and ending with the file itself\n */", "private", "LinkedList", "<", "File", ">", "getParents", "(", "File", "file", ")", "{", "LinkedList", "<", "File", ">", "r", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "while", "(", "file", "!=", "null", ")", "{", "r", ".", "addFirst", "(", "file", ")", ";", "file", "=", "file", ".", "getParentFile", "(", ")", ";", "}", "return", "r", ";", "}", "private", "static", "class", "EmptyFileSet", "extends", "FileSet", "{", "private", "DirectoryScanner", "ds", "=", "new", "EmptyDirectoryScanner", "(", ")", ";", "public", "Iterator", "<", "Resource", ">", "iterator", "(", ")", "{", "return", "new", "EmptyIterator", "<", ">", "(", ")", ";", "}", "public", "Object", "clone", "(", ")", "{", "return", "new", "EmptyFileSet", "(", ")", ";", "}", "public", "int", "size", "(", ")", "{", "return", "0", ";", "}", "public", "DirectoryScanner", "getDirectoryScanner", "(", "Project", "project", ")", "{", "return", "ds", ";", "}", "}", "private", "static", "class", "EmptyIterator", "<", "T", ">", "implements", "Iterator", "<", "T", ">", "{", "public", "boolean", "hasNext", "(", ")", "{", "return", "false", ";", "}", "public", "T", "next", "(", ")", "{", "throw", "new", "NoSuchElementException", "(", "\"", "EmptyFileSet Iterator", "\"", ")", ";", "}", "public", "void", "remove", "(", ")", "{", "throw", "new", "IllegalStateException", "(", "\"", "EmptyFileSet Iterator", "\"", ")", ";", "}", "}", "private", "static", "class", "EmptyDirectoryScanner", "extends", "DirectoryScanner", "{", "public", "String", "[", "]", "getIncludedFiles", "(", ")", "{", "return", "new", "String", "[", "0", "]", ";", "}", "}", "}" ]
Creates an ant fileset consisting in all artifacts found during a resolve.
[ "Creates", "an", "ant", "fileset", "consisting", "in", "all", "artifacts", "found", "during", "a", "resolve", "." ]
[ "// generate an empty fileset", "// find a common base dir of the resolved artifacts", "// enroll each of the artifact files into the fileset", "// use the parent dir of the artifact as the base", "// try and find a common base directory between the current base", "// directory and the artifact's file", "// fail fast - we couldn't determine a common base directory, throw an error", "// finally, we couldn't determine a common base directory, throw an error", "// checks if the basePath ends with the file separator (which can for instance", "// happen if the basePath is the root on unix)", "// skip the separator char as well" ]
[ { "param": "IvyCacheTask", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IvyCacheTask", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
170b0a38c1d882ce06f197820160c6193fd9fbb6
musicglue/cmb
src/com/comcast/cmb/common/util/RollingWindowCapture.java
[ "Apache-2.0" ]
Java
RollingWindowCapture
/** * A utility class used to capture objects in a rolling window fashion * Note: This class should not be used if there are a lot of adding of events * instead callers should get the latest node and modify that in most cases * * @author aseem * Class is thread-safe */
A utility class used to capture objects in a rolling window fashion Note: This class should not be used if there are a lot of adding of events instead callers should get the latest node and modify that in most cases @author aseem Class is thread-safe
[ "A", "utility", "class", "used", "to", "capture", "objects", "in", "a", "rolling", "window", "fashion", "Note", ":", "This", "class", "should", "not", "be", "used", "if", "there", "are", "a", "lot", "of", "adding", "of", "events", "instead", "callers", "should", "get", "the", "latest", "node", "and", "modify", "that", "in", "most", "cases", "@author", "aseem", "Class", "is", "thread", "-", "safe" ]
public final class RollingWindowCapture<T extends RollingWindowCapture.PayLoad> { private static Logger logger = Logger.getLogger(RollingWindowCapture.class); private final long _windowSizeSec; private final int _tolerance; private final AtomicInteger _toleranceCount; private class PayLoadNode { public final T _payLoad; private final long _captureTime; public PayLoadNode(T payload, long captureTime) { _payLoad = payload; _captureTime = captureTime; } } //internally we used a CopyOnWriteArrayList to implement the rolling window in chronological order. //First node is the oldest node //We use CopyOnWriteArrayList since its the only standard data-structure provided that offers concurrent //access to its elements and provides the List interface, specifically get(index) method. We need this //method to return the tail of the rollingwindow. private CopyOnWriteArrayList<PayLoadNode> _queue = new CopyOnWriteArrayList<PayLoadNode>(); public static interface Visitor<T> { public void processNode(T n); } /** * The payl0ad to capture in window * */ public static abstract class PayLoad {} /** * * @param windowSizeSec the size of rolling window in seconds * @param tolerance the number of adds you can go over before must reduce the window */ public RollingWindowCapture(int windowSizeSec, int tolerance) { _windowSizeSec = windowSizeSec; _tolerance = tolerance; _toleranceCount = new AtomicInteger(); } /** * Method would traverse the entire list of elements in the window and call * the visitor on each node * @param v the Visitor impl */ public void visitAllNodes(Visitor<T> v) { cleanupWindow(); Iterator<PayLoadNode> it = _queue.iterator(); while (it.hasNext()) { PayLoadNode node = it.next(); v.processNode(node._payLoad); } } /** * Add current time to the header of list * Note: This is an expensive operation O(n) complexity where n is the number of elements in the list */ public void addNow(T payLoad) { PayLoadNode node = new PayLoadNode(payLoad, System.currentTimeMillis()); _queue.add(node); if (_toleranceCount.incrementAndGet() >= _tolerance) { cleanupWindow(); } } /** * @return The last added payload or null if no element */ public T getLatestPayload() { boolean success = false; while (!success) { if (_queue.size() == 0) return null; try { PayLoadNode head = _queue.get(_queue.size() - 1); success = true; return head._payLoad; } catch (IndexOutOfBoundsException e) {} } return null; } /** * Go through the beginning of the queue and remove all expired nodes */ private void cleanupWindow() { long now = System.currentTimeMillis(); Iterator<PayLoadNode> it = _queue.iterator(); while (it.hasNext()) { PayLoadNode node = it.next(); if (node._captureTime + (_windowSizeSec*1000) < now) { if (!_queue.remove(node)) { logger.debug("event=cleanup_window status=queue_did_not_change info=node_may_have_been_deleted"); } } else { //found the first node in the capture window. we are done _toleranceCount.set(0); return; } } _toleranceCount.set(0); } }
[ "public", "final", "class", "RollingWindowCapture", "<", "T", "extends", "RollingWindowCapture", ".", "PayLoad", ">", "{", "private", "static", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "RollingWindowCapture", ".", "class", ")", ";", "private", "final", "long", "_windowSizeSec", ";", "private", "final", "int", "_tolerance", ";", "private", "final", "AtomicInteger", "_toleranceCount", ";", "private", "class", "PayLoadNode", "{", "public", "final", "T", "_payLoad", ";", "private", "final", "long", "_captureTime", ";", "public", "PayLoadNode", "(", "T", "payload", ",", "long", "captureTime", ")", "{", "_payLoad", "=", "payload", ";", "_captureTime", "=", "captureTime", ";", "}", "}", "private", "CopyOnWriteArrayList", "<", "PayLoadNode", ">", "_queue", "=", "new", "CopyOnWriteArrayList", "<", "PayLoadNode", ">", "(", ")", ";", "public", "static", "interface", "Visitor", "<", "T", ">", "{", "public", "void", "processNode", "(", "T", "n", ")", ";", "}", "/**\r\n * The payl0ad to capture in window\r\n *\r\n */", "public", "static", "abstract", "class", "PayLoad", "{", "}", "/**\r\n * \r\n * @param windowSizeSec the size of rolling window in seconds\r\n * @param tolerance the number of adds you can go over before must reduce the window\r\n */", "public", "RollingWindowCapture", "(", "int", "windowSizeSec", ",", "int", "tolerance", ")", "{", "_windowSizeSec", "=", "windowSizeSec", ";", "_tolerance", "=", "tolerance", ";", "_toleranceCount", "=", "new", "AtomicInteger", "(", ")", ";", "}", "/**\r\n * Method would traverse the entire list of elements in the window and call\r\n * the visitor on each node\r\n * @param v the Visitor impl\r\n */", "public", "void", "visitAllNodes", "(", "Visitor", "<", "T", ">", "v", ")", "{", "cleanupWindow", "(", ")", ";", "Iterator", "<", "PayLoadNode", ">", "it", "=", "_queue", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "PayLoadNode", "node", "=", "it", ".", "next", "(", ")", ";", "v", ".", "processNode", "(", "node", ".", "_payLoad", ")", ";", "}", "}", "/**\r\n * Add current time to the header of list\r\n * Note: This is an expensive operation O(n) complexity where n is the number of elements in the list\r\n */", "public", "void", "addNow", "(", "T", "payLoad", ")", "{", "PayLoadNode", "node", "=", "new", "PayLoadNode", "(", "payLoad", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "_queue", ".", "add", "(", "node", ")", ";", "if", "(", "_toleranceCount", ".", "incrementAndGet", "(", ")", ">=", "_tolerance", ")", "{", "cleanupWindow", "(", ")", ";", "}", "}", "/**\r\n * @return The last added payload or null if no element\r\n */", "public", "T", "getLatestPayload", "(", ")", "{", "boolean", "success", "=", "false", ";", "while", "(", "!", "success", ")", "{", "if", "(", "_queue", ".", "size", "(", ")", "==", "0", ")", "return", "null", ";", "try", "{", "PayLoadNode", "head", "=", "_queue", ".", "get", "(", "_queue", ".", "size", "(", ")", "-", "1", ")", ";", "success", "=", "true", ";", "return", "head", ".", "_payLoad", ";", "}", "catch", "(", "IndexOutOfBoundsException", "e", ")", "{", "}", "}", "return", "null", ";", "}", "/**\r\n * Go through the beginning of the queue and remove all expired nodes\r\n */", "private", "void", "cleanupWindow", "(", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "Iterator", "<", "PayLoadNode", ">", "it", "=", "_queue", ".", "iterator", "(", ")", ";", "while", "(", "it", ".", "hasNext", "(", ")", ")", "{", "PayLoadNode", "node", "=", "it", ".", "next", "(", ")", ";", "if", "(", "node", ".", "_captureTime", "+", "(", "_windowSizeSec", "*", "1000", ")", "<", "now", ")", "{", "if", "(", "!", "_queue", ".", "remove", "(", "node", ")", ")", "{", "logger", ".", "debug", "(", "\"", "event=cleanup_window status=queue_did_not_change info=node_may_have_been_deleted", "\"", ")", ";", "}", "}", "else", "{", "_toleranceCount", ".", "set", "(", "0", ")", ";", "return", ";", "}", "}", "_toleranceCount", ".", "set", "(", "0", ")", ";", "}", "}" ]
A utility class used to capture objects in a rolling window fashion Note: This class should not be used if there are a lot of adding of events instead callers should get the latest node and modify that in most cases
[ "A", "utility", "class", "used", "to", "capture", "objects", "in", "a", "rolling", "window", "fashion", "Note", ":", "This", "class", "should", "not", "be", "used", "if", "there", "are", "a", "lot", "of", "adding", "of", "events", "instead", "callers", "should", "get", "the", "latest", "node", "and", "modify", "that", "in", "most", "cases" ]
[ "//internally we used a CopyOnWriteArrayList to implement the rolling window in chronological order. \r", "//First node is the oldest node\r", "//We use CopyOnWriteArrayList since its the only standard data-structure provided that offers concurrent\r", "//access to its elements and provides the List interface, specifically get(index) method. We need this\r", "//method to return the tail of the rollingwindow.\r", "//found the first node in the capture window. we are done\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
171764ff567cb6df8a4808a217aa12a3ac103414
ModelWriter/AlloyInEcore
Source/eu.modelwriter.core.alloyinecore/src/main/java/eu/modelwriter/core/alloyinecore/interpreter/typesystem/UnaryBoundsCreator.java
[ "MIT" ]
Java
UnaryBoundsCreator
/** * Created by harun on 2/2/18. */
Created by harun on 2/2/18.
[ "Created", "by", "harun", "on", "2", "/", "2", "/", "18", "." ]
public class UnaryBoundsCreator { private TypeSystem typeSystem; private BoundCollector boundCollector; private Set<Atom> atomsToIgnore; private Set<Atom> originalAtoms; private Map<Type, Boolean> visited; private UnaryBoundsCreator(BoundCollector boundCollector) { this.typeSystem = boundCollector.getTypeSystem(); this.boundCollector = boundCollector; atomsToIgnore = new HashSet<>(); originalAtoms = boundCollector.getUnaryLowerBounds().values().stream() .flatMap(Collection::stream) .filter(a -> a.getType().equals(Atom.AtomType.OBJECT)) .collect(Collectors.toSet()); visited = new HashMap<>(); } public static void create(BoundCollector boundCollector) { UnaryBoundsCreator ubc = new UnaryBoundsCreator(boundCollector); ubc.typeSystem.getRootTypes().stream().filter(t -> t instanceof BasicType || t instanceof GenericTypeTemplate).forEach(ubc::createObjectAtoms); ubc.typeSystem.getAllTypes().stream().filter(t -> t.getSuperTypes().size() > 1).forEach(type -> { type.getAllSuperTypes().forEach(e -> boundCollector.getUnaryUpperBounds() .computeIfAbsent(e, t -> new HashSet<>()) .addAll(boundCollector.getUnaryUpperBounds().get(type))); }); /*ubc.boundCollector.getUnaryLowerBounds().put(ubc.typeSystem.OBJECT, ubc.typeSystem.getRootTypes().stream() .filter(t -> !(t instanceof PrimitiveType) || !((PrimitiveType) t).getAtomType().equals(Atom.AtomType.CLASS)) .map(t -> ubc.boundCollector.getUnaryLowerBounds().getOrDefault(t, Collections.emptySet())) .flatMap(Collection::stream) .collect(Collectors.toSet())); ubc.boundCollector.getUnaryUpperBounds().put(ubc.typeSystem.OBJECT, ubc.typeSystem.getRootTypes().stream() .filter(t -> !(t instanceof PrimitiveType) || !((PrimitiveType) t).getAtomType().equals(Atom.AtomType.CLASS)) .map(t -> ubc.boundCollector.getUnaryUpperBounds().getOrDefault(t, Collections.emptySet())) .flatMap(Collection::stream) .collect(Collectors.toSet()));*/ ubc.createPrimitiveTypeAtoms(); } private void createPrimitiveTypeAtoms() { // Create and add integers if gt, gte, lt, lte used. int integerPerGap = boundCollector.getIntegersPerGap(); if (integerPerGap > 0) { PrimitiveType pt = typeSystem.getPrimitiveType("EInt"); List<Integer> integerList = boundCollector.getUnaryLowerBounds() .getOrDefault(pt, Collections.emptySet()).stream() .map(e -> Integer.parseInt(e.getName())) .sorted() .collect(Collectors.toList()); List<Integer> newIntegers = new ArrayList<>(); for (int i = 0; i < integerList.size(); i++) { if (i == 0) { int number = integerList.get(i); for (int j = 0; j < integerPerGap; j++) { newIntegers.add(number - j - 1); } } else if (i == integerList.size() - 1) { int number = integerList.get(i); for (int j = 0; j < integerPerGap; j++) { newIntegers.add(number + j + 1); } } else { int downLimit = integerList.get(i); int upLimit = integerList.get(i + 1); int ipg = Math.min(upLimit - downLimit - 1, integerPerGap); for (int j = 0; j < ipg; j++) { newIntegers.add(downLimit + j + 1); } } } boundCollector.getUnaryUpperBounds().computeIfAbsent(pt, p -> new HashSet<>()).addAll( boundCollector.getUnaryLowerBounds() .getOrDefault(pt, Collections.emptySet()) ); boundCollector.getUnaryUpperBounds().computeIfAbsent(pt, p -> new HashSet<>()).addAll( newIntegers.stream() .map(i -> new Atom(i + "", Atom.AtomType.INTEGER)) .collect(Collectors.toSet()) ); } // Get upper scope informations Map<PrimitiveType, Integer> primitiveUpperScopes = new HashMap<>(); typeSystem.getAllPrimitiveTypes().forEach(primitiveType -> { typeSystem.getAllBasicReferences().stream() .filter(ref -> ref.getReferencedType().equals(primitiveType)).forEach(ref -> { Type ownerType = ref.getOwnerType(); primitiveUpperScopes.put( primitiveType, primitiveUpperScopes.computeIfAbsent(primitiveType, p -> 0) + boundCollector.getUpperScope(ownerType)); }); }); primitiveUpperScopes.forEach(((primitiveType, upperScope) -> { Set<Atom> atoms = new HashSet<>(); atoms.addAll(boundCollector.getUnaryLowerBounds().getOrDefault(primitiveType, Collections.emptySet())); int count = upperScope - atoms.size(); if (count <= 0) return; switch (primitiveType.getAtomType()) { case STRING: for (int i = 0; i < count; i++) { String name = "String_" + i; if (atoms.stream().anyMatch(a -> a.getName().equals(name))) count++; else atoms.add(new Atom(name, Atom.AtomType.STRING)); } break; case INTEGER: for (int i = 0; i < count; i++) { String name = "" + new Random().nextInt() % 10000; if (atoms.stream().anyMatch(a -> a.getName().equals(name))) count++; else atoms.add(new Atom(name, Atom.AtomType.INTEGER)); } break; case BIG_INTEGER: for (int i = 0; i < count; i++) { String name = "" + new Random().nextInt() % 10000; if (atoms.stream().anyMatch(a -> a.getName().equals(name))) count++; else atoms.add(new Atom(name, Atom.AtomType.BIG_INTEGER)); } break; case BIG_DECIMAL: for (int i = 0; i < count; i++) { String name = "" + new Random().nextFloat(); if (atoms.stream().anyMatch(a -> a.getName().equals(name))) count++; else atoms.add(new Atom(name, Atom.AtomType.BIG_DECIMAL)); } break; } boundCollector.getUnaryUpperBounds().computeIfAbsent(primitiveType, p -> new HashSet<>()).addAll(atoms); })); } private void createObjectAtoms(Type type) { if (visited.getOrDefault(type, false)) return; visited.put(type, true); type.getSubTypes().forEach(this::createObjectAtoms); boundCollector.getUnaryLowerBounds().computeIfAbsent(type, t -> new HashSet<>()) .addAll(type.getSubTypes().stream() .filter(t -> t.getSuperTypes().stream().filter(x -> (x instanceof GenericTypeTemplate || x instanceof BasicType)).count() <= 1) .flatMap(t -> boundCollector.getUnaryLowerBounds().getOrDefault(t, Collections.emptySet()).stream()) .collect(Collectors.toSet())); boundCollector.getUnaryUpperBounds().computeIfAbsent(type, t -> new HashSet<>()) .addAll(type.getSubTypes().stream() .filter(t -> t.getSuperTypes().stream().filter(x -> (x instanceof GenericTypeTemplate || x instanceof BasicType)).count() <= 1) .flatMap(t -> boundCollector.getUnaryUpperBounds().getOrDefault(t, Collections.emptySet()).stream()) .collect(Collectors.toSet())); if (type.getSubTypes().stream().noneMatch(t -> (t instanceof GenericTypeTemplate || t instanceof BasicType) && t.getSuperTypes().size() > 1)) { Set<Atom> temp = new HashSet<>(boundCollector.getUnaryLowerBounds().get(type)); temp.addAll(boundCollector.getUnaryUpperBounds().get(type)); if (temp.size() <= boundCollector.getLowerScope(type)) { boundCollector.getUnaryLowerBounds().put(type, temp); if (boundCollector.getUnaryLowerBounds().get(type).size() < boundCollector.getLowerScope(type)) { Set<Atom> newAtoms = createNewAtoms(type, boundCollector.getUnaryLowerBounds().get(type).size(), boundCollector.getLowerScope(type)); boundCollector.getUnaryLowerBounds().get(type).addAll(newAtoms); type.getSubTypes().forEach(t -> addToUpper(t, newAtoms)); } } } boundCollector.getUnaryUpperBounds().get(type).addAll(boundCollector.getUnaryLowerBounds().get(type)); Set<Atom> newAtoms = new HashSet<>(); if (boundCollector.getUnaryUpperBounds().get(type).size() < boundCollector.getUpperScope(type)) { newAtoms.addAll(createNewAtoms(type, boundCollector.getUnaryUpperBounds().get(type).size(), boundCollector.getUpperScope(type))); boundCollector.getUnaryUpperBounds().get(type).addAll(newAtoms); type.getSubTypes().forEach(t -> addToUpper(t, newAtoms)); } if (type instanceof GenericTypeTemplate) { type.getSubTypes().forEach(t -> addToUpperOfGenerics(t, boundCollector.getUnaryLowerBounds().get(type))); } // type.getSubTypes().forEach(t -> addToUpper(t, type, boundCollector.getUnaryUpperBounds().get(type))); atomsToIgnore.addAll(boundCollector.getUnaryLowerBounds().get(type)); } private void addToUpperOfGenerics(Type type, Set<Atom> atoms){ if (!(type instanceof GenericTypeAbstractImpl || type instanceof GenericTypeImpl)) return; if (boundCollector.hasScope(type)) return; Set<Atom> atomsClone = new HashSet<>(atoms); atomsClone.removeAll(atomsToIgnore); if (atomsClone.isEmpty()) return; boundCollector.getUnaryUpperBounds().computeIfAbsent(type, t -> new HashSet<>()).addAll(atomsClone); type.getSubTypes().forEach(subType -> addToUpperOfGenerics(subType, atomsClone)); } private void addToUpper(Type type, Set<Atom> atoms){ if (boundCollector.hasScope(type)) return; Set<Atom> atomsClone = new HashSet<>(atoms); atomsClone.removeAll(atomsToIgnore); if (type instanceof BasicType) atomsClone.removeAll(originalAtoms); if (atomsClone.isEmpty()) return; boundCollector.getUnaryUpperBounds().computeIfAbsent(type, t -> new HashSet<>()).addAll(atomsClone); type.getSubTypes().forEach(subType -> addToUpper(subType, atomsClone)); } private Set<Atom> createNewAtoms(Type type, int curSize, int wantedSize) { Set<Atom> newAtoms = new HashSet<>(); for (int i = curSize; i < wantedSize; i++) { Atom atom = new Atom(type.getName() + "_" + i, Atom.AtomType.OBJECT); atom.setObject(type.getElement()); newAtoms.add(atom); } return newAtoms; } }
[ "public", "class", "UnaryBoundsCreator", "{", "private", "TypeSystem", "typeSystem", ";", "private", "BoundCollector", "boundCollector", ";", "private", "Set", "<", "Atom", ">", "atomsToIgnore", ";", "private", "Set", "<", "Atom", ">", "originalAtoms", ";", "private", "Map", "<", "Type", ",", "Boolean", ">", "visited", ";", "private", "UnaryBoundsCreator", "(", "BoundCollector", "boundCollector", ")", "{", "this", ".", "typeSystem", "=", "boundCollector", ".", "getTypeSystem", "(", ")", ";", "this", ".", "boundCollector", "=", "boundCollector", ";", "atomsToIgnore", "=", "new", "HashSet", "<", ">", "(", ")", ";", "originalAtoms", "=", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "values", "(", ")", ".", "stream", "(", ")", ".", "flatMap", "(", "Collection", "::", "stream", ")", ".", "filter", "(", "a", "->", "a", ".", "getType", "(", ")", ".", "equals", "(", "Atom", ".", "AtomType", ".", "OBJECT", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "visited", "=", "new", "HashMap", "<", ">", "(", ")", ";", "}", "public", "static", "void", "create", "(", "BoundCollector", "boundCollector", ")", "{", "UnaryBoundsCreator", "ubc", "=", "new", "UnaryBoundsCreator", "(", "boundCollector", ")", ";", "ubc", ".", "typeSystem", ".", "getRootTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "t", "instanceof", "BasicType", "||", "t", "instanceof", "GenericTypeTemplate", ")", ".", "forEach", "(", "ubc", "::", "createObjectAtoms", ")", ";", "ubc", ".", "typeSystem", ".", "getAllTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "t", ".", "getSuperTypes", "(", ")", ".", "size", "(", ")", ">", "1", ")", ".", "forEach", "(", "type", "->", "{", "type", ".", "getAllSuperTypes", "(", ")", ".", "forEach", "(", "e", "->", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "e", ",", "t", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ")", ")", ";", "}", ")", ";", "/*ubc.boundCollector.getUnaryLowerBounds().put(ubc.typeSystem.OBJECT, ubc.typeSystem.getRootTypes().stream()\n .filter(t -> !(t instanceof PrimitiveType) || !((PrimitiveType) t).getAtomType().equals(Atom.AtomType.CLASS))\n .map(t -> ubc.boundCollector.getUnaryLowerBounds().getOrDefault(t, Collections.emptySet()))\n .flatMap(Collection::stream)\n .collect(Collectors.toSet()));\n ubc.boundCollector.getUnaryUpperBounds().put(ubc.typeSystem.OBJECT, ubc.typeSystem.getRootTypes().stream()\n .filter(t -> !(t instanceof PrimitiveType) || !((PrimitiveType) t).getAtomType().equals(Atom.AtomType.CLASS))\n .map(t -> ubc.boundCollector.getUnaryUpperBounds().getOrDefault(t, Collections.emptySet()))\n .flatMap(Collection::stream)\n .collect(Collectors.toSet()));*/", "ubc", ".", "createPrimitiveTypeAtoms", "(", ")", ";", "}", "private", "void", "createPrimitiveTypeAtoms", "(", ")", "{", "int", "integerPerGap", "=", "boundCollector", ".", "getIntegersPerGap", "(", ")", ";", "if", "(", "integerPerGap", ">", "0", ")", "{", "PrimitiveType", "pt", "=", "typeSystem", ".", "getPrimitiveType", "(", "\"", "EInt", "\"", ")", ";", "List", "<", "Integer", ">", "integerList", "=", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "getOrDefault", "(", "pt", ",", "Collections", ".", "emptySet", "(", ")", ")", ".", "stream", "(", ")", ".", "map", "(", "e", "->", "Integer", ".", "parseInt", "(", "e", ".", "getName", "(", ")", ")", ")", ".", "sorted", "(", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "List", "<", "Integer", ">", "newIntegers", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "integerList", ".", "size", "(", ")", ";", "i", "++", ")", "{", "if", "(", "i", "==", "0", ")", "{", "int", "number", "=", "integerList", ".", "get", "(", "i", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "integerPerGap", ";", "j", "++", ")", "{", "newIntegers", ".", "add", "(", "number", "-", "j", "-", "1", ")", ";", "}", "}", "else", "if", "(", "i", "==", "integerList", ".", "size", "(", ")", "-", "1", ")", "{", "int", "number", "=", "integerList", ".", "get", "(", "i", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "integerPerGap", ";", "j", "++", ")", "{", "newIntegers", ".", "add", "(", "number", "+", "j", "+", "1", ")", ";", "}", "}", "else", "{", "int", "downLimit", "=", "integerList", ".", "get", "(", "i", ")", ";", "int", "upLimit", "=", "integerList", ".", "get", "(", "i", "+", "1", ")", ";", "int", "ipg", "=", "Math", ".", "min", "(", "upLimit", "-", "downLimit", "-", "1", ",", "integerPerGap", ")", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "ipg", ";", "j", "++", ")", "{", "newIntegers", ".", "add", "(", "downLimit", "+", "j", "+", "1", ")", ";", "}", "}", "}", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "pt", ",", "p", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "getOrDefault", "(", "pt", ",", "Collections", ".", "emptySet", "(", ")", ")", ")", ";", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "pt", ",", "p", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "newIntegers", ".", "stream", "(", ")", ".", "map", "(", "i", "->", "new", "Atom", "(", "i", "+", "\"", "\"", ",", "Atom", ".", "AtomType", ".", "INTEGER", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ")", ";", "}", "Map", "<", "PrimitiveType", ",", "Integer", ">", "primitiveUpperScopes", "=", "new", "HashMap", "<", ">", "(", ")", ";", "typeSystem", ".", "getAllPrimitiveTypes", "(", ")", ".", "forEach", "(", "primitiveType", "->", "{", "typeSystem", ".", "getAllBasicReferences", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "ref", "->", "ref", ".", "getReferencedType", "(", ")", ".", "equals", "(", "primitiveType", ")", ")", ".", "forEach", "(", "ref", "->", "{", "Type", "ownerType", "=", "ref", ".", "getOwnerType", "(", ")", ";", "primitiveUpperScopes", ".", "put", "(", "primitiveType", ",", "primitiveUpperScopes", ".", "computeIfAbsent", "(", "primitiveType", ",", "p", "->", "0", ")", "+", "boundCollector", ".", "getUpperScope", "(", "ownerType", ")", ")", ";", "}", ")", ";", "}", ")", ";", "primitiveUpperScopes", ".", "forEach", "(", "(", "(", "primitiveType", ",", "upperScope", ")", "->", "{", "Set", "<", "Atom", ">", "atoms", "=", "new", "HashSet", "<", ">", "(", ")", ";", "atoms", ".", "addAll", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "getOrDefault", "(", "primitiveType", ",", "Collections", ".", "emptySet", "(", ")", ")", ")", ";", "int", "count", "=", "upperScope", "-", "atoms", ".", "size", "(", ")", ";", "if", "(", "count", "<=", "0", ")", "return", ";", "switch", "(", "primitiveType", ".", "getAtomType", "(", ")", ")", "{", "case", "STRING", ":", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "String", "name", "=", "\"", "String_", "\"", "+", "i", ";", "if", "(", "atoms", ".", "stream", "(", ")", ".", "anyMatch", "(", "a", "->", "a", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", ")", "count", "++", ";", "else", "atoms", ".", "add", "(", "new", "Atom", "(", "name", ",", "Atom", ".", "AtomType", ".", "STRING", ")", ")", ";", "}", "break", ";", "case", "INTEGER", ":", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "String", "name", "=", "\"", "\"", "+", "new", "Random", "(", ")", ".", "nextInt", "(", ")", "%", "10000", ";", "if", "(", "atoms", ".", "stream", "(", ")", ".", "anyMatch", "(", "a", "->", "a", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", ")", "count", "++", ";", "else", "atoms", ".", "add", "(", "new", "Atom", "(", "name", ",", "Atom", ".", "AtomType", ".", "INTEGER", ")", ")", ";", "}", "break", ";", "case", "BIG_INTEGER", ":", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "String", "name", "=", "\"", "\"", "+", "new", "Random", "(", ")", ".", "nextInt", "(", ")", "%", "10000", ";", "if", "(", "atoms", ".", "stream", "(", ")", ".", "anyMatch", "(", "a", "->", "a", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", ")", "count", "++", ";", "else", "atoms", ".", "add", "(", "new", "Atom", "(", "name", ",", "Atom", ".", "AtomType", ".", "BIG_INTEGER", ")", ")", ";", "}", "break", ";", "case", "BIG_DECIMAL", ":", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "String", "name", "=", "\"", "\"", "+", "new", "Random", "(", ")", ".", "nextFloat", "(", ")", ";", "if", "(", "atoms", ".", "stream", "(", ")", ".", "anyMatch", "(", "a", "->", "a", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", ")", "count", "++", ";", "else", "atoms", ".", "add", "(", "new", "Atom", "(", "name", ",", "Atom", ".", "AtomType", ".", "BIG_DECIMAL", ")", ")", ";", "}", "break", ";", "}", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "primitiveType", ",", "p", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "atoms", ")", ";", "}", ")", ")", ";", "}", "private", "void", "createObjectAtoms", "(", "Type", "type", ")", "{", "if", "(", "visited", ".", "getOrDefault", "(", "type", ",", "false", ")", ")", "return", ";", "visited", ".", "put", "(", "type", ",", "true", ")", ";", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "this", "::", "createObjectAtoms", ")", ";", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "computeIfAbsent", "(", "type", ",", "t", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "type", ".", "getSubTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "t", ".", "getSuperTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "x", "->", "(", "x", "instanceof", "GenericTypeTemplate", "||", "x", "instanceof", "BasicType", ")", ")", ".", "count", "(", ")", "<=", "1", ")", ".", "flatMap", "(", "t", "->", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "getOrDefault", "(", "t", ",", "Collections", ".", "emptySet", "(", ")", ")", ".", "stream", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ")", ";", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "type", ",", "t", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "type", ".", "getSubTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "t", "->", "t", ".", "getSuperTypes", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "x", "->", "(", "x", "instanceof", "GenericTypeTemplate", "||", "x", "instanceof", "BasicType", ")", ")", ".", "count", "(", ")", "<=", "1", ")", ".", "flatMap", "(", "t", "->", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "getOrDefault", "(", "t", ",", "Collections", ".", "emptySet", "(", ")", ")", ".", "stream", "(", ")", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ")", ";", "if", "(", "type", ".", "getSubTypes", "(", ")", ".", "stream", "(", ")", ".", "noneMatch", "(", "t", "->", "(", "t", "instanceof", "GenericTypeTemplate", "||", "t", "instanceof", "BasicType", ")", "&&", "t", ".", "getSuperTypes", "(", ")", ".", "size", "(", ")", ">", "1", ")", ")", "{", "Set", "<", "Atom", ">", "temp", "=", "new", "HashSet", "<", ">", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ")", ";", "temp", ".", "addAll", "(", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ")", ";", "if", "(", "temp", ".", "size", "(", ")", "<=", "boundCollector", ".", "getLowerScope", "(", "type", ")", ")", "{", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "put", "(", "type", ",", "temp", ")", ";", "if", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ".", "size", "(", ")", "<", "boundCollector", ".", "getLowerScope", "(", "type", ")", ")", "{", "Set", "<", "Atom", ">", "newAtoms", "=", "createNewAtoms", "(", "type", ",", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ".", "size", "(", ")", ",", "boundCollector", ".", "getLowerScope", "(", "type", ")", ")", ";", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ".", "addAll", "(", "newAtoms", ")", ";", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "t", "->", "addToUpper", "(", "t", ",", "newAtoms", ")", ")", ";", "}", "}", "}", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ".", "addAll", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ")", ";", "Set", "<", "Atom", ">", "newAtoms", "=", "new", "HashSet", "<", ">", "(", ")", ";", "if", "(", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ".", "size", "(", ")", "<", "boundCollector", ".", "getUpperScope", "(", "type", ")", ")", "{", "newAtoms", ".", "addAll", "(", "createNewAtoms", "(", "type", ",", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ".", "size", "(", ")", ",", "boundCollector", ".", "getUpperScope", "(", "type", ")", ")", ")", ";", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "get", "(", "type", ")", ".", "addAll", "(", "newAtoms", ")", ";", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "t", "->", "addToUpper", "(", "t", ",", "newAtoms", ")", ")", ";", "}", "if", "(", "type", "instanceof", "GenericTypeTemplate", ")", "{", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "t", "->", "addToUpperOfGenerics", "(", "t", ",", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ")", ")", ";", "}", "atomsToIgnore", ".", "addAll", "(", "boundCollector", ".", "getUnaryLowerBounds", "(", ")", ".", "get", "(", "type", ")", ")", ";", "}", "private", "void", "addToUpperOfGenerics", "(", "Type", "type", ",", "Set", "<", "Atom", ">", "atoms", ")", "{", "if", "(", "!", "(", "type", "instanceof", "GenericTypeAbstractImpl", "||", "type", "instanceof", "GenericTypeImpl", ")", ")", "return", ";", "if", "(", "boundCollector", ".", "hasScope", "(", "type", ")", ")", "return", ";", "Set", "<", "Atom", ">", "atomsClone", "=", "new", "HashSet", "<", ">", "(", "atoms", ")", ";", "atomsClone", ".", "removeAll", "(", "atomsToIgnore", ")", ";", "if", "(", "atomsClone", ".", "isEmpty", "(", ")", ")", "return", ";", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "type", ",", "t", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "atomsClone", ")", ";", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "subType", "->", "addToUpperOfGenerics", "(", "subType", ",", "atomsClone", ")", ")", ";", "}", "private", "void", "addToUpper", "(", "Type", "type", ",", "Set", "<", "Atom", ">", "atoms", ")", "{", "if", "(", "boundCollector", ".", "hasScope", "(", "type", ")", ")", "return", ";", "Set", "<", "Atom", ">", "atomsClone", "=", "new", "HashSet", "<", ">", "(", "atoms", ")", ";", "atomsClone", ".", "removeAll", "(", "atomsToIgnore", ")", ";", "if", "(", "type", "instanceof", "BasicType", ")", "atomsClone", ".", "removeAll", "(", "originalAtoms", ")", ";", "if", "(", "atomsClone", ".", "isEmpty", "(", ")", ")", "return", ";", "boundCollector", ".", "getUnaryUpperBounds", "(", ")", ".", "computeIfAbsent", "(", "type", ",", "t", "->", "new", "HashSet", "<", ">", "(", ")", ")", ".", "addAll", "(", "atomsClone", ")", ";", "type", ".", "getSubTypes", "(", ")", ".", "forEach", "(", "subType", "->", "addToUpper", "(", "subType", ",", "atomsClone", ")", ")", ";", "}", "private", "Set", "<", "Atom", ">", "createNewAtoms", "(", "Type", "type", ",", "int", "curSize", ",", "int", "wantedSize", ")", "{", "Set", "<", "Atom", ">", "newAtoms", "=", "new", "HashSet", "<", ">", "(", ")", ";", "for", "(", "int", "i", "=", "curSize", ";", "i", "<", "wantedSize", ";", "i", "++", ")", "{", "Atom", "atom", "=", "new", "Atom", "(", "type", ".", "getName", "(", ")", "+", "\"", "_", "\"", "+", "i", ",", "Atom", ".", "AtomType", ".", "OBJECT", ")", ";", "atom", ".", "setObject", "(", "type", ".", "getElement", "(", ")", ")", ";", "newAtoms", ".", "add", "(", "atom", ")", ";", "}", "return", "newAtoms", ";", "}", "}" ]
Created by harun on 2/2/18.
[ "Created", "by", "harun", "on", "2", "/", "2", "/", "18", "." ]
[ "// Create and add integers if gt, gte, lt, lte used.", "// Get upper scope informations", "// type.getSubTypes().forEach(t -> addToUpper(t, type, boundCollector.getUnaryUpperBounds().get(type)));" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
171845ed75ae35de377c3222d617eb6229d6ca28
hugy718/cool
cool-core/src/test/java/com/nus/cool/core/io/store/TestTable.java
[ "Apache-2.0" ]
Java
TestTable
/** * Generate TestTable from csv File simply and Generate Data for UnitTest */
Generate TestTable from csv File simply and Generate Data for UnitTest
[ "Generate", "TestTable", "from", "csv", "File", "simply", "and", "Generate", "Data", "for", "UnitTest" ]
public class TestTable { public HashMap<String, Integer> field2Ids; public ArrayList<String> fields; public ArrayList<ArrayList<String>> cols; public CsvTupleParser parser = null; public int rowCounts; public int colCounts; private TestTable() { this.field2Ids = new HashMap<String, Integer>(); this.fields = new ArrayList<>(); this.parser = new CsvTupleParser(); this.cols = new ArrayList<ArrayList<String>>(); this.rowCounts = 0; this.colCounts = 0; } /** * * @param filepath * @return new TestTable object which structured file data */ public static TestTable readFromCSV(String filepath) { TestTable table = new TestTable(); try { File file = new File(filepath); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; Boolean header = true; while ((line = br.readLine()) != null) { String[] vs = table.parser.parse(line); if (header) { for (int i = 0; i < vs.length; i++) { table.field2Ids.put(vs[i], i); table.fields.add(vs[i]); table.cols.add(new ArrayList<String>()); } table.colCounts = table.field2Ids.size(); header = false; continue; } for (int i = 0; i < table.field2Ids.size(); i++) { table.cols.get(i).add(vs[i]); table.rowCounts += 1; } } fr.close(); } catch (IOException e) { e.printStackTrace(); } return table; } /** * Print all dataItem */ public void ShowTable() { this.tablePrint(this.rowCounts); } /** * Print first 10 line dataitem */ public void ShowTableHead() { this.tablePrint(10); } private void tablePrint(int rows) { int rowMax = rows > this.rowCounts ? this.rowCounts : rows; // print header System.out.println("Table:"); String line = "|"; for (String colheader : this.fields) { String s = String.format("%15s_%d", colheader, this.field2Ids.get(colheader)); line += s; } line += "|"; int n = line.length() - 2; printline(n); System.out.println(line); printline(n); // print value for (int row = 0; row < rowMax; row++) { line = "| "; for (int col = 0; col < this.colCounts; col++) { String s = String.format("%15s |", this.cols.get(col).get(row)); line = String.join("", line, s); } System.out.println(line); } printline(n); } private void printline(int n) { String line = "|"; String s = String.join("", Collections.nCopies(n, "-")); line = line + s + line; System.out.println(line); } }
[ "public", "class", "TestTable", "{", "public", "HashMap", "<", "String", ",", "Integer", ">", "field2Ids", ";", "public", "ArrayList", "<", "String", ">", "fields", ";", "public", "ArrayList", "<", "ArrayList", "<", "String", ">", ">", "cols", ";", "public", "CsvTupleParser", "parser", "=", "null", ";", "public", "int", "rowCounts", ";", "public", "int", "colCounts", ";", "private", "TestTable", "(", ")", "{", "this", ".", "field2Ids", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "this", ".", "fields", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "this", ".", "parser", "=", "new", "CsvTupleParser", "(", ")", ";", "this", ".", "cols", "=", "new", "ArrayList", "<", "ArrayList", "<", "String", ">", ">", "(", ")", ";", "this", ".", "rowCounts", "=", "0", ";", "this", ".", "colCounts", "=", "0", ";", "}", "/**\n * \n * @param filepath\n * @return new TestTable object which structured file data\n */", "public", "static", "TestTable", "readFromCSV", "(", "String", "filepath", ")", "{", "TestTable", "table", "=", "new", "TestTable", "(", ")", ";", "try", "{", "File", "file", "=", "new", "File", "(", "filepath", ")", ";", "FileReader", "fr", "=", "new", "FileReader", "(", "file", ")", ";", "BufferedReader", "br", "=", "new", "BufferedReader", "(", "fr", ")", ";", "String", "line", ";", "Boolean", "header", "=", "true", ";", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "[", "]", "vs", "=", "table", ".", "parser", ".", "parse", "(", "line", ")", ";", "if", "(", "header", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "vs", ".", "length", ";", "i", "++", ")", "{", "table", ".", "field2Ids", ".", "put", "(", "vs", "[", "i", "]", ",", "i", ")", ";", "table", ".", "fields", ".", "add", "(", "vs", "[", "i", "]", ")", ";", "table", ".", "cols", ".", "add", "(", "new", "ArrayList", "<", "String", ">", "(", ")", ")", ";", "}", "table", ".", "colCounts", "=", "table", ".", "field2Ids", ".", "size", "(", ")", ";", "header", "=", "false", ";", "continue", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "table", ".", "field2Ids", ".", "size", "(", ")", ";", "i", "++", ")", "{", "table", ".", "cols", ".", "get", "(", "i", ")", ".", "add", "(", "vs", "[", "i", "]", ")", ";", "table", ".", "rowCounts", "+=", "1", ";", "}", "}", "fr", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "table", ";", "}", "/**\n * Print all dataItem\n */", "public", "void", "ShowTable", "(", ")", "{", "this", ".", "tablePrint", "(", "this", ".", "rowCounts", ")", ";", "}", "/**\n * Print first 10 line dataitem\n */", "public", "void", "ShowTableHead", "(", ")", "{", "this", ".", "tablePrint", "(", "10", ")", ";", "}", "private", "void", "tablePrint", "(", "int", "rows", ")", "{", "int", "rowMax", "=", "rows", ">", "this", ".", "rowCounts", "?", "this", ".", "rowCounts", ":", "rows", ";", "System", ".", "out", ".", "println", "(", "\"", "Table:", "\"", ")", ";", "String", "line", "=", "\"", "|", "\"", ";", "for", "(", "String", "colheader", ":", "this", ".", "fields", ")", "{", "String", "s", "=", "String", ".", "format", "(", "\"", "%15s_%d", "\"", ",", "colheader", ",", "this", ".", "field2Ids", ".", "get", "(", "colheader", ")", ")", ";", "line", "+=", "s", ";", "}", "line", "+=", "\"", "|", "\"", ";", "int", "n", "=", "line", ".", "length", "(", ")", "-", "2", ";", "printline", "(", "n", ")", ";", "System", ".", "out", ".", "println", "(", "line", ")", ";", "printline", "(", "n", ")", ";", "for", "(", "int", "row", "=", "0", ";", "row", "<", "rowMax", ";", "row", "++", ")", "{", "line", "=", "\"", "| ", "\"", ";", "for", "(", "int", "col", "=", "0", ";", "col", "<", "this", ".", "colCounts", ";", "col", "++", ")", "{", "String", "s", "=", "String", ".", "format", "(", "\"", "%15s |", "\"", ",", "this", ".", "cols", ".", "get", "(", "col", ")", ".", "get", "(", "row", ")", ")", ";", "line", "=", "String", ".", "join", "(", "\"", "\"", ",", "line", ",", "s", ")", ";", "}", "System", ".", "out", ".", "println", "(", "line", ")", ";", "}", "printline", "(", "n", ")", ";", "}", "private", "void", "printline", "(", "int", "n", ")", "{", "String", "line", "=", "\"", "|", "\"", ";", "String", "s", "=", "String", ".", "join", "(", "\"", "\"", ",", "Collections", ".", "nCopies", "(", "n", ",", "\"", "-", "\"", ")", ")", ";", "line", "=", "line", "+", "s", "+", "line", ";", "System", ".", "out", ".", "println", "(", "line", ")", ";", "}", "}" ]
Generate TestTable from csv File simply and Generate Data for UnitTest
[ "Generate", "TestTable", "from", "csv", "File", "simply", "and", "Generate", "Data", "for", "UnitTest" ]
[ "// print header", "// print value" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
1718a44389380a57a83bb51611e7f97df06c1de8
lafaspot/imapnioclient
core/src/test/java/com/yahoo/imapnio/async/exception/ImapAsyncClientExceptionTest.java
[ "Apache-2.0" ]
Java
ImapAsyncClientExceptionTest
/** * Unit test for {@link ImapAsyncClientException}. */
Unit test for ImapAsyncClientException.
[ "Unit", "test", "for", "ImapAsyncClientException", "." ]
public class ImapAsyncClientExceptionTest { /** * Tests ImapAsyncClientException. */ @Test public void testImapAsyncClientException() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED; final ImapAsyncClientException resp = new ImapAsyncClientException(failureType); Assert.assertEquals(resp.getFailureType(), failureType, "result mismatched."); Assert.assertNull(resp.getCause(), "cause of exception mismatched."); Assert.assertEquals(resp.getMessage(), "failureType=" + failureType.name(), "result mismatched."); } /** * Tests ImapAsyncClientException constructor. */ @Test public void testImapAsyncClientExceptionWithFailureTypeAndCause() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED; final IOException cause = new IOException("Failure in IO!"); final ImapAsyncClientException ex = new ImapAsyncClientException(failureType, cause); Assert.assertEquals(ex.getFailureType(), failureType, "result mismatched."); Assert.assertEquals(ex.getMessage(), "failureType=CHANNEL_DISCONNECTED", "result mismatched."); Assert.assertEquals(ex.getCause(), cause, "cause of exception mismatched."); } /** * Tests ImapAsyncClientException constructor. */ @Test public void testImapAsyncClientExceptionWithSessionIdClientContext() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED; final Long sessionId = new Long(5); final String sessCtx = "[email protected]"; final ImapAsyncClientException ex = new ImapAsyncClientException(failureType, sessionId, sessCtx); Assert.assertEquals(ex.getFailureType(), failureType, "result mismatched."); Assert.assertNull(ex.getCause(), "cause of exception mismatched."); Assert.assertEquals(ex.getMessage(), "failureType=CHANNEL_DISCONNECTED,sId=5,[email protected]", "result mismatched."); } /** * Tests ImapAsyncClientException when failureType is null. */ @Test public void testFailureType() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.valueOf("CHANNEL_DISCONNECTED"); Assert.assertEquals(failureType, ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED, "result mismatched."); Assert.assertEquals(ImapAsyncClientException.FailureType.values().length, 17, "Number of enums mismatched."); } }
[ "public", "class", "ImapAsyncClientExceptionTest", "{", "/**\n * Tests ImapAsyncClientException.\n */", "@", "Test", "public", "void", "testImapAsyncClientException", "(", ")", "{", "final", "ImapAsyncClientException", ".", "FailureType", "failureType", "=", "ImapAsyncClientException", ".", "FailureType", ".", "CHANNEL_DISCONNECTED", ";", "final", "ImapAsyncClientException", "resp", "=", "new", "ImapAsyncClientException", "(", "failureType", ")", ";", "Assert", ".", "assertEquals", "(", "resp", ".", "getFailureType", "(", ")", ",", "failureType", ",", "\"", "result mismatched.", "\"", ")", ";", "Assert", ".", "assertNull", "(", "resp", ".", "getCause", "(", ")", ",", "\"", "cause of exception mismatched.", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "resp", ".", "getMessage", "(", ")", ",", "\"", "failureType=", "\"", "+", "failureType", ".", "name", "(", ")", ",", "\"", "result mismatched.", "\"", ")", ";", "}", "/**\n * Tests ImapAsyncClientException constructor.\n */", "@", "Test", "public", "void", "testImapAsyncClientExceptionWithFailureTypeAndCause", "(", ")", "{", "final", "ImapAsyncClientException", ".", "FailureType", "failureType", "=", "ImapAsyncClientException", ".", "FailureType", ".", "CHANNEL_DISCONNECTED", ";", "final", "IOException", "cause", "=", "new", "IOException", "(", "\"", "Failure in IO!", "\"", ")", ";", "final", "ImapAsyncClientException", "ex", "=", "new", "ImapAsyncClientException", "(", "failureType", ",", "cause", ")", ";", "Assert", ".", "assertEquals", "(", "ex", ".", "getFailureType", "(", ")", ",", "failureType", ",", "\"", "result mismatched.", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "ex", ".", "getMessage", "(", ")", ",", "\"", "failureType=CHANNEL_DISCONNECTED", "\"", ",", "\"", "result mismatched.", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "ex", ".", "getCause", "(", ")", ",", "cause", ",", "\"", "cause of exception mismatched.", "\"", ")", ";", "}", "/**\n * Tests ImapAsyncClientException constructor.\n */", "@", "Test", "public", "void", "testImapAsyncClientExceptionWithSessionIdClientContext", "(", ")", "{", "final", "ImapAsyncClientException", ".", "FailureType", "failureType", "=", "ImapAsyncClientException", ".", "FailureType", ".", "CHANNEL_DISCONNECTED", ";", "final", "Long", "sessionId", "=", "new", "Long", "(", "5", ")", ";", "final", "String", "sessCtx", "=", "\"", "[email protected]", "\"", ";", "final", "ImapAsyncClientException", "ex", "=", "new", "ImapAsyncClientException", "(", "failureType", ",", "sessionId", ",", "sessCtx", ")", ";", "Assert", ".", "assertEquals", "(", "ex", ".", "getFailureType", "(", ")", ",", "failureType", ",", "\"", "result mismatched.", "\"", ")", ";", "Assert", ".", "assertNull", "(", "ex", ".", "getCause", "(", ")", ",", "\"", "cause of exception mismatched.", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "ex", ".", "getMessage", "(", ")", ",", "\"", "failureType=CHANNEL_DISCONNECTED,sId=5,[email protected]", "\"", ",", "\"", "result mismatched.", "\"", ")", ";", "}", "/**\n * Tests ImapAsyncClientException when failureType is null.\n */", "@", "Test", "public", "void", "testFailureType", "(", ")", "{", "final", "ImapAsyncClientException", ".", "FailureType", "failureType", "=", "ImapAsyncClientException", ".", "FailureType", ".", "valueOf", "(", "\"", "CHANNEL_DISCONNECTED", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "failureType", ",", "ImapAsyncClientException", ".", "FailureType", ".", "CHANNEL_DISCONNECTED", ",", "\"", "result mismatched.", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "ImapAsyncClientException", ".", "FailureType", ".", "values", "(", ")", ".", "length", ",", "17", ",", "\"", "Number of enums mismatched.", "\"", ")", ";", "}", "}" ]
Unit test for {@link ImapAsyncClientException}.
[ "Unit", "test", "for", "{", "@link", "ImapAsyncClientException", "}", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
171f7d49d8262a7aa7d216253b0dd8c9cebd5387
melink14/6.867-Final-Project
src/erekspeed/CuckooAgentLoader.java
[ "BSD-3-Clause" ]
Java
CuckooAgentLoader
/** * Created by IntelliJ IDEA. * User: espeed * Date: Aug 18, 2009 * Time: 5:46:34 PM * When run as agent loads */
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
public class CuckooAgentLoader implements Agent { CuckooSubAgent agent; public CuckooAgentLoader() { try { long start, stop, elapsed; start = System.currentTimeMillis(); FileInputStream is = new FileInputStream("F:\\college\\6867\\project\\benchmark\\best_def_6792.0_24_5_1339_lhb-false_lt-0_13224632"); ObjectInputStream in = new ObjectInputStream(is); agent = (CuckooSubAgent) in.readObject(); stop = System.currentTimeMillis(); elapsed = stop - start; System.out.println("Time taken to load:" + elapsed); } catch (Exception ex) { System.err.println(ex); } setName("Cuckoo Agent"); } public void reset() { agent.reset(); } public boolean[] getAction() { return agent.getAction(); } public void integrateObservation(Environment environment) { try { agent.integrateObservation(environment); } catch (Exception ex) { System.out.println("cuckoo agent loader:" + ex.toString()); } } public void giveIntermediateReward(float intermediateReward) { //To change body of implemented methods use File | Settings | File Templates. } public String getName() { return agent.getName(); } public void setName(String name) { agent.setName(name); } @Override public void setObservationDetails(int rfWidth, int rfHeight, int egoRow, int egoCol) { // TODO Auto-generated method stub } }
[ "public", "class", "CuckooAgentLoader", "implements", "Agent", "{", "CuckooSubAgent", "agent", ";", "public", "CuckooAgentLoader", "(", ")", "{", "try", "{", "long", "start", ",", "stop", ",", "elapsed", ";", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "FileInputStream", "is", "=", "new", "FileInputStream", "(", "\"", "F:", "\\\\", "college", "\\\\", "6867", "\\\\", "project", "\\\\", "benchmark", "\\\\", "best_def_6792.0_24_5_1339_lhb-false_lt-0_13224632", "\"", ")", ";", "ObjectInputStream", "in", "=", "new", "ObjectInputStream", "(", "is", ")", ";", "agent", "=", "(", "CuckooSubAgent", ")", "in", ".", "readObject", "(", ")", ";", "stop", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "elapsed", "=", "stop", "-", "start", ";", "System", ".", "out", ".", "println", "(", "\"", "Time taken to load:", "\"", "+", "elapsed", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "System", ".", "err", ".", "println", "(", "ex", ")", ";", "}", "setName", "(", "\"", "Cuckoo Agent", "\"", ")", ";", "}", "public", "void", "reset", "(", ")", "{", "agent", ".", "reset", "(", ")", ";", "}", "public", "boolean", "[", "]", "getAction", "(", ")", "{", "return", "agent", ".", "getAction", "(", ")", ";", "}", "public", "void", "integrateObservation", "(", "Environment", "environment", ")", "{", "try", "{", "agent", ".", "integrateObservation", "(", "environment", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "cuckoo agent loader:", "\"", "+", "ex", ".", "toString", "(", ")", ")", ";", "}", "}", "public", "void", "giveIntermediateReward", "(", "float", "intermediateReward", ")", "{", "}", "public", "String", "getName", "(", ")", "{", "return", "agent", ".", "getName", "(", ")", ";", "}", "public", "void", "setName", "(", "String", "name", ")", "{", "agent", ".", "setName", "(", "name", ")", ";", "}", "@", "Override", "public", "void", "setObservationDetails", "(", "int", "rfWidth", ",", "int", "rfHeight", ",", "int", "egoRow", ",", "int", "egoCol", ")", "{", "}", "}" ]
Created by IntelliJ IDEA.
[ "Created", "by", "IntelliJ", "IDEA", "." ]
[ "//To change body of implemented methods use File | Settings | File Templates.", "// TODO Auto-generated method stub" ]
[ { "param": "Agent", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Agent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe022dad7c6d090d24cadf9da3a09c3a92b9765f
jstastny-cz/appformer
uberfire-extensions/uberfire-security/uberfire-security-management/uberfire-security-management-wildfly/src/main/java/org/uberfire/ext/security/management/wildfly/properties/BaseWildflyPropertiesManager.java
[ "Apache-2.0" ]
Java
BaseWildflyPropertiesManager
/** * <p>Base class for JBoss Wildfly security management when using realms based on properties files.</p> * <p>Based on JBoss Wildfly controller client API & Util classes.</p> * @since 0.8.0 */
Base class for JBoss Wildfly security management when using realms based on properties files. Based on JBoss Wildfly controller client API & Util classes. @since 0.8.0
[ "Base", "class", "for", "JBoss", "Wildfly", "security", "management", "when", "using", "realms", "based", "on", "properties", "files", ".", "Based", "on", "JBoss", "Wildfly", "controller", "client", "API", "&", "Util", "classes", ".", "@since", "0", ".", "8", ".", "0" ]
public abstract class BaseWildflyPropertiesManager { public static final String DEFAULT_REALM = "ApplicationRealm"; private static final Logger LOG = LoggerFactory.getLogger(BaseWildflyPropertiesManager.class); protected String realm = DEFAULT_REALM; protected static String generateHashPassword(final String username, final String realm, final String password) { String result = null; try { result = new UsernamePasswordHashUtil().generateHashedHexURP( username, realm, password.toCharArray()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } protected static boolean isConfigPropertySet(ConfigProperties.ConfigProperty property) { if (property == null) { return false; } String value = property.getValue(); return !isEmpty(value); } protected static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; } protected void loadConfig(final ConfigProperties config) { final ConfigProperties.ConfigProperty realm = config.get("org.uberfire.ext.security.management.wildfly.properties.realm", DEFAULT_REALM); this.realm = realm.getValue(); } }
[ "public", "abstract", "class", "BaseWildflyPropertiesManager", "{", "public", "static", "final", "String", "DEFAULT_REALM", "=", "\"", "ApplicationRealm", "\"", ";", "private", "static", "final", "Logger", "LOG", "=", "LoggerFactory", ".", "getLogger", "(", "BaseWildflyPropertiesManager", ".", "class", ")", ";", "protected", "String", "realm", "=", "DEFAULT_REALM", ";", "protected", "static", "String", "generateHashPassword", "(", "final", "String", "username", ",", "final", "String", "realm", ",", "final", "String", "password", ")", "{", "String", "result", "=", "null", ";", "try", "{", "result", "=", "new", "UsernamePasswordHashUtil", "(", ")", ".", "generateHashedHexURP", "(", "username", ",", "realm", ",", "password", ".", "toCharArray", "(", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "return", "result", ";", "}", "protected", "static", "boolean", "isConfigPropertySet", "(", "ConfigProperties", ".", "ConfigProperty", "property", ")", "{", "if", "(", "property", "==", "null", ")", "{", "return", "false", ";", "}", "String", "value", "=", "property", ".", "getValue", "(", ")", ";", "return", "!", "isEmpty", "(", "value", ")", ";", "}", "protected", "static", "boolean", "isEmpty", "(", "String", "s", ")", "{", "return", "s", "==", "null", "||", "s", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ";", "}", "protected", "void", "loadConfig", "(", "final", "ConfigProperties", "config", ")", "{", "final", "ConfigProperties", ".", "ConfigProperty", "realm", "=", "config", ".", "get", "(", "\"", "org.uberfire.ext.security.management.wildfly.properties.realm", "\"", ",", "DEFAULT_REALM", ")", ";", "this", ".", "realm", "=", "realm", ".", "getValue", "(", ")", ";", "}", "}" ]
<p>Base class for JBoss Wildfly security management when using realms based on properties files.</p> <p>Based on JBoss Wildfly controller client API & Util classes.</p> @since 0.8.0
[ "<p", ">", "Base", "class", "for", "JBoss", "Wildfly", "security", "management", "when", "using", "realms", "based", "on", "properties", "files", ".", "<", "/", "p", ">", "<p", ">", "Based", "on", "JBoss", "Wildfly", "controller", "client", "API", "&", "Util", "classes", ".", "<", "/", "p", ">", "@since", "0", ".", "8", ".", "0" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe025fcb486b7ae970b5ea498784986660147d55
datengaertnerei/jira-client
src/main/java/com/datengaertnerei/jira/rest/client/model/ErrorCollection.java
[ "Unlicense" ]
Java
ErrorCollection
/** * Error messages from an operation. */
Error messages from an operation.
[ "Error", "messages", "from", "an", "operation", "." ]
@ApiModel(description = "Error messages from an operation.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-05-17T17:45:56.601554Z[Etc/UTC]") public class ErrorCollection { public static final String SERIALIZED_NAME_ERROR_MESSAGES = "errorMessages"; @SerializedName(SERIALIZED_NAME_ERROR_MESSAGES) private List<String> errorMessages = null; public static final String SERIALIZED_NAME_ERRORS = "errors"; @SerializedName(SERIALIZED_NAME_ERRORS) private Map<String, String> errors = null; public static final String SERIALIZED_NAME_STATUS = "status"; @SerializedName(SERIALIZED_NAME_STATUS) private Integer status; public ErrorCollection errorMessages(List<String> errorMessages) { this.errorMessages = errorMessages; return this; } public ErrorCollection addErrorMessagesItem(String errorMessagesItem) { if (this.errorMessages == null) { this.errorMessages = new ArrayList<>(); } this.errorMessages.add(errorMessagesItem); return this; } /** * The list of error messages produced by this operation. For example, \&quot;input parameter &#39;key&#39; must be provided\&quot; * @return errorMessages **/ @javax.annotation.Nullable @ApiModelProperty(value = "The list of error messages produced by this operation. For example, \"input parameter 'key' must be provided\"") public List<String> getErrorMessages() { return errorMessages; } public void setErrorMessages(List<String> errorMessages) { this.errorMessages = errorMessages; } public ErrorCollection errors(Map<String, String> errors) { this.errors = errors; return this; } public ErrorCollection putErrorsItem(String key, String errorsItem) { if (this.errors == null) { this.errors = new HashMap<>(); } this.errors.put(key, errorsItem); return this; } /** * The list of errors by parameter returned by the operation. For example,\&quot;projectKey\&quot;: \&quot;Project keys must start with an uppercase letter, followed by one or more uppercase alphanumeric characters.\&quot; * @return errors **/ @javax.annotation.Nullable @ApiModelProperty(value = "The list of errors by parameter returned by the operation. For example,\"projectKey\": \"Project keys must start with an uppercase letter, followed by one or more uppercase alphanumeric characters.\"") public Map<String, String> getErrors() { return errors; } public void setErrors(Map<String, String> errors) { this.errors = errors; } public ErrorCollection status(Integer status) { this.status = status; return this; } /** * Get status * @return status **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ErrorCollection errorCollection = (ErrorCollection) o; return Objects.equals(this.errorMessages, errorCollection.errorMessages) && Objects.equals(this.errors, errorCollection.errors) && Objects.equals(this.status, errorCollection.status); } @Override public int hashCode() { return Objects.hash(errorMessages, errors, status); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ErrorCollection {\n"); sb.append(" errorMessages: ").append(toIndentedString(errorMessages)).append("\n"); sb.append(" errors: ").append(toIndentedString(errors)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
[ "@", "ApiModel", "(", "description", "=", "\"", "Error messages from an operation.", "\"", ")", "@", "javax", ".", "annotation", ".", "Generated", "(", "value", "=", "\"", "org.openapitools.codegen.languages.JavaClientCodegen", "\"", ",", "date", "=", "\"", "2021-05-17T17:45:56.601554Z[Etc/UTC]", "\"", ")", "public", "class", "ErrorCollection", "{", "public", "static", "final", "String", "SERIALIZED_NAME_ERROR_MESSAGES", "=", "\"", "errorMessages", "\"", ";", "@", "SerializedName", "(", "SERIALIZED_NAME_ERROR_MESSAGES", ")", "private", "List", "<", "String", ">", "errorMessages", "=", "null", ";", "public", "static", "final", "String", "SERIALIZED_NAME_ERRORS", "=", "\"", "errors", "\"", ";", "@", "SerializedName", "(", "SERIALIZED_NAME_ERRORS", ")", "private", "Map", "<", "String", ",", "String", ">", "errors", "=", "null", ";", "public", "static", "final", "String", "SERIALIZED_NAME_STATUS", "=", "\"", "status", "\"", ";", "@", "SerializedName", "(", "SERIALIZED_NAME_STATUS", ")", "private", "Integer", "status", ";", "public", "ErrorCollection", "errorMessages", "(", "List", "<", "String", ">", "errorMessages", ")", "{", "this", ".", "errorMessages", "=", "errorMessages", ";", "return", "this", ";", "}", "public", "ErrorCollection", "addErrorMessagesItem", "(", "String", "errorMessagesItem", ")", "{", "if", "(", "this", ".", "errorMessages", "==", "null", ")", "{", "this", ".", "errorMessages", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "}", "this", ".", "errorMessages", ".", "add", "(", "errorMessagesItem", ")", ";", "return", "this", ";", "}", "/**\n * The list of error messages produced by this operation. For example, \\&quot;input parameter &#39;key&#39; must be provided\\&quot;\n * @return errorMessages\n **/", "@", "javax", ".", "annotation", ".", "Nullable", "@", "ApiModelProperty", "(", "value", "=", "\"", "The list of error messages produced by this operation. For example, ", "\\\"", "input parameter 'key' must be provided", "\\\"", "\"", ")", "public", "List", "<", "String", ">", "getErrorMessages", "(", ")", "{", "return", "errorMessages", ";", "}", "public", "void", "setErrorMessages", "(", "List", "<", "String", ">", "errorMessages", ")", "{", "this", ".", "errorMessages", "=", "errorMessages", ";", "}", "public", "ErrorCollection", "errors", "(", "Map", "<", "String", ",", "String", ">", "errors", ")", "{", "this", ".", "errors", "=", "errors", ";", "return", "this", ";", "}", "public", "ErrorCollection", "putErrorsItem", "(", "String", "key", ",", "String", "errorsItem", ")", "{", "if", "(", "this", ".", "errors", "==", "null", ")", "{", "this", ".", "errors", "=", "new", "HashMap", "<", ">", "(", ")", ";", "}", "this", ".", "errors", ".", "put", "(", "key", ",", "errorsItem", ")", ";", "return", "this", ";", "}", "/**\n * The list of errors by parameter returned by the operation. For example,\\&quot;projectKey\\&quot;: \\&quot;Project keys must start with an uppercase letter, followed by one or more uppercase alphanumeric characters.\\&quot;\n * @return errors\n **/", "@", "javax", ".", "annotation", ".", "Nullable", "@", "ApiModelProperty", "(", "value", "=", "\"", "The list of errors by parameter returned by the operation. For example,", "\\\"", "projectKey", "\\\"", ": ", "\\\"", "Project keys must start with an uppercase letter, followed by one or more uppercase alphanumeric characters.", "\\\"", "\"", ")", "public", "Map", "<", "String", ",", "String", ">", "getErrors", "(", ")", "{", "return", "errors", ";", "}", "public", "void", "setErrors", "(", "Map", "<", "String", ",", "String", ">", "errors", ")", "{", "this", ".", "errors", "=", "errors", ";", "}", "public", "ErrorCollection", "status", "(", "Integer", "status", ")", "{", "this", ".", "status", "=", "status", ";", "return", "this", ";", "}", "/**\n * Get status\n * @return status\n **/", "@", "javax", ".", "annotation", ".", "Nullable", "@", "ApiModelProperty", "(", "value", "=", "\"", "\"", ")", "public", "Integer", "getStatus", "(", ")", "{", "return", "status", ";", "}", "public", "void", "setStatus", "(", "Integer", "status", ")", "{", "this", ".", "status", "=", "status", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "ErrorCollection", "errorCollection", "=", "(", "ErrorCollection", ")", "o", ";", "return", "Objects", ".", "equals", "(", "this", ".", "errorMessages", ",", "errorCollection", ".", "errorMessages", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "errors", ",", "errorCollection", ".", "errors", ")", "&&", "Objects", ".", "equals", "(", "this", ".", "status", ",", "errorCollection", ".", "status", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "errorMessages", ",", "errors", ",", "status", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "class ErrorCollection {", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " errorMessages: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "errorMessages", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " errors: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "errors", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", " status: ", "\"", ")", ".", "append", "(", "toIndentedString", "(", "status", ")", ")", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "sb", ".", "append", "(", "\"", "}", "\"", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */", "private", "String", "toIndentedString", "(", "Object", "o", ")", "{", "if", "(", "o", "==", "null", ")", "{", "return", "\"", "null", "\"", ";", "}", "return", "o", ".", "toString", "(", ")", ".", "replace", "(", "\"", "\\n", "\"", ",", "\"", "\\n", " ", "\"", ")", ";", "}", "}" ]
Error messages from an operation.
[ "Error", "messages", "from", "an", "operation", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe04ab22be75546f29f1655821d2909555b20353
xxlabaza/hazelcast_eureka
member/src/main/java/com/xxlabaza/test/hazelcast/eureka/member/HazelcastMemberConfiguration.java
[ "Apache-2.0" ]
Java
HazelcastMemberConfiguration
/** * @author Artem Labazin <[email protected]> * @since 01.12.2016 */
@author Artem Labazin @since 01.12.2016
[ "@author", "Artem", "Labazin", "@since", "01", ".", "12", ".", "2016" ]
@Configuration class HazelcastMemberConfiguration { @Autowired private DiscoveryClient discoveryClient; @Value("${spring.application.name}") private String applicationName; @Value("${app.hazelcast.port}") private Integer hazelcastPort; @Bean public Config hazelcastConfig () { val config = new Config(); config.setProperty("hazelcast.discovery.enabled", "true"); val networkingConfig = config.getNetworkConfig(); networkingConfig.setPort(hazelcastPort); networkingConfig.setPortAutoIncrement(false); val joinConfig = networkingConfig.getJoin(); joinConfig.getMulticastConfig().setEnabled(false); joinConfig.getTcpIpConfig().setEnabled(false); joinConfig.getAwsConfig().setEnabled(false); joinConfig.getDiscoveryConfig() .addDiscoveryStrategyConfig(new DiscoveryStrategyConfig(discoveryStrategyFactory())); return config; } @Bean public DiscoveryStrategyFactory discoveryStrategyFactory () { return new DiscoveryStrategyFactory() { @Override public Class<? extends DiscoveryStrategy> getDiscoveryStrategyType () { return EurekaDiscoveryStrategy.class; } @Override public DiscoveryStrategy newDiscoveryStrategy (DiscoveryNode discoveryNode, ILogger logger, Map<String, Comparable> properties ) { val eurekaDiscoveryStrategy = new EurekaDiscoveryStrategy(logger, emptyMap()); eurekaDiscoveryStrategy.setDiscoveryClient(discoveryClient); eurekaDiscoveryStrategy.setHaselcastNodeServiceId(applicationName); return eurekaDiscoveryStrategy; } @Override public Collection<PropertyDefinition> getConfigurationProperties () { return null; } }; } }
[ "@", "Configuration", "class", "HazelcastMemberConfiguration", "{", "@", "Autowired", "private", "DiscoveryClient", "discoveryClient", ";", "@", "Value", "(", "\"", "${spring.application.name}", "\"", ")", "private", "String", "applicationName", ";", "@", "Value", "(", "\"", "${app.hazelcast.port}", "\"", ")", "private", "Integer", "hazelcastPort", ";", "@", "Bean", "public", "Config", "hazelcastConfig", "(", ")", "{", "val", "config", "=", "new", "Config", "(", ")", ";", "config", ".", "setProperty", "(", "\"", "hazelcast.discovery.enabled", "\"", ",", "\"", "true", "\"", ")", ";", "val", "networkingConfig", "=", "config", ".", "getNetworkConfig", "(", ")", ";", "networkingConfig", ".", "setPort", "(", "hazelcastPort", ")", ";", "networkingConfig", ".", "setPortAutoIncrement", "(", "false", ")", ";", "val", "joinConfig", "=", "networkingConfig", ".", "getJoin", "(", ")", ";", "joinConfig", ".", "getMulticastConfig", "(", ")", ".", "setEnabled", "(", "false", ")", ";", "joinConfig", ".", "getTcpIpConfig", "(", ")", ".", "setEnabled", "(", "false", ")", ";", "joinConfig", ".", "getAwsConfig", "(", ")", ".", "setEnabled", "(", "false", ")", ";", "joinConfig", ".", "getDiscoveryConfig", "(", ")", ".", "addDiscoveryStrategyConfig", "(", "new", "DiscoveryStrategyConfig", "(", "discoveryStrategyFactory", "(", ")", ")", ")", ";", "return", "config", ";", "}", "@", "Bean", "public", "DiscoveryStrategyFactory", "discoveryStrategyFactory", "(", ")", "{", "return", "new", "DiscoveryStrategyFactory", "(", ")", "{", "@", "Override", "public", "Class", "<", "?", "extends", "DiscoveryStrategy", ">", "getDiscoveryStrategyType", "(", ")", "{", "return", "EurekaDiscoveryStrategy", ".", "class", ";", "}", "@", "Override", "public", "DiscoveryStrategy", "newDiscoveryStrategy", "(", "DiscoveryNode", "discoveryNode", ",", "ILogger", "logger", ",", "Map", "<", "String", ",", "Comparable", ">", "properties", ")", "{", "val", "eurekaDiscoveryStrategy", "=", "new", "EurekaDiscoveryStrategy", "(", "logger", ",", "emptyMap", "(", ")", ")", ";", "eurekaDiscoveryStrategy", ".", "setDiscoveryClient", "(", "discoveryClient", ")", ";", "eurekaDiscoveryStrategy", ".", "setHaselcastNodeServiceId", "(", "applicationName", ")", ";", "return", "eurekaDiscoveryStrategy", ";", "}", "@", "Override", "public", "Collection", "<", "PropertyDefinition", ">", "getConfigurationProperties", "(", ")", "{", "return", "null", ";", "}", "}", ";", "}", "}" ]
@author Artem Labazin <[email protected]> @since 01.12.2016
[ "@author", "Artem", "Labazin", "<xxlabaza@gmail", ".", "com", ">", "@since", "01", ".", "12", ".", "2016" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe04d25f4e3bc505ab3821f6a74f7e6e31692efd
ganadist/r8
src/test/java/com/android/tools/r8/jasmin/NameTestBase.java
[ "Apache-2.0", "BSD-3-Clause" ]
Java
TestString
// characters outside 0x20..0x7e.
characters outside 0x20..0x7e.
[ "characters", "outside", "0x20", "..", "0x7e", "." ]
static class TestString { private final String value; TestString(String value) { this.value = value; } String getValue() { return value; } @Override public String toString() { return StringUtils.toASCIIString(value); } }
[ "static", "class", "TestString", "{", "private", "final", "String", "value", ";", "TestString", "(", "String", "value", ")", "{", "this", ".", "value", "=", "value", ";", "}", "String", "getValue", "(", ")", "{", "return", "value", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "StringUtils", ".", "toASCIIString", "(", "value", ")", ";", "}", "}" ]
characters outside 0x20..0x7e.
[ "characters", "outside", "0x20", "..", "0x7e", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe04f5d5afd13d252d39e3cc100a69a4f7611fa7
CarlosUlisesOchoa/Juego-ruleta-de-imagenes-java-sqlite
src/juego_imagenes/AcercaDe.java
[ "MIT" ]
Java
AcercaDe
/** * * @author Uli Gibson */
@author Uli Gibson
[ "@author", "Uli", "Gibson" ]
public class AcercaDe extends javax.swing.JFrame { /** * Creates new form AcercaDe */ public AcercaDe() { initComponents(); setLang(1); } private void setLang(int id) { switch(id) { case 0: { //spanish lblTitle.setText("<html><center><font style=\"color: #5e9ca0;\" size=\"14\";>Acerca del desarrollador</font></center></html>"); lblDescription.setText("<html>Mi nombre es Carlos Ulises, soy estudiante de la carrera de ingeniería <br/> en sistemas computacionales, me encanta todo lo relacionado con la tecnología, <br/> especialmente el area del desarrollo web. Constantemente estoy intentando aprender <br/> nuevas tecnologías para poder mejorar mis habilidades en esa y otras areas.</html>"); lblDescription1.setText("<html>Si quieres modificar este proyecto, solo te pido conserves mis créditos, ¡ gracias !.</html>"); lblCopyright.setText("Todos los derechos reservados® copyright © 2010 - " + Calendar.getInstance().get(Calendar.YEAR)); lblENG.setForeground(new Color(51,102,255)); lblES.setForeground(new Color(102,102,102)); break; } case 1: { //english lblTitle.setText("<html><center><font style=\"color: #5e9ca0;\" size=\"14\";>About developer</font></center></html>"); lblDescription.setText("<html>My name is Carlos Ulises, I am student of software engineering career, <br/> I love everything related to technology and especially the development area. <br/> I am constantly learning more about the web development technologies for <br/> improve my skills in that area.</html>"); lblDescription1.setText("<html>If you want to modify this project, please keep my credits. Thank you!.</html>"); lblCopyright.setText("All rings reserved ® copyright © 2010 - " + Calendar.getInstance().get(Calendar.YEAR)); lblENG.setForeground(new Color(102,102,102)); lblES.setForeground(new Color(51,102,255)); break; } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); lblCopyright = new javax.swing.JLabel(); lblENG = new javax.swing.JLabel(); lblES = new javax.swing.JLabel(); lblDescription = new javax.swing.JLabel(); lblPhoto = new javax.swing.JLabel(); lblDescription1 = new javax.swing.JLabel(); lblWeb = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Acerca del desarrollador"); setResizable(false); lblTitle.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTitle.setText("<html><center><font style=\"color: #5e9ca0; font-size:32px;\">About developer</font></center></html>"); lblCopyright.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N lblCopyright.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblCopyright.setText("All rings reserved ® copyright © 2010 - 2019"); lblENG.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N lblENG.setForeground(new java.awt.Color(51, 102, 255)); lblENG.setText("English"); lblENG.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblENG.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblENGMouseClicked(evt); } }); lblES.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N lblES.setForeground(new java.awt.Color(102, 102, 102)); lblES.setText("Spanish"); lblES.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblES.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblESMouseClicked(evt); } }); lblDescription.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N lblDescription.setText("<html>Mi nombre es Carlos Ulises, soy estudiante de la carrera de ingeniería <br/>\nen sistemas computacionales, me encanta todo lo relacionado con la tecnología, <br/>\nespecialmente el area del desarrollo web. Constantemente estoy intentando aprender <br/> \nnuevas tecnologías para poder mejorar mis habilidades en esa y otras areas.</html>"); lblPhoto.setText("<html><img src=\"https://raw.githubusercontent.com/CarlosUlisesOchoa/Reloj-Analogo-Alarma/master/src/img/dev%20profile.png\" alt=\"Developer photo\"/></html>"); lblDescription1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N lblDescription1.setText("<html>Si quieres modificar este proyecto, solo te pido conserves mis créditos, ¡ gracias !.</html>"); lblWeb.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N lblWeb.setForeground(new java.awt.Color(0, 153, 255)); lblWeb.setText("www.carlosulises.ml"); lblWeb.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblWeb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblWebMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblDescription1, javax.swing.GroupLayout.PREFERRED_SIZE, 769, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(lblDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 811, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(688, 688, 688) .addComponent(lblES) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblENG))) .addGap(745, 745, 745)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lblTitle) .addComponent(lblCopyright, javax.swing.GroupLayout.DEFAULT_SIZE, 1177, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(497, 497, 497) .addComponent(lblWeb))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(lblPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblES) .addComponent(lblENG)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblDescription, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lblDescription1, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE) .addComponent(lblWeb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblCopyright)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 1181, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void lblESMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblESMouseClicked // TODO add your handling code here: setLang(0); }//GEN-LAST:event_lblESMouseClicked private void lblENGMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblENGMouseClicked // TODO add your handling code here: setLang(1); }//GEN-LAST:event_lblENGMouseClicked private void lblWebMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblWebMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblWebMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JLabel lblCopyright; private javax.swing.JLabel lblDescription; private javax.swing.JLabel lblDescription1; private javax.swing.JLabel lblENG; private javax.swing.JLabel lblES; private javax.swing.JLabel lblPhoto; private javax.swing.JLabel lblTitle; private javax.swing.JLabel lblWeb; // End of variables declaration//GEN-END:variables }
[ "public", "class", "AcercaDe", "extends", "javax", ".", "swing", ".", "JFrame", "{", "/**\n * Creates new form AcercaDe\n */", "public", "AcercaDe", "(", ")", "{", "initComponents", "(", ")", ";", "setLang", "(", "1", ")", ";", "}", "private", "void", "setLang", "(", "int", "id", ")", "{", "switch", "(", "id", ")", "{", "case", "0", ":", "{", "lblTitle", ".", "setText", "(", "\"", "<html><center><font style=", "\\\"", "color: #5e9ca0;", "\\\"", " size=", "\\\"", "14", "\\\"", ";>Acerca del desarrollador</font></center></html>", "\"", ")", ";", "lblDescription", ".", "setText", "(", "\"", "<html>Mi nombre es Carlos Ulises, soy estudiante de la carrera de ingeniería <br/> en sistemas computacionales, me encanta todo lo relacionado con la tecnología, <br/> especialmente el area del desarrollo web. Constantemente estoy intentando aprender <br/> nuevas tecnologías para poder mejorar mis habilidades en esa y otras areas.</html>\");", "", "", "", "lblDescription1", ".", "setText", "(", "\"", "<html>Si quieres modificar este proyecto, solo te pido conserves mis créditos, ¡ gracias !.</html>\")", ";", "", "", "lblCopyright", ".", "setText", "(", "\"", "Todos los derechos reservados® copyright © 2010 - \" ", "+", "C", "lendar.g", "e", "tInstance()", ".", "g", "e", "t(C", "a", "lendar.Y", "E", "AR))", ";", "", "", "lblENG", ".", "setForeground", "(", "new", "Color", "(", "51", ",", "102", ",", "255", ")", ")", ";", "lblES", ".", "setForeground", "(", "new", "Color", "(", "102", ",", "102", ",", "102", ")", ")", ";", "break", ";", "}", "case", "1", ":", "{", "lblTitle", ".", "setText", "(", "\"", "<html><center><font style=", "\\\"", "color: #5e9ca0;", "\\\"", " size=", "\\\"", "14", "\\\"", ";>About developer</font></center></html>", "\"", ")", ";", "lblDescription", ".", "setText", "(", "\"", "<html>My name is Carlos Ulises, I am student of software engineering career, <br/> I love everything related to technology and especially the development area. <br/> I am constantly learning more about the web development technologies for <br/> improve my skills in that area.</html>", "\"", ")", ";", "lblDescription1", ".", "setText", "(", "\"", "<html>If you want to modify this project, please keep my credits. Thank you!.</html>", "\"", ")", ";", "lblCopyright", ".", "setText", "(", "\"", "All rings reserved ® copyright © 2010 - \" ", "+", "C", "lendar.g", "e", "tInstance()", ".", "g", "e", "t(C", "a", "lendar.Y", "E", "AR))", ";", "", "", "lblENG", ".", "setForeground", "(", "new", "Color", "(", "102", ",", "102", ",", "102", ")", ")", ";", "lblES", ".", "setForeground", "(", "new", "Color", "(", "51", ",", "102", ",", "255", ")", ")", ";", "break", ";", "}", "}", "}", "/**\n * This method is called from within the constructor to initialize the form.\n * WARNING: Do NOT modify this code. The content of this method is always\n * regenerated by the Form Editor.\n */", "@", "SuppressWarnings", "(", "\"", "unchecked", "\"", ")", "private", "void", "initComponents", "(", ")", "{", "jPanel1", "=", "new", "javax", ".", "swing", ".", "JPanel", "(", ")", ";", "lblTitle", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblCopyright", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblENG", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblES", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblDescription", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblPhoto", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblDescription1", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "lblWeb", "=", "new", "javax", ".", "swing", ".", "JLabel", "(", ")", ";", "setDefaultCloseOperation", "(", "javax", ".", "swing", ".", "WindowConstants", ".", "DISPOSE_ON_CLOSE", ")", ";", "setTitle", "(", "\"", "Acerca del desarrollador", "\"", ")", ";", "setResizable", "(", "false", ")", ";", "lblTitle", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "24", ")", ")", ";", "lblTitle", ".", "setHorizontalAlignment", "(", "javax", ".", "swing", ".", "SwingConstants", ".", "CENTER", ")", ";", "lblTitle", ".", "setText", "(", "\"", "<html><center><font style=", "\\\"", "color: #5e9ca0; font-size:32px;", "\\\"", ">About developer</font></center></html>", "\"", ")", ";", "lblCopyright", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "20", ")", ")", ";", "lblCopyright", ".", "setHorizontalAlignment", "(", "javax", ".", "swing", ".", "SwingConstants", ".", "CENTER", ")", ";", "lblCopyright", ".", "setText", "(", "\"", "All rings reserved ® copyright © 2010 - 2019\")", ";", "", "", "lblENG", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "18", ")", ")", ";", "lblENG", ".", "setForeground", "(", "new", "java", ".", "awt", ".", "Color", "(", "51", ",", "102", ",", "255", ")", ")", ";", "lblENG", ".", "setText", "(", "\"", "English", "\"", ")", ";", "lblENG", ".", "setCursor", "(", "new", "java", ".", "awt", ".", "Cursor", "(", "java", ".", "awt", ".", "Cursor", ".", "HAND_CURSOR", ")", ")", ";", "lblENG", ".", "addMouseListener", "(", "new", "java", ".", "awt", ".", "event", ".", "MouseAdapter", "(", ")", "{", "public", "void", "mouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "lblENGMouseClicked", "(", "evt", ")", ";", "}", "}", ")", ";", "lblES", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "18", ")", ")", ";", "lblES", ".", "setForeground", "(", "new", "java", ".", "awt", ".", "Color", "(", "102", ",", "102", ",", "102", ")", ")", ";", "lblES", ".", "setText", "(", "\"", "Spanish", "\"", ")", ";", "lblES", ".", "setCursor", "(", "new", "java", ".", "awt", ".", "Cursor", "(", "java", ".", "awt", ".", "Cursor", ".", "HAND_CURSOR", ")", ")", ";", "lblES", ".", "addMouseListener", "(", "new", "java", ".", "awt", ".", "event", ".", "MouseAdapter", "(", ")", "{", "public", "void", "mouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "lblESMouseClicked", "(", "evt", ")", ";", "}", "}", ")", ";", "lblDescription", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "20", ")", ")", ";", "lblDescription", ".", "setText", "(", "\"", "<html>Mi nombre es Carlos Ulises, soy estudiante de la carrera de ingeniería <br/>\\", "ne", "n sistemas computacionales, me encanta todo lo relacionado con la tecnología, <br/>\\n", "es", "pecialmente el area del desarrollo web. Constantemente estoy intentando aprender <br/> \\n", "nu", "evas tecnologías para poder mejorar mis habilidades en esa y otras areas.</html>\");", "", "", "", "lblPhoto", ".", "setText", "(", "\"", "<html><img src=", "\\\"", "https://raw.githubusercontent.com/CarlosUlisesOchoa/Reloj-Analogo-Alarma/master/src/img/dev%20profile.png", "\\\"", " alt=", "\\\"", "Developer photo", "\\\"", "/></html>", "\"", ")", ";", "lblDescription1", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "20", ")", ")", ";", "lblDescription1", ".", "setText", "(", "\"", "<html>Si quieres modificar este proyecto, solo te pido conserves mis créditos, ¡ gracias !.</html>\")", ";", "", "", "lblWeb", ".", "setFont", "(", "new", "java", ".", "awt", ".", "Font", "(", "\"", "Tahoma", "\"", ",", "0", ",", "20", ")", ")", ";", "lblWeb", ".", "setForeground", "(", "new", "java", ".", "awt", ".", "Color", "(", "0", ",", "153", ",", "255", ")", ")", ";", "lblWeb", ".", "setText", "(", "\"", "www.carlosulises.ml", "\"", ")", ";", "lblWeb", ".", "setCursor", "(", "new", "java", ".", "awt", ".", "Cursor", "(", "java", ".", "awt", ".", "Cursor", ".", "HAND_CURSOR", ")", ")", ";", "lblWeb", ".", "addMouseListener", "(", "new", "java", ".", "awt", ".", "event", ".", "MouseAdapter", "(", ")", "{", "public", "void", "mouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "lblWebMouseClicked", "(", "evt", ")", ";", "}", "}", ")", ";", "javax", ".", "swing", ".", "GroupLayout", "jPanel1Layout", "=", "new", "javax", ".", "swing", ".", "GroupLayout", "(", "jPanel1", ")", ";", "jPanel1", ".", "setLayout", "(", "jPanel1Layout", ")", ";", "jPanel1Layout", ".", "setHorizontalGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "TRAILING", ",", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addContainerGap", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ".", "addComponent", "(", "lblPhoto", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addPreferredGap", "(", "javax", ".", "swing", ".", "LayoutStyle", ".", "ComponentPlacement", ".", "UNRELATED", ")", ".", "addComponent", "(", "lblDescription1", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "769", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ")", ".", "addGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "TRAILING", ",", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addGap", "(", "17", ",", "17", ",", "17", ")", ".", "addComponent", "(", "lblDescription", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "811", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ")", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addGap", "(", "688", ",", "688", ",", "688", ")", ".", "addComponent", "(", "lblES", ")", ".", "addPreferredGap", "(", "javax", ".", "swing", ".", "LayoutStyle", ".", "ComponentPlacement", ".", "RELATED", ")", ".", "addComponent", "(", "lblENG", ")", ")", ")", ".", "addGap", "(", "745", ",", "745", ",", "745", ")", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ",", "false", ")", ".", "addComponent", "(", "lblTitle", ")", ".", "addComponent", "(", "lblCopyright", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "1177", ",", "Short", ".", "MAX_VALUE", ")", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addGap", "(", "497", ",", "497", ",", "497", ")", ".", "addComponent", "(", "lblWeb", ")", ")", ")", ".", "addContainerGap", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ")", ")", ";", "jPanel1Layout", ".", "setVerticalGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addComponent", "(", "lblTitle", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "112", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addGap", "(", "18", ",", "18", ",", "18", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "TRAILING", ",", "false", ")", ".", "addComponent", "(", "lblPhoto", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createSequentialGroup", "(", ")", ".", "addGroup", "(", "jPanel1Layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "BASELINE", ")", ".", "addComponent", "(", "lblES", ")", ".", "addComponent", "(", "lblENG", ")", ")", ".", "addPreferredGap", "(", "javax", ".", "swing", ".", "LayoutStyle", ".", "ComponentPlacement", ".", "RELATED", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ".", "addComponent", "(", "lblDescription", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "196", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addGap", "(", "18", ",", "18", ",", "18", ")", ".", "addComponent", "(", "lblDescription1", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "61", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ")", ")", ".", "addPreferredGap", "(", "javax", ".", "swing", ".", "LayoutStyle", ".", "ComponentPlacement", ".", "RELATED", ",", "58", ",", "Short", ".", "MAX_VALUE", ")", ".", "addComponent", "(", "lblWeb", ")", ".", "addPreferredGap", "(", "javax", ".", "swing", ".", "LayoutStyle", ".", "ComponentPlacement", ".", "RELATED", ")", ".", "addComponent", "(", "lblCopyright", ")", ")", ")", ";", "javax", ".", "swing", ".", "GroupLayout", "layout", "=", "new", "javax", ".", "swing", ".", "GroupLayout", "(", "getContentPane", "(", ")", ")", ";", "getContentPane", "(", ")", ".", "setLayout", "(", "layout", ")", ";", "layout", ".", "setHorizontalGroup", "(", "layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "layout", ".", "createSequentialGroup", "(", ")", ".", "addContainerGap", "(", ")", ".", "addComponent", "(", "jPanel1", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "1181", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addContainerGap", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ")", ")", ";", "layout", ".", "setVerticalGroup", "(", "layout", ".", "createParallelGroup", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "Alignment", ".", "LEADING", ")", ".", "addGroup", "(", "layout", ".", "createSequentialGroup", "(", ")", ".", "addContainerGap", "(", ")", ".", "addComponent", "(", "jPanel1", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "javax", ".", "swing", ".", "GroupLayout", ".", "PREFERRED_SIZE", ")", ".", "addContainerGap", "(", "javax", ".", "swing", ".", "GroupLayout", ".", "DEFAULT_SIZE", ",", "Short", ".", "MAX_VALUE", ")", ")", ")", ";", "pack", "(", ")", ";", "}", "private", "void", "lblESMouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "setLang", "(", "0", ")", ";", "}", "private", "void", "lblENGMouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "setLang", "(", "1", ")", ";", "}", "private", "void", "lblWebMouseClicked", "(", "java", ".", "awt", ".", "event", ".", "MouseEvent", "evt", ")", "{", "}", "private", "javax", ".", "swing", ".", "JPanel", "jPanel1", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblCopyright", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblDescription", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblDescription1", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblENG", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblES", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblPhoto", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblTitle", ";", "private", "javax", ".", "swing", ".", "JLabel", "lblWeb", ";", "}" ]
@author Uli Gibson
[ "@author", "Uli", "Gibson" ]
[ "//spanish", "//english", "// <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// </editor-fold>//GEN-END:initComponents", "//GEN-FIRST:event_lblESMouseClicked", "// TODO add your handling code here:", "//GEN-LAST:event_lblESMouseClicked", "//GEN-FIRST:event_lblENGMouseClicked", "// TODO add your handling code here:", "//GEN-LAST:event_lblENGMouseClicked", "//GEN-FIRST:event_lblWebMouseClicked", "// TODO add your handling code here:", "//GEN-LAST:event_lblWebMouseClicked", "// Variables declaration - do not modify//GEN-BEGIN:variables", "// End of variables declaration//GEN-END:variables" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe055d82556f71c949e508c261bcab6d667e612f
DUDEbehindDUDE/TNFC_Mod
src/main/java/tnfcmod/qfc/api/module/ModuleLoadedEvent.java
[ "MIT" ]
Java
ModuleLoadedEvent
/** * Canceling this event will result in the module being ignored completely. */
Canceling this event will result in the module being ignored completely.
[ "Canceling", "this", "event", "will", "result", "in", "the", "module", "being", "ignored", "completely", "." ]
@Cancelable public class ModuleLoadedEvent extends Event { private final IModule module; public ModuleLoadedEvent(IModule module) { this.module = module; } public IModule getModule() { return module; } }
[ "@", "Cancelable", "public", "class", "ModuleLoadedEvent", "extends", "Event", "{", "private", "final", "IModule", "module", ";", "public", "ModuleLoadedEvent", "(", "IModule", "module", ")", "{", "this", ".", "module", "=", "module", ";", "}", "public", "IModule", "getModule", "(", ")", "{", "return", "module", ";", "}", "}" ]
Canceling this event will result in the module being ignored completely.
[ "Canceling", "this", "event", "will", "result", "in", "the", "module", "being", "ignored", "completely", "." ]
[]
[ { "param": "Event", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Event", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe0a4fb0ae10fe359f2d3da39938bb5d5cdda5bc
NoYouShutup/CryptMeme
CryptMeme/core/java/src/net/i2p/util/Log.java
[ "MIT" ]
Java
Log
/** * Wrapper class for whatever logging system I2P uses. This class should be * instantiated and kept as a variable for each class it is used by, ala: * <code>private final Log _log = context.logManager().getLog(MyClassName.class);</code> * * If there is anything in here that doesn't make sense, turn off your computer * and go fly a kite. * * * @author jrandom */
Wrapper class for whatever logging system I2P uses. This class should be instantiated and kept as a variable for each class it is used by, ala: private final Log _log = context.logManager().getLog(MyClassName.class). If there is anything in here that doesn't make sense, turn off your computer and go fly a kite. @author jrandom
[ "Wrapper", "class", "for", "whatever", "logging", "system", "I2P", "uses", ".", "This", "class", "should", "be", "instantiated", "and", "kept", "as", "a", "variable", "for", "each", "class", "it", "is", "used", "by", "ala", ":", "private", "final", "Log", "_log", "=", "context", ".", "logManager", "()", ".", "getLog", "(", "MyClassName", ".", "class", ")", ".", "If", "there", "is", "anything", "in", "here", "that", "doesn", "'", "t", "make", "sense", "turn", "off", "your", "computer", "and", "go", "fly", "a", "kite", ".", "@author", "jrandom" ]
public class Log { private final Class<?> _class; private final String _className; private final String _name; private int _minPriority; private final LogScope _scope; private final LogManager _manager; public final static int DEBUG = 10; public final static int INFO = 20; public final static int WARN = 30; public final static int ERROR = 40; public final static int CRIT = 50; public final static String STR_DEBUG = "DEBUG"; public final static String STR_INFO = "INFO"; public final static String STR_WARN = "WARN"; public final static String STR_ERROR = "ERROR"; public final static String STR_CRIT = "CRIT"; public static int getLevel(String level) { if (level == null) return Log.CRIT; level = level.toUpperCase(Locale.US); if (STR_DEBUG.startsWith(level)) return DEBUG; if (STR_INFO.startsWith(level)) return INFO; if (STR_WARN.startsWith(level)) return WARN; if (STR_ERROR.startsWith(level)) return ERROR; if (STR_CRIT.startsWith(level)) return CRIT; return CRIT; } public static String toLevelString(int level) { switch (level) { case DEBUG: return STR_DEBUG; case INFO: return STR_INFO; case WARN: return STR_WARN; case ERROR: return STR_ERROR; case CRIT: return STR_CRIT; } return (level > CRIT ? STR_CRIT : STR_DEBUG); } /** * Warning - not recommended. * Use I2PAppContext.getGlobalContext().logManager().getLog(cls) */ public Log(Class<?> cls) { this(I2PAppContext.getGlobalContext().logManager(), cls, null); _manager.addLog(this); } /** * Warning - not recommended. * Use I2PAppContext.getGlobalContext().logManager().getLog(name) */ public Log(String name) { this(I2PAppContext.getGlobalContext().logManager(), null, name); _manager.addLog(this); } Log(LogManager manager, Class<?> cls) { this(manager, cls, null); } Log(LogManager manager, String name) { this(manager, null, name); } Log(LogManager manager, Class<?> cls, String name) { _manager = manager; _class = cls; _className = cls != null ? cls.getName() : null; _name = name; _minPriority = DEBUG; _scope = new LogScope(name, cls); //_manager.addRecord(new LogRecord(Log.class, null, Thread.currentThread().getName(), Log.DEBUG, // "Log created with manager " + manager + " for class " + cls, null)); } public void log(int priority, String msg) { if (priority >= _minPriority) { _manager.addRecord(new LogRecord(_class, _name, Thread.currentThread().getName(), priority, msg, null)); } } public void log(int priority, String msg, Throwable t) { // Boost the priority of NPE and friends so they get seen and reported //if (t != null && t instanceof RuntimeException && !(t instanceof IllegalArgumentException)) // priority = CRIT; if (priority >= _minPriority) { _manager.addRecord(new LogRecord(_class, _name, Thread.currentThread().getName(), priority, msg, t)); } } /** * Always log this messge with the given priority, ignoring current minimum priority level. * This allows an INFO message about changing port numbers, for example, to always be logged. * @since 0.8.2 */ public void logAlways(int priority, String msg) { _manager.addRecord(new LogRecord(_class, _name, Thread.currentThread().getName(), priority, msg, null)); } public void debug(String msg) { log(DEBUG, msg); } public void debug(String msg, Throwable t) { log(DEBUG, msg, t); } public void info(String msg) { log(INFO, msg); } public void info(String msg, Throwable t) { log(INFO, msg, t); } public void warn(String msg) { log(WARN, msg); } public void warn(String msg, Throwable t) { log(WARN, msg, t); } public void error(String msg) { log(ERROR, msg); } public void error(String msg, Throwable t) { log(ERROR, msg, t); } public int getMinimumPriority() { return _minPriority; } public void setMinimumPriority(int priority) { _minPriority = priority; //_manager.addRecord(new LogRecord(Log.class, null, Thread.currentThread().getName(), Log.DEBUG, // "Log with manager " + _manager + " for class " + _class // + " new priority " + toLevelString(priority), null)); } public boolean shouldLog(int priority) { return priority >= _minPriority; } /** @since 0.9.20 */ public boolean shouldDebug() { return shouldLog(DEBUG); } /** @since 0.9.20 */ public boolean shouldInfo() { return shouldLog(INFO); } /** @since 0.9.20 */ public boolean shouldWarn() { return shouldLog(WARN); } /** @since 0.9.20 */ public boolean shouldError() { return shouldLog(ERROR); } /** * logs a loop when closing a resource with level INFO * This method is for debugging purposes only and * as such subject to change or removal w/o notice. * @param desc vararg description * @since 0.9.8 */ public void logCloseLoop(Object... desc) { logCloseLoop(Log.INFO, desc); } /** * Logs a close loop when closing a resource * This method is for debugging purposes only and * as such subject to change or removal w/o notice. * @param desc vararg description of the resource * @param level level at which to log * @since 0.9.8 */ public void logCloseLoop(int level, Object... desc) { if (!shouldLog(level)) return; // catenate all toString()s StringBuilder builder = new StringBuilder(); builder.append("close() loop in"); for (Object o : desc) { builder.append(" "); builder.append(String.valueOf(o)); } Exception e = new Exception("check stack trace"); log(level,builder.toString(),e); } public String getName() { if (_className != null) return _className; return _name; } /** @return the LogScope (private class) */ public Object getScope() { return _scope; } static String getScope(String name, Class<?> cls) { if ( (name == null) && (cls == null) ) return "f00"; if (cls == null) return name; if (name == null) return cls.getName(); return name + "" + cls.getName(); } private static final class LogScope { private final String _scopeCache; public LogScope(String name, Class<?> cls) { _scopeCache = getScope(name, cls); } @Override public int hashCode() { return _scopeCache.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj instanceof LogScope) { LogScope s = (LogScope)obj; return s._scopeCache.equals(_scopeCache); } else if (obj instanceof String) { return obj.equals(_scopeCache); } return false; } } }
[ "public", "class", "Log", "{", "private", "final", "Class", "<", "?", ">", "_class", ";", "private", "final", "String", "_className", ";", "private", "final", "String", "_name", ";", "private", "int", "_minPriority", ";", "private", "final", "LogScope", "_scope", ";", "private", "final", "LogManager", "_manager", ";", "public", "final", "static", "int", "DEBUG", "=", "10", ";", "public", "final", "static", "int", "INFO", "=", "20", ";", "public", "final", "static", "int", "WARN", "=", "30", ";", "public", "final", "static", "int", "ERROR", "=", "40", ";", "public", "final", "static", "int", "CRIT", "=", "50", ";", "public", "final", "static", "String", "STR_DEBUG", "=", "\"", "DEBUG", "\"", ";", "public", "final", "static", "String", "STR_INFO", "=", "\"", "INFO", "\"", ";", "public", "final", "static", "String", "STR_WARN", "=", "\"", "WARN", "\"", ";", "public", "final", "static", "String", "STR_ERROR", "=", "\"", "ERROR", "\"", ";", "public", "final", "static", "String", "STR_CRIT", "=", "\"", "CRIT", "\"", ";", "public", "static", "int", "getLevel", "(", "String", "level", ")", "{", "if", "(", "level", "==", "null", ")", "return", "Log", ".", "CRIT", ";", "level", "=", "level", ".", "toUpperCase", "(", "Locale", ".", "US", ")", ";", "if", "(", "STR_DEBUG", ".", "startsWith", "(", "level", ")", ")", "return", "DEBUG", ";", "if", "(", "STR_INFO", ".", "startsWith", "(", "level", ")", ")", "return", "INFO", ";", "if", "(", "STR_WARN", ".", "startsWith", "(", "level", ")", ")", "return", "WARN", ";", "if", "(", "STR_ERROR", ".", "startsWith", "(", "level", ")", ")", "return", "ERROR", ";", "if", "(", "STR_CRIT", ".", "startsWith", "(", "level", ")", ")", "return", "CRIT", ";", "return", "CRIT", ";", "}", "public", "static", "String", "toLevelString", "(", "int", "level", ")", "{", "switch", "(", "level", ")", "{", "case", "DEBUG", ":", "return", "STR_DEBUG", ";", "case", "INFO", ":", "return", "STR_INFO", ";", "case", "WARN", ":", "return", "STR_WARN", ";", "case", "ERROR", ":", "return", "STR_ERROR", ";", "case", "CRIT", ":", "return", "STR_CRIT", ";", "}", "return", "(", "level", ">", "CRIT", "?", "STR_CRIT", ":", "STR_DEBUG", ")", ";", "}", "/**\n * Warning - not recommended.\n * Use I2PAppContext.getGlobalContext().logManager().getLog(cls)\n */", "public", "Log", "(", "Class", "<", "?", ">", "cls", ")", "{", "this", "(", "I2PAppContext", ".", "getGlobalContext", "(", ")", ".", "logManager", "(", ")", ",", "cls", ",", "null", ")", ";", "_manager", ".", "addLog", "(", "this", ")", ";", "}", "/**\n * Warning - not recommended.\n * Use I2PAppContext.getGlobalContext().logManager().getLog(name)\n */", "public", "Log", "(", "String", "name", ")", "{", "this", "(", "I2PAppContext", ".", "getGlobalContext", "(", ")", ".", "logManager", "(", ")", ",", "null", ",", "name", ")", ";", "_manager", ".", "addLog", "(", "this", ")", ";", "}", "Log", "(", "LogManager", "manager", ",", "Class", "<", "?", ">", "cls", ")", "{", "this", "(", "manager", ",", "cls", ",", "null", ")", ";", "}", "Log", "(", "LogManager", "manager", ",", "String", "name", ")", "{", "this", "(", "manager", ",", "null", ",", "name", ")", ";", "}", "Log", "(", "LogManager", "manager", ",", "Class", "<", "?", ">", "cls", ",", "String", "name", ")", "{", "_manager", "=", "manager", ";", "_class", "=", "cls", ";", "_className", "=", "cls", "!=", "null", "?", "cls", ".", "getName", "(", ")", ":", "null", ";", "_name", "=", "name", ";", "_minPriority", "=", "DEBUG", ";", "_scope", "=", "new", "LogScope", "(", "name", ",", "cls", ")", ";", "}", "public", "void", "log", "(", "int", "priority", ",", "String", "msg", ")", "{", "if", "(", "priority", ">=", "_minPriority", ")", "{", "_manager", ".", "addRecord", "(", "new", "LogRecord", "(", "_class", ",", "_name", ",", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ",", "priority", ",", "msg", ",", "null", ")", ")", ";", "}", "}", "public", "void", "log", "(", "int", "priority", ",", "String", "msg", ",", "Throwable", "t", ")", "{", "if", "(", "priority", ">=", "_minPriority", ")", "{", "_manager", ".", "addRecord", "(", "new", "LogRecord", "(", "_class", ",", "_name", ",", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ",", "priority", ",", "msg", ",", "t", ")", ")", ";", "}", "}", "/**\n * Always log this messge with the given priority, ignoring current minimum priority level.\n * This allows an INFO message about changing port numbers, for example, to always be logged.\n * @since 0.8.2\n */", "public", "void", "logAlways", "(", "int", "priority", ",", "String", "msg", ")", "{", "_manager", ".", "addRecord", "(", "new", "LogRecord", "(", "_class", ",", "_name", ",", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ",", "priority", ",", "msg", ",", "null", ")", ")", ";", "}", "public", "void", "debug", "(", "String", "msg", ")", "{", "log", "(", "DEBUG", ",", "msg", ")", ";", "}", "public", "void", "debug", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "log", "(", "DEBUG", ",", "msg", ",", "t", ")", ";", "}", "public", "void", "info", "(", "String", "msg", ")", "{", "log", "(", "INFO", ",", "msg", ")", ";", "}", "public", "void", "info", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "log", "(", "INFO", ",", "msg", ",", "t", ")", ";", "}", "public", "void", "warn", "(", "String", "msg", ")", "{", "log", "(", "WARN", ",", "msg", ")", ";", "}", "public", "void", "warn", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "log", "(", "WARN", ",", "msg", ",", "t", ")", ";", "}", "public", "void", "error", "(", "String", "msg", ")", "{", "log", "(", "ERROR", ",", "msg", ")", ";", "}", "public", "void", "error", "(", "String", "msg", ",", "Throwable", "t", ")", "{", "log", "(", "ERROR", ",", "msg", ",", "t", ")", ";", "}", "public", "int", "getMinimumPriority", "(", ")", "{", "return", "_minPriority", ";", "}", "public", "void", "setMinimumPriority", "(", "int", "priority", ")", "{", "_minPriority", "=", "priority", ";", "}", "public", "boolean", "shouldLog", "(", "int", "priority", ")", "{", "return", "priority", ">=", "_minPriority", ";", "}", "/** @since 0.9.20 */", "public", "boolean", "shouldDebug", "(", ")", "{", "return", "shouldLog", "(", "DEBUG", ")", ";", "}", "/** @since 0.9.20 */", "public", "boolean", "shouldInfo", "(", ")", "{", "return", "shouldLog", "(", "INFO", ")", ";", "}", "/** @since 0.9.20 */", "public", "boolean", "shouldWarn", "(", ")", "{", "return", "shouldLog", "(", "WARN", ")", ";", "}", "/** @since 0.9.20 */", "public", "boolean", "shouldError", "(", ")", "{", "return", "shouldLog", "(", "ERROR", ")", ";", "}", "/**\n * logs a loop when closing a resource with level INFO\n * This method is for debugging purposes only and \n * as such subject to change or removal w/o notice.\n * @param desc vararg description\n * @since 0.9.8\n */", "public", "void", "logCloseLoop", "(", "Object", "...", "desc", ")", "{", "logCloseLoop", "(", "Log", ".", "INFO", ",", "desc", ")", ";", "}", "/**\n * Logs a close loop when closing a resource\n * This method is for debugging purposes only and \n * as such subject to change or removal w/o notice.\n * @param desc vararg description of the resource\n * @param level level at which to log\n * @since 0.9.8\n */", "public", "void", "logCloseLoop", "(", "int", "level", ",", "Object", "...", "desc", ")", "{", "if", "(", "!", "shouldLog", "(", "level", ")", ")", "return", ";", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "\"", "close() loop in", "\"", ")", ";", "for", "(", "Object", "o", ":", "desc", ")", "{", "builder", ".", "append", "(", "\"", " ", "\"", ")", ";", "builder", ".", "append", "(", "String", ".", "valueOf", "(", "o", ")", ")", ";", "}", "Exception", "e", "=", "new", "Exception", "(", "\"", "check stack trace", "\"", ")", ";", "log", "(", "level", ",", "builder", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "public", "String", "getName", "(", ")", "{", "if", "(", "_className", "!=", "null", ")", "return", "_className", ";", "return", "_name", ";", "}", "/** @return the LogScope (private class) */", "public", "Object", "getScope", "(", ")", "{", "return", "_scope", ";", "}", "static", "String", "getScope", "(", "String", "name", ",", "Class", "<", "?", ">", "cls", ")", "{", "if", "(", "(", "name", "==", "null", ")", "&&", "(", "cls", "==", "null", ")", ")", "return", "\"", "f00", "\"", ";", "if", "(", "cls", "==", "null", ")", "return", "name", ";", "if", "(", "name", "==", "null", ")", "return", "cls", ".", "getName", "(", ")", ";", "return", "name", "+", "\"", "\"", "+", "cls", ".", "getName", "(", ")", ";", "}", "private", "static", "final", "class", "LogScope", "{", "private", "final", "String", "_scopeCache", ";", "public", "LogScope", "(", "String", "name", ",", "Class", "<", "?", ">", "cls", ")", "{", "_scopeCache", "=", "getScope", "(", "name", ",", "cls", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "_scopeCache", ".", "hashCode", "(", ")", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "obj", "instanceof", "LogScope", ")", "{", "LogScope", "s", "=", "(", "LogScope", ")", "obj", ";", "return", "s", ".", "_scopeCache", ".", "equals", "(", "_scopeCache", ")", ";", "}", "else", "if", "(", "obj", "instanceof", "String", ")", "{", "return", "obj", ".", "equals", "(", "_scopeCache", ")", ";", "}", "return", "false", ";", "}", "}", "}" ]
Wrapper class for whatever logging system I2P uses.
[ "Wrapper", "class", "for", "whatever", "logging", "system", "I2P", "uses", "." ]
[ "//_manager.addRecord(new LogRecord(Log.class, null, Thread.currentThread().getName(), Log.DEBUG, ", "// \"Log created with manager \" + manager + \" for class \" + cls, null));", "// Boost the priority of NPE and friends so they get seen and reported", "//if (t != null && t instanceof RuntimeException && !(t instanceof IllegalArgumentException))", "// priority = CRIT;", "//_manager.addRecord(new LogRecord(Log.class, null, Thread.currentThread().getName(), Log.DEBUG, ", "// \"Log with manager \" + _manager + \" for class \" + _class ", "// + \" new priority \" + toLevelString(priority), null));", "// catenate all toString()s" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe0cb2d00f5abdabea4db0ecc8dcbdfdda1441bf
bsuscavage/carina
archetype/src/main/resources/archetype-resources/src/test/java/carina/demo/WebSampleSingleDriver.java
[ "Apache-2.0" ]
Java
WebSampleSingleDriver
/** * This sample shows how create Web test with dependent methods which shares existing driver between methods. * * @author qpsdemo */
This sample shows how create Web test with dependent methods which shares existing driver between methods. @author qpsdemo
[ "This", "sample", "shows", "how", "create", "Web", "test", "with", "dependent", "methods", "which", "shares", "existing", "driver", "between", "methods", ".", "@author", "qpsdemo" ]
public class WebSampleSingleDriver implements IAbstractTest { HomePage homePage = null; CompareModelsPage comparePage = null; List<ModelSpecs> specs = new ArrayList<>(); @BeforeSuite public void startDriver() { // Open GSM Arena home page and verify page is opened homePage = new HomePage(getDriver()); } @Test @MethodOwner(owner = "qpsdemo") @TestLabel(name = "feature", value = {"web", "regression"}) public void testOpenPage() { homePage.open(); Assert.assertTrue(homePage.isPageOpened(), "Home page is not opened"); } @Test(dependsOnMethods="testOpenPage") //for dependent tests Carina keeps driver sessions by default @MethodOwner(owner = "qpsdemo") @TestLabel(name = "feature", value = {"web", "regression"}) public void testOpenCompare() { // Open GSM Arena home page and verify page is opened // Open model compare page FooterMenu footerMenu = homePage.getFooterMenu(); Assert.assertTrue(footerMenu.isUIObjectPresent(2), "Footer menu wasn't found!"); comparePage = footerMenu.openComparePage(); } @Test(dependsOnMethods="testOpenCompare") //for dependent tests Carina keeps driver sessions by default @MethodOwner(owner = "qpsdemo") @TestLabel(name = "feature", value = {"web", "regression"}) public void testReadSpecs() { // Compare 3 models specs = comparePage.compareModels("Samsung Galaxy J3", "Samsung Galaxy J5", "Samsung Galaxy J7 Pro"); } @Test(dependsOnMethods="testReadSpecs") //for dependent tests Carina keeps driver sessions by default @MethodOwner(owner = "qpsdemo") @TestLabel(name = "feature", value = {"web", "acceptance"}) public void testCompareModels() { // Verify model announced dates Assert.assertEquals(specs.get(0).readSpec(SpecType.ANNOUNCED), "2016, March 31"); Assert.assertEquals(specs.get(1).readSpec(SpecType.ANNOUNCED), "2015, June 19"); Assert.assertEquals(specs.get(2).readSpec(SpecType.ANNOUNCED), "2017, June"); } }
[ "public", "class", "WebSampleSingleDriver", "implements", "IAbstractTest", "{", "HomePage", "homePage", "=", "null", ";", "CompareModelsPage", "comparePage", "=", "null", ";", "List", "<", "ModelSpecs", ">", "specs", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "@", "BeforeSuite", "public", "void", "startDriver", "(", ")", "{", "homePage", "=", "new", "HomePage", "(", "getDriver", "(", ")", ")", ";", "}", "@", "Test", "@", "MethodOwner", "(", "owner", "=", "\"", "qpsdemo", "\"", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "regression", "\"", "}", ")", "public", "void", "testOpenPage", "(", ")", "{", "homePage", ".", "open", "(", ")", ";", "Assert", ".", "assertTrue", "(", "homePage", ".", "isPageOpened", "(", ")", ",", "\"", "Home page is not opened", "\"", ")", ";", "}", "@", "Test", "(", "dependsOnMethods", "=", "\"", "testOpenPage", "\"", ")", "@", "MethodOwner", "(", "owner", "=", "\"", "qpsdemo", "\"", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "regression", "\"", "}", ")", "public", "void", "testOpenCompare", "(", ")", "{", "FooterMenu", "footerMenu", "=", "homePage", ".", "getFooterMenu", "(", ")", ";", "Assert", ".", "assertTrue", "(", "footerMenu", ".", "isUIObjectPresent", "(", "2", ")", ",", "\"", "Footer menu wasn't found!", "\"", ")", ";", "comparePage", "=", "footerMenu", ".", "openComparePage", "(", ")", ";", "}", "@", "Test", "(", "dependsOnMethods", "=", "\"", "testOpenCompare", "\"", ")", "@", "MethodOwner", "(", "owner", "=", "\"", "qpsdemo", "\"", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "regression", "\"", "}", ")", "public", "void", "testReadSpecs", "(", ")", "{", "specs", "=", "comparePage", ".", "compareModels", "(", "\"", "Samsung Galaxy J3", "\"", ",", "\"", "Samsung Galaxy J5", "\"", ",", "\"", "Samsung Galaxy J7 Pro", "\"", ")", ";", "}", "@", "Test", "(", "dependsOnMethods", "=", "\"", "testReadSpecs", "\"", ")", "@", "MethodOwner", "(", "owner", "=", "\"", "qpsdemo", "\"", ")", "@", "TestLabel", "(", "name", "=", "\"", "feature", "\"", ",", "value", "=", "{", "\"", "web", "\"", ",", "\"", "acceptance", "\"", "}", ")", "public", "void", "testCompareModels", "(", ")", "{", "Assert", ".", "assertEquals", "(", "specs", ".", "get", "(", "0", ")", ".", "readSpec", "(", "SpecType", ".", "ANNOUNCED", ")", ",", "\"", "2016, March 31", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "specs", ".", "get", "(", "1", ")", ".", "readSpec", "(", "SpecType", ".", "ANNOUNCED", ")", ",", "\"", "2015, June 19", "\"", ")", ";", "Assert", ".", "assertEquals", "(", "specs", ".", "get", "(", "2", ")", ".", "readSpec", "(", "SpecType", ".", "ANNOUNCED", ")", ",", "\"", "2017, June", "\"", ")", ";", "}", "}" ]
This sample shows how create Web test with dependent methods which shares existing driver between methods.
[ "This", "sample", "shows", "how", "create", "Web", "test", "with", "dependent", "methods", "which", "shares", "existing", "driver", "between", "methods", "." ]
[ "// Open GSM Arena home page and verify page is opened", "//for dependent tests Carina keeps driver sessions by default", "// Open GSM Arena home page and verify page is opened", "// Open model compare page", "//for dependent tests Carina keeps driver sessions by default", "// Compare 3 models", "//for dependent tests Carina keeps driver sessions by default", "// Verify model announced dates" ]
[ { "param": "IAbstractTest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IAbstractTest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe0dc8c5cd8792f1a5816e8945b77fd39731f26a
corfeur12/rp-shared
src/rp/config/WheeledRobotConfiguration.java
[ "MIT" ]
Java
WheeledRobotConfiguration
/** * A class to store configuration information for a wheeled robot. You could * subclass this to also contain information about sensor ports. * * @author Nick Hawes * */
A class to store configuration information for a wheeled robot. You could subclass this to also contain information about sensor ports. @author Nick Hawes
[ "A", "class", "to", "store", "configuration", "information", "for", "a", "wheeled", "robot", ".", "You", "could", "subclass", "this", "to", "also", "contain", "information", "about", "sensor", "ports", ".", "@author", "Nick", "Hawes" ]
public class WheeledRobotConfiguration extends MobileRobotConfiguration implements WheeledRobotDescription { private final float m_wheelDiameter; private final RegulatedMotor m_leftWheel; final RegulatedMotor m_rightWheel; public float getWheelDiameter() { return m_wheelDiameter; } public float getTrackWidth() { return m_trackWidth; } public RegulatedMotor getLeftWheel() { return m_leftWheel; } public WheeledRobotConfiguration(float _wheelDiameter, float _trackWidth, float _robotLength, RegulatedMotor _leftWheel, RegulatedMotor _rightWheel) { super(_trackWidth, _robotLength); m_wheelDiameter = _wheelDiameter; m_leftWheel = _leftWheel; m_rightWheel = _rightWheel; } @Override public RegulatedMotor getRightWheel() { return m_rightWheel; } }
[ "public", "class", "WheeledRobotConfiguration", "extends", "MobileRobotConfiguration", "implements", "WheeledRobotDescription", "{", "private", "final", "float", "m_wheelDiameter", ";", "private", "final", "RegulatedMotor", "m_leftWheel", ";", "final", "RegulatedMotor", "m_rightWheel", ";", "public", "float", "getWheelDiameter", "(", ")", "{", "return", "m_wheelDiameter", ";", "}", "public", "float", "getTrackWidth", "(", ")", "{", "return", "m_trackWidth", ";", "}", "public", "RegulatedMotor", "getLeftWheel", "(", ")", "{", "return", "m_leftWheel", ";", "}", "public", "WheeledRobotConfiguration", "(", "float", "_wheelDiameter", ",", "float", "_trackWidth", ",", "float", "_robotLength", ",", "RegulatedMotor", "_leftWheel", ",", "RegulatedMotor", "_rightWheel", ")", "{", "super", "(", "_trackWidth", ",", "_robotLength", ")", ";", "m_wheelDiameter", "=", "_wheelDiameter", ";", "m_leftWheel", "=", "_leftWheel", ";", "m_rightWheel", "=", "_rightWheel", ";", "}", "@", "Override", "public", "RegulatedMotor", "getRightWheel", "(", ")", "{", "return", "m_rightWheel", ";", "}", "}" ]
A class to store configuration information for a wheeled robot.
[ "A", "class", "to", "store", "configuration", "information", "for", "a", "wheeled", "robot", "." ]
[]
[ { "param": "MobileRobotConfiguration", "type": null }, { "param": "WheeledRobotDescription", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MobileRobotConfiguration", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "WheeledRobotDescription", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe0e75f98395a5bdd9e71f551e9c8baeeccc3b06
CK35/happy-chameleon
jar/src/main/java/de/ck35/raspberry/happy/chameleon/configuration/JpaConfiguration.java
[ "Apache-2.0" ]
Java
JpaConfiguration
/** * Main configuration for all JPA aspects. Couples Eclipse Link with Spring Data JPA. * * @author Christian Kaspari * @since 1.0.0 */
Main configuration for all JPA aspects. Couples Eclipse Link with Spring Data JPA. @author Christian Kaspari @since 1.0.0
[ "Main", "configuration", "for", "all", "JPA", "aspects", ".", "Couples", "Eclipse", "Link", "with", "Spring", "Data", "JPA", ".", "@author", "Christian", "Kaspari", "@since", "1", ".", "0", ".", "0" ]
@Configuration @EnableJpaRepositories(basePackages="de.ck35.raspberry.happy.chameleon.terrarium.jpa", considerNestedRepositories=true) @ComponentScan("de.ck35.raspberry.happy.chameleon.terrarium.jpa") public class JpaConfiguration { @Autowired Environment env; @Autowired AutowireCapableBeanFactory beanFactory; @Autowired DataSource dataSource; @Bean public SpringEntityListener SpringEntityListener() { SpringEntityListener listener = SpringEntityListener.get(); listener.setBeanFactory(beanFactory); return listener; } @Bean protected Map<String, Object> getVendorProperties() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put(PersistenceUnitProperties.WEAVING, Boolean.FALSE.toString()); map.put(PersistenceUnitProperties.LOGGING_LEVEL, "FINE"); return map; } @Bean protected EclipseLinkJpaVendorAdapter jpaVendorAdapter() { EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter(); adapter.setDatabase(Database.MYSQL); adapter.setShowSql(true); adapter.setGenerateDdl(false); return adapter; } @Bean public EntityManagerFactoryBuilder entityManagerFactoryBuilder() { EntityManagerFactoryBuilder builder = new EntityManagerFactoryBuilder(jpaVendorAdapter(), Collections.emptyMap(), null); return builder; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { Map<String, Object> vendorProperties = getVendorProperties(); return entityManagerFactoryBuilder().dataSource(dataSource) .packages("de.ck35.raspberry.happy.chameleon.terrarium.jpa") .properties(vendorProperties) .jta(false) .build(); } @Bean({"transactionManager", "txManager"}) public PlatformTransactionManager transactionManager() { return new JpaTransactionManager(entityManagerFactory().getObject()); } }
[ "@", "Configuration", "@", "EnableJpaRepositories", "(", "basePackages", "=", "\"", "de.ck35.raspberry.happy.chameleon.terrarium.jpa", "\"", ",", "considerNestedRepositories", "=", "true", ")", "@", "ComponentScan", "(", "\"", "de.ck35.raspberry.happy.chameleon.terrarium.jpa", "\"", ")", "public", "class", "JpaConfiguration", "{", "@", "Autowired", "Environment", "env", ";", "@", "Autowired", "AutowireCapableBeanFactory", "beanFactory", ";", "@", "Autowired", "DataSource", "dataSource", ";", "@", "Bean", "public", "SpringEntityListener", "SpringEntityListener", "(", ")", "{", "SpringEntityListener", "listener", "=", "SpringEntityListener", ".", "get", "(", ")", ";", "listener", ".", "setBeanFactory", "(", "beanFactory", ")", ";", "return", "listener", ";", "}", "@", "Bean", "protected", "Map", "<", "String", ",", "Object", ">", "getVendorProperties", "(", ")", "{", "HashMap", "<", "String", ",", "Object", ">", "map", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "map", ".", "put", "(", "PersistenceUnitProperties", ".", "WEAVING", ",", "Boolean", ".", "FALSE", ".", "toString", "(", ")", ")", ";", "map", ".", "put", "(", "PersistenceUnitProperties", ".", "LOGGING_LEVEL", ",", "\"", "FINE", "\"", ")", ";", "return", "map", ";", "}", "@", "Bean", "protected", "EclipseLinkJpaVendorAdapter", "jpaVendorAdapter", "(", ")", "{", "EclipseLinkJpaVendorAdapter", "adapter", "=", "new", "EclipseLinkJpaVendorAdapter", "(", ")", ";", "adapter", ".", "setDatabase", "(", "Database", ".", "MYSQL", ")", ";", "adapter", ".", "setShowSql", "(", "true", ")", ";", "adapter", ".", "setGenerateDdl", "(", "false", ")", ";", "return", "adapter", ";", "}", "@", "Bean", "public", "EntityManagerFactoryBuilder", "entityManagerFactoryBuilder", "(", ")", "{", "EntityManagerFactoryBuilder", "builder", "=", "new", "EntityManagerFactoryBuilder", "(", "jpaVendorAdapter", "(", ")", ",", "Collections", ".", "emptyMap", "(", ")", ",", "null", ")", ";", "return", "builder", ";", "}", "@", "Bean", "public", "LocalContainerEntityManagerFactoryBean", "entityManagerFactory", "(", ")", "{", "Map", "<", "String", ",", "Object", ">", "vendorProperties", "=", "getVendorProperties", "(", ")", ";", "return", "entityManagerFactoryBuilder", "(", ")", ".", "dataSource", "(", "dataSource", ")", ".", "packages", "(", "\"", "de.ck35.raspberry.happy.chameleon.terrarium.jpa", "\"", ")", ".", "properties", "(", "vendorProperties", ")", ".", "jta", "(", "false", ")", ".", "build", "(", ")", ";", "}", "@", "Bean", "(", "{", "\"", "transactionManager", "\"", ",", "\"", "txManager", "\"", "}", ")", "public", "PlatformTransactionManager", "transactionManager", "(", ")", "{", "return", "new", "JpaTransactionManager", "(", "entityManagerFactory", "(", ")", ".", "getObject", "(", ")", ")", ";", "}", "}" ]
Main configuration for all JPA aspects.
[ "Main", "configuration", "for", "all", "JPA", "aspects", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe165a4f281be1cc42eb411da61d56e10d0b7c56
vinayakbhope/burlap
src/main/java/burlap/behavior/singleagent/planning/deterministic/informed/astar/AStar.java
[ "Apache-2.0" ]
Java
AStar
/** * An implementation of A*. The typical "costs" of A* should be represented by negative reward returned by the reward function. * Similarly, the heuristic function should return non-positive values and an admissible heuristic would be h(n) &gt;= C(n) for all n. * A* computes the f-score as g(n) + h(n) where g(n) is the cost so far to node n and h(n) is the admissible heuristic to estimate * the remaining cost. Again, costs should be represented as negative reward. * <p> * If a terminal function is provided via the setter method defined for OO-MDPs, then the search algorithm will not expand any nodes * that are terminal states, as if there were no actions that could be executed from that state. Note that terminal states * are not necessarily the same as goal states, since there could be a fail condition from which the agent cannot act, but * that is not explicitly represented in the transition dynamics. * * @author James MacGlashan * */
An implementation of A*. The typical "costs" of A* should be represented by negative reward returned by the reward function. Similarly, the heuristic function should return non-positive values and an admissible heuristic would be h(n) >= C(n) for all n. A* computes the f-score as g(n) + h(n) where g(n) is the cost so far to node n and h(n) is the admissible heuristic to estimate the remaining cost. Again, costs should be represented as negative reward. If a terminal function is provided via the setter method defined for OO-MDPs, then the search algorithm will not expand any nodes that are terminal states, as if there were no actions that could be executed from that state. Note that terminal states are not necessarily the same as goal states, since there could be a fail condition from which the agent cannot act, but that is not explicitly represented in the transition dynamics.
[ "An", "implementation", "of", "A", "*", ".", "The", "typical", "\"", "costs", "\"", "of", "A", "*", "should", "be", "represented", "by", "negative", "reward", "returned", "by", "the", "reward", "function", ".", "Similarly", "the", "heuristic", "function", "should", "return", "non", "-", "positive", "values", "and", "an", "admissible", "heuristic", "would", "be", "h", "(", "n", ")", ">", "=", "C", "(", "n", ")", "for", "all", "n", ".", "A", "*", "computes", "the", "f", "-", "score", "as", "g", "(", "n", ")", "+", "h", "(", "n", ")", "where", "g", "(", "n", ")", "is", "the", "cost", "so", "far", "to", "node", "n", "and", "h", "(", "n", ")", "is", "the", "admissible", "heuristic", "to", "estimate", "the", "remaining", "cost", ".", "Again", "costs", "should", "be", "represented", "as", "negative", "reward", ".", "If", "a", "terminal", "function", "is", "provided", "via", "the", "setter", "method", "defined", "for", "OO", "-", "MDPs", "then", "the", "search", "algorithm", "will", "not", "expand", "any", "nodes", "that", "are", "terminal", "states", "as", "if", "there", "were", "no", "actions", "that", "could", "be", "executed", "from", "that", "state", ".", "Note", "that", "terminal", "states", "are", "not", "necessarily", "the", "same", "as", "goal", "states", "since", "there", "could", "be", "a", "fail", "condition", "from", "which", "the", "agent", "cannot", "act", "but", "that", "is", "not", "explicitly", "represented", "in", "the", "transition", "dynamics", "." ]
public class AStar extends BestFirst{ /** * The heuristic function. */ protected Heuristic heuristic; /** * Data structure for maintaining g(n): the cost so far to node n */ protected Map <HashableState, Double> cumulatedRewardMap; /** * Store the most recent cumulative reward received to some node. */ protected double lastComputedCumR; /** * Initializes A*. Goal states are indicated by gc evaluating to true. The costs are stored as negative rewards in the reward function. * By default there are no terminal states except teh goal states, so a terminal function is not taken. * @param domain the domain in which to plan * @param gc should evaluate to true for goal states; false otherwise * @param hashingFactory the state hashing factory to use * @param heuristic the planning heuristic. Should return non-positive values. */ public AStar(SADomain domain, StateConditionTest gc, HashableStateFactory hashingFactory, Heuristic heuristic){ this.deterministicPlannerInit(domain, gc, hashingFactory); this.heuristic = heuristic; } @Override public void prePlanPrep(){ cumulatedRewardMap = new HashMap<HashableState, Double>(); } @Override public void postPlanPrep(){ cumulatedRewardMap = null; //clear to free memory } @Override public void insertIntoOpen(HashIndexedHeap<PrioritizedSearchNode> openQueue, PrioritizedSearchNode psn){ super.insertIntoOpen(openQueue, psn); cumulatedRewardMap.put(psn.s, lastComputedCumR); } @Override public void updateOpen(HashIndexedHeap<PrioritizedSearchNode> openQueue, PrioritizedSearchNode openPSN, PrioritizedSearchNode npsn){ super.updateOpen(openQueue, openPSN, npsn); cumulatedRewardMap.put(npsn.s, lastComputedCumR); } @Override public double computeF(PrioritizedSearchNode parentNode, Action generatingAction, HashableState successorState, double r) { double cumR = 0.; if(parentNode != null){ double pCumR = cumulatedRewardMap.get(parentNode.s); cumR = pCumR + r; } double H = heuristic.h(successorState.s()); lastComputedCumR = cumR; double F = cumR + H; return F; } }
[ "public", "class", "AStar", "extends", "BestFirst", "{", "/**\n\t * The heuristic function.\n\t */", "protected", "Heuristic", "heuristic", ";", "/**\n\t * Data structure for maintaining g(n): the cost so far to node n\n\t */", "protected", "Map", "<", "HashableState", ",", "Double", ">", "cumulatedRewardMap", ";", "/**\n\t * Store the most recent cumulative reward received to some node.\n\t */", "protected", "double", "lastComputedCumR", ";", "/**\n\t * Initializes A*. Goal states are indicated by gc evaluating to true. The costs are stored as negative rewards in the reward function.\n\t * By default there are no terminal states except teh goal states, so a terminal function is not taken.\n\t * @param domain the domain in which to plan\n\t * @param gc should evaluate to true for goal states; false otherwise\n\t * @param hashingFactory the state hashing factory to use\n\t * @param heuristic the planning heuristic. Should return non-positive values.\n\t */", "public", "AStar", "(", "SADomain", "domain", ",", "StateConditionTest", "gc", ",", "HashableStateFactory", "hashingFactory", ",", "Heuristic", "heuristic", ")", "{", "this", ".", "deterministicPlannerInit", "(", "domain", ",", "gc", ",", "hashingFactory", ")", ";", "this", ".", "heuristic", "=", "heuristic", ";", "}", "@", "Override", "public", "void", "prePlanPrep", "(", ")", "{", "cumulatedRewardMap", "=", "new", "HashMap", "<", "HashableState", ",", "Double", ">", "(", ")", ";", "}", "@", "Override", "public", "void", "postPlanPrep", "(", ")", "{", "cumulatedRewardMap", "=", "null", ";", "}", "@", "Override", "public", "void", "insertIntoOpen", "(", "HashIndexedHeap", "<", "PrioritizedSearchNode", ">", "openQueue", ",", "PrioritizedSearchNode", "psn", ")", "{", "super", ".", "insertIntoOpen", "(", "openQueue", ",", "psn", ")", ";", "cumulatedRewardMap", ".", "put", "(", "psn", ".", "s", ",", "lastComputedCumR", ")", ";", "}", "@", "Override", "public", "void", "updateOpen", "(", "HashIndexedHeap", "<", "PrioritizedSearchNode", ">", "openQueue", ",", "PrioritizedSearchNode", "openPSN", ",", "PrioritizedSearchNode", "npsn", ")", "{", "super", ".", "updateOpen", "(", "openQueue", ",", "openPSN", ",", "npsn", ")", ";", "cumulatedRewardMap", ".", "put", "(", "npsn", ".", "s", ",", "lastComputedCumR", ")", ";", "}", "@", "Override", "public", "double", "computeF", "(", "PrioritizedSearchNode", "parentNode", ",", "Action", "generatingAction", ",", "HashableState", "successorState", ",", "double", "r", ")", "{", "double", "cumR", "=", "0.", ";", "if", "(", "parentNode", "!=", "null", ")", "{", "double", "pCumR", "=", "cumulatedRewardMap", ".", "get", "(", "parentNode", ".", "s", ")", ";", "cumR", "=", "pCumR", "+", "r", ";", "}", "double", "H", "=", "heuristic", ".", "h", "(", "successorState", ".", "s", "(", ")", ")", ";", "lastComputedCumR", "=", "cumR", ";", "double", "F", "=", "cumR", "+", "H", ";", "return", "F", ";", "}", "}" ]
An implementation of A*.
[ "An", "implementation", "of", "A", "*", "." ]
[ "//clear to free memory" ]
[ { "param": "BestFirst", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "BestFirst", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe165b64b8867149d365292236cbcd6bbae5c2ad
nikelin/Redshape-AS
utils/utils-core/src/test/java/com/redshape/utils/system/console/ConsoleCommandGeneratorFactoryTest.java
[ "Apache-2.0" ]
Java
ConsoleCommandGeneratorFactoryTest
/** * User: Sergey Kidyaev * Date: 8/2/12 * Time: 1:54 PM */
Sergey Kidyaev Date: 8/2/12 Time: 1:54 PM
[ "Sergey", "Kidyaev", "Date", ":", "8", "/", "2", "/", "12", "Time", ":", "1", ":", "54", "PM" ]
public class ConsoleCommandGeneratorFactoryTest { public static final String SYSTEM_PROPERTY_OS_NAME = "os.name"; private String operationSystemName; @Before public void setUp() { operationSystemName = System.getProperty(SYSTEM_PROPERTY_OS_NAME); } @After public void tearDown() { System.setProperty(SYSTEM_PROPERTY_OS_NAME, operationSystemName); } @Test public void testLinuxConsoleCommandGeneratorCreation() { System.setProperty(SYSTEM_PROPERTY_OS_NAME, "Linux Ubuntu"); ConsoleCommandGenerator generator = ConsoleCommandGeneratorFactory.createConsoleCommandGenerator(); assertNotNull(generator); assertTrue(generator instanceof LinuxConsoleCommandGenerator); } @Test public void testWinConsoleCommandGeneratorCreation() { System.setProperty(SYSTEM_PROPERTY_OS_NAME, "Windows 7"); ConsoleCommandGenerator generator = ConsoleCommandGeneratorFactory.createConsoleCommandGenerator(); assertNotNull(generator); assertTrue(generator instanceof WinConsoleCommandGenerator); } @Test (expected = UnsupportedOperationException.class) public void testUnknownConsoleCommandGeneratorCreation() { System.setProperty(SYSTEM_PROPERTY_OS_NAME, "Mac OS"); ConsoleCommandGeneratorFactory.createConsoleCommandGenerator(); } }
[ "public", "class", "ConsoleCommandGeneratorFactoryTest", "{", "public", "static", "final", "String", "SYSTEM_PROPERTY_OS_NAME", "=", "\"", "os.name", "\"", ";", "private", "String", "operationSystemName", ";", "@", "Before", "public", "void", "setUp", "(", ")", "{", "operationSystemName", "=", "System", ".", "getProperty", "(", "SYSTEM_PROPERTY_OS_NAME", ")", ";", "}", "@", "After", "public", "void", "tearDown", "(", ")", "{", "System", ".", "setProperty", "(", "SYSTEM_PROPERTY_OS_NAME", ",", "operationSystemName", ")", ";", "}", "@", "Test", "public", "void", "testLinuxConsoleCommandGeneratorCreation", "(", ")", "{", "System", ".", "setProperty", "(", "SYSTEM_PROPERTY_OS_NAME", ",", "\"", "Linux Ubuntu", "\"", ")", ";", "ConsoleCommandGenerator", "generator", "=", "ConsoleCommandGeneratorFactory", ".", "createConsoleCommandGenerator", "(", ")", ";", "assertNotNull", "(", "generator", ")", ";", "assertTrue", "(", "generator", "instanceof", "LinuxConsoleCommandGenerator", ")", ";", "}", "@", "Test", "public", "void", "testWinConsoleCommandGeneratorCreation", "(", ")", "{", "System", ".", "setProperty", "(", "SYSTEM_PROPERTY_OS_NAME", ",", "\"", "Windows 7", "\"", ")", ";", "ConsoleCommandGenerator", "generator", "=", "ConsoleCommandGeneratorFactory", ".", "createConsoleCommandGenerator", "(", ")", ";", "assertNotNull", "(", "generator", ")", ";", "assertTrue", "(", "generator", "instanceof", "WinConsoleCommandGenerator", ")", ";", "}", "@", "Test", "(", "expected", "=", "UnsupportedOperationException", ".", "class", ")", "public", "void", "testUnknownConsoleCommandGeneratorCreation", "(", ")", "{", "System", ".", "setProperty", "(", "SYSTEM_PROPERTY_OS_NAME", ",", "\"", "Mac OS", "\"", ")", ";", "ConsoleCommandGeneratorFactory", ".", "createConsoleCommandGenerator", "(", ")", ";", "}", "}" ]
User: Sergey Kidyaev Date: 8/2/12 Time: 1:54 PM
[ "User", ":", "Sergey", "Kidyaev", "Date", ":", "8", "/", "2", "/", "12", "Time", ":", "1", ":", "54", "PM" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe16f02a6a338fac08da04976b44035fc73c07cb
kpiwko/wolf-validator
src/main/java/org/jboss/wolf/validator/internal/LogTransferListener.java
[ "Apache-2.0" ]
Java
LogTransferListener
// see project shrinkwrap-resolver, class org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener
see project shrinkwrap-resolver, class org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener
[ "see", "project", "shrinkwrap", "-", "resolver", "class", "org", ".", "jboss", ".", "shrinkwrap", ".", "resolver", ".", "impl", ".", "maven", ".", "logging", ".", "LogTransferListener" ]
public class LogTransferListener extends AbstractTransferListener { private static final Logger logger = LoggerFactory.getLogger(LogTransferListener.class); private static final long TRANSFER_THRESHOLD = 1024 * 50; private final Map<TransferResource, Long> downloads = new ConcurrentHashMap<TransferResource, Long>(); @Override public void transferInitiated(TransferEvent event) { TransferResource resource = event.getResource(); StringBuilder sb = new StringBuilder() .append(event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploading" : "Downloading").append(":") .append(resource.getRepositoryUrl()).append(resource.getResourceName()); downloads.put(resource, new Long(0)); logger.debug(sb.toString()); } @Override public void transferProgressed(TransferEvent event) { TransferResource resource = event.getResource(); long lastTransferred = downloads.get(resource); long transferred = event.getTransferredBytes(); if (transferred - lastTransferred >= TRANSFER_THRESHOLD) { downloads.put(resource, Long.valueOf(transferred)); long total = resource.getContentLength(); logger.trace(getStatus(transferred, total) + ", "); } } @Override public void transferSucceeded(TransferEvent event) { TransferResource resource = event.getResource(); downloads.remove(resource); long contentLength = event.getTransferredBytes(); if (contentLength >= 0) { long duration = System.currentTimeMillis() - resource.getTransferStartTime(); double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0); StringBuilder sb = new StringBuilder().append("Completed") .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ") .append(resource.getResourceName()) .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") .append(resource.getRepositoryUrl()).append(", transferred ") .append(contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B").append(" at ") .append(new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH)).format(kbPerSec)) .append("KB/sec"); logger.debug(sb.toString()); } } @Override public void transferFailed(TransferEvent event) { TransferResource resource = event.getResource(); downloads.remove(resource); StringBuilder sb = new StringBuilder().append("Failed") .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " uploading " : " downloading ") .append(resource.getResourceName()) .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") .append(resource.getRepositoryUrl()).append(". "); if (event.getException() != null) { sb.append("Reason: \n").append(event.getException()); } logger.warn(sb.toString()); } @Override public void transferCorrupted(TransferEvent event) { TransferResource resource = event.getResource(); downloads.remove(resource); StringBuilder sb = new StringBuilder().append("Corrupted") .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " upload of " : " download of ") .append(resource.getResourceName()) .append(event.getRequestType() == TransferEvent.RequestType.PUT ? " into " : " from ") .append(resource.getRepositoryUrl()).append(". "); if (event.getException() != null) { sb.append("Reason: \n").append(event.getException()); } logger.warn(sb.toString()); } private String getStatus(long complete, long total) { if (total >= 1024) { return toKB(complete) + "/" + toKB(total) + " KB"; } else if (total >= 0) { return complete + "/" + total + " B"; } else if (complete >= 1024) { return toKB(complete) + " KB"; } else { return complete + " B"; } } private long toKB(long bytes) { return (bytes + 1023) / 1024; } }
[ "public", "class", "LogTransferListener", "extends", "AbstractTransferListener", "{", "private", "static", "final", "Logger", "logger", "=", "LoggerFactory", ".", "getLogger", "(", "LogTransferListener", ".", "class", ")", ";", "private", "static", "final", "long", "TRANSFER_THRESHOLD", "=", "1024", "*", "50", ";", "private", "final", "Map", "<", "TransferResource", ",", "Long", ">", "downloads", "=", "new", "ConcurrentHashMap", "<", "TransferResource", ",", "Long", ">", "(", ")", ";", "@", "Override", "public", "void", "transferInitiated", "(", "TransferEvent", "event", ")", "{", "TransferResource", "resource", "=", "event", ".", "getResource", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", "Uploading", "\"", ":", "\"", "Downloading", "\"", ")", ".", "append", "(", "\"", ":", "\"", ")", ".", "append", "(", "resource", ".", "getRepositoryUrl", "(", ")", ")", ".", "append", "(", "resource", ".", "getResourceName", "(", ")", ")", ";", "downloads", ".", "put", "(", "resource", ",", "new", "Long", "(", "0", ")", ")", ";", "logger", ".", "debug", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "transferProgressed", "(", "TransferEvent", "event", ")", "{", "TransferResource", "resource", "=", "event", ".", "getResource", "(", ")", ";", "long", "lastTransferred", "=", "downloads", ".", "get", "(", "resource", ")", ";", "long", "transferred", "=", "event", ".", "getTransferredBytes", "(", ")", ";", "if", "(", "transferred", "-", "lastTransferred", ">=", "TRANSFER_THRESHOLD", ")", "{", "downloads", ".", "put", "(", "resource", ",", "Long", ".", "valueOf", "(", "transferred", ")", ")", ";", "long", "total", "=", "resource", ".", "getContentLength", "(", ")", ";", "logger", ".", "trace", "(", "getStatus", "(", "transferred", ",", "total", ")", "+", "\"", ", ", "\"", ")", ";", "}", "}", "@", "Override", "public", "void", "transferSucceeded", "(", "TransferEvent", "event", ")", "{", "TransferResource", "resource", "=", "event", ".", "getResource", "(", ")", ";", "downloads", ".", "remove", "(", "resource", ")", ";", "long", "contentLength", "=", "event", ".", "getTransferredBytes", "(", ")", ";", "if", "(", "contentLength", ">=", "0", ")", "{", "long", "duration", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "resource", ".", "getTransferStartTime", "(", ")", ";", "double", "kbPerSec", "=", "(", "contentLength", "/", "1024.0", ")", "/", "(", "duration", "/", "1000.0", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"", "Completed", "\"", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " upload of ", "\"", ":", "\"", " download of ", "\"", ")", ".", "append", "(", "resource", ".", "getResourceName", "(", ")", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " into ", "\"", ":", "\"", " from ", "\"", ")", ".", "append", "(", "resource", ".", "getRepositoryUrl", "(", ")", ")", ".", "append", "(", "\"", ", transferred ", "\"", ")", ".", "append", "(", "contentLength", ">=", "1024", "?", "toKB", "(", "contentLength", ")", "+", "\"", " KB", "\"", ":", "contentLength", "+", "\"", " B", "\"", ")", ".", "append", "(", "\"", " at ", "\"", ")", ".", "append", "(", "new", "DecimalFormat", "(", "\"", "0.0", "\"", ",", "new", "DecimalFormatSymbols", "(", "Locale", ".", "ENGLISH", ")", ")", ".", "format", "(", "kbPerSec", ")", ")", ".", "append", "(", "\"", "KB/sec", "\"", ")", ";", "logger", ".", "debug", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "}", "@", "Override", "public", "void", "transferFailed", "(", "TransferEvent", "event", ")", "{", "TransferResource", "resource", "=", "event", ".", "getResource", "(", ")", ";", "downloads", ".", "remove", "(", "resource", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"", "Failed", "\"", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " uploading ", "\"", ":", "\"", " downloading ", "\"", ")", ".", "append", "(", "resource", ".", "getResourceName", "(", ")", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " into ", "\"", ":", "\"", " from ", "\"", ")", ".", "append", "(", "resource", ".", "getRepositoryUrl", "(", ")", ")", ".", "append", "(", "\"", ". ", "\"", ")", ";", "if", "(", "event", ".", "getException", "(", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", "Reason: ", "\\n", "\"", ")", ".", "append", "(", "event", ".", "getException", "(", ")", ")", ";", "}", "logger", ".", "warn", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "@", "Override", "public", "void", "transferCorrupted", "(", "TransferEvent", "event", ")", "{", "TransferResource", "resource", "=", "event", ".", "getResource", "(", ")", ";", "downloads", ".", "remove", "(", "resource", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\"", "Corrupted", "\"", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " upload of ", "\"", ":", "\"", " download of ", "\"", ")", ".", "append", "(", "resource", ".", "getResourceName", "(", ")", ")", ".", "append", "(", "event", ".", "getRequestType", "(", ")", "==", "TransferEvent", ".", "RequestType", ".", "PUT", "?", "\"", " into ", "\"", ":", "\"", " from ", "\"", ")", ".", "append", "(", "resource", ".", "getRepositoryUrl", "(", ")", ")", ".", "append", "(", "\"", ". ", "\"", ")", ";", "if", "(", "event", ".", "getException", "(", ")", "!=", "null", ")", "{", "sb", ".", "append", "(", "\"", "Reason: ", "\\n", "\"", ")", ".", "append", "(", "event", ".", "getException", "(", ")", ")", ";", "}", "logger", ".", "warn", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "private", "String", "getStatus", "(", "long", "complete", ",", "long", "total", ")", "{", "if", "(", "total", ">=", "1024", ")", "{", "return", "toKB", "(", "complete", ")", "+", "\"", "/", "\"", "+", "toKB", "(", "total", ")", "+", "\"", " KB", "\"", ";", "}", "else", "if", "(", "total", ">=", "0", ")", "{", "return", "complete", "+", "\"", "/", "\"", "+", "total", "+", "\"", " B", "\"", ";", "}", "else", "if", "(", "complete", ">=", "1024", ")", "{", "return", "toKB", "(", "complete", ")", "+", "\"", " KB", "\"", ";", "}", "else", "{", "return", "complete", "+", "\"", " B", "\"", ";", "}", "}", "private", "long", "toKB", "(", "long", "bytes", ")", "{", "return", "(", "bytes", "+", "1023", ")", "/", "1024", ";", "}", "}" ]
see project shrinkwrap-resolver, class org.jboss.shrinkwrap.resolver.impl.maven.logging.LogTransferListener
[ "see", "project", "shrinkwrap", "-", "resolver", "class", "org", ".", "jboss", ".", "shrinkwrap", ".", "resolver", ".", "impl", ".", "maven", ".", "logging", ".", "LogTransferListener" ]
[]
[ { "param": "AbstractTransferListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractTransferListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe1e764cd19de42bc59c48981271010901c4ec1b
aVolpe/cotizacion
src/main/java/py/com/volpe/cotizacion/controller/ExchangeController.java
[ "MIT" ]
Java
ExchangeController
/** * @author Arturo Volpe * @since 4/27/18 */
@author Arturo Volpe @since 4/27/18
[ "@author", "Arturo", "Volpe", "@since", "4", "/", "27", "/", "18" ]
@RestController @RequiredArgsConstructor public class ExchangeController { private final QueryResponseDetailRepository detailRepository; @GetMapping(value = "/api/exchange/{iso}", produces = MediaType.APPLICATION_JSON_VALUE) public ResultData byIso(@PathVariable(value = "iso") String code) { List<ByIsoCodeResult> data = detailRepository.getMaxByPlaceInISO(code); LongSummaryStatistics lsm = data.stream().map(ByIsoCodeResult::getQueryDate).collect(Collectors.summarizingLong(Date::getTime)); return new ResultData( lsm.getMin() == Long.MAX_VALUE ? null : new Date(lsm.getMin()), lsm.getMax() == Long.MIN_VALUE ? null : new Date(lsm.getMax()), lsm.getCount(), data); } @GetMapping(value = "/api/exchange/", produces = MediaType.APPLICATION_JSON_VALUE) public List<String> getAvailableCurrencies() { return Arrays.asList( "ARS", "EUR", "BRL", "USD", "UYU", "GBP", "CAD", "CHF", "JPY", "CLP", "AUD", "BOB", "MXN", "PEN", "COP", "DKK", "SEK", "CNY", "NOK", "ILS", "KWD", "RUB", "SGD", "TWD", "ZAR"); } @Value public static class ResultData { Date firstQueryResult; Date lastQueryResult; long count; List<ByIsoCodeResult> data; } }
[ "@", "RestController", "@", "RequiredArgsConstructor", "public", "class", "ExchangeController", "{", "private", "final", "QueryResponseDetailRepository", "detailRepository", ";", "@", "GetMapping", "(", "value", "=", "\"", "/api/exchange/{iso}", "\"", ",", "produces", "=", "MediaType", ".", "APPLICATION_JSON_VALUE", ")", "public", "ResultData", "byIso", "(", "@", "PathVariable", "(", "value", "=", "\"", "iso", "\"", ")", "String", "code", ")", "{", "List", "<", "ByIsoCodeResult", ">", "data", "=", "detailRepository", ".", "getMaxByPlaceInISO", "(", "code", ")", ";", "LongSummaryStatistics", "lsm", "=", "data", ".", "stream", "(", ")", ".", "map", "(", "ByIsoCodeResult", "::", "getQueryDate", ")", ".", "collect", "(", "Collectors", ".", "summarizingLong", "(", "Date", "::", "getTime", ")", ")", ";", "return", "new", "ResultData", "(", "lsm", ".", "getMin", "(", ")", "==", "Long", ".", "MAX_VALUE", "?", "null", ":", "new", "Date", "(", "lsm", ".", "getMin", "(", ")", ")", ",", "lsm", ".", "getMax", "(", ")", "==", "Long", ".", "MIN_VALUE", "?", "null", ":", "new", "Date", "(", "lsm", ".", "getMax", "(", ")", ")", ",", "lsm", ".", "getCount", "(", ")", ",", "data", ")", ";", "}", "@", "GetMapping", "(", "value", "=", "\"", "/api/exchange/", "\"", ",", "produces", "=", "MediaType", ".", "APPLICATION_JSON_VALUE", ")", "public", "List", "<", "String", ">", "getAvailableCurrencies", "(", ")", "{", "return", "Arrays", ".", "asList", "(", "\"", "ARS", "\"", ",", "\"", "EUR", "\"", ",", "\"", "BRL", "\"", ",", "\"", "USD", "\"", ",", "\"", "UYU", "\"", ",", "\"", "GBP", "\"", ",", "\"", "CAD", "\"", ",", "\"", "CHF", "\"", ",", "\"", "JPY", "\"", ",", "\"", "CLP", "\"", ",", "\"", "AUD", "\"", ",", "\"", "BOB", "\"", ",", "\"", "MXN", "\"", ",", "\"", "PEN", "\"", ",", "\"", "COP", "\"", ",", "\"", "DKK", "\"", ",", "\"", "SEK", "\"", ",", "\"", "CNY", "\"", ",", "\"", "NOK", "\"", ",", "\"", "ILS", "\"", ",", "\"", "KWD", "\"", ",", "\"", "RUB", "\"", ",", "\"", "SGD", "\"", ",", "\"", "TWD", "\"", ",", "\"", "ZAR", "\"", ")", ";", "}", "@", "Value", "public", "static", "class", "ResultData", "{", "Date", "firstQueryResult", ";", "Date", "lastQueryResult", ";", "long", "count", ";", "List", "<", "ByIsoCodeResult", ">", "data", ";", "}", "}" ]
@author Arturo Volpe @since 4/27/18
[ "@author", "Arturo", "Volpe", "@since", "4", "/", "27", "/", "18" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe29cd707a623ff6c69dda06daef57df3237beb1
rapiddweller/rd-lib-common
src/main/java/com/rapiddweller/common/RegexUtil.java
[ "Apache-2.0" ]
Java
RegexUtil
/** * Provides utility methods regarding regular expressions.<br><br> * Created: 22.09.2019 07:21:55 * * @author Volker Bergmann * @since 1.0.12 */
Provides utility methods regarding regular expressions. Created: 22.09.2019 07:21:55 @author Volker Bergmann @since 1.0.12
[ "Provides", "utility", "methods", "regarding", "regular", "expressions", ".", "Created", ":", "22", ".", "09", ".", "2019", "07", ":", "21", ":", "55", "@author", "Volker", "Bergmann", "@since", "1", ".", "0", ".", "12" ]
public class RegexUtil { /** * Parse string [ ]. * * @param text the text * @param regex the regex * @return the string [ ] */ public static String[] parse(String text, String regex) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (!matcher.find()) { return null; } int groupCount = matcher.groupCount(); String[] result = new String[groupCount]; for (int i = 0; i < groupCount; i++) { result[i] = matcher.group(i + 1); } return result; } /** * Matches boolean. * * @param regex the regex * @param text the text * @return the boolean */ public static boolean matches(String regex, String text) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); return matcher.matches(); } }
[ "public", "class", "RegexUtil", "{", "/**\n * Parse string [ ].\n *\n * @param text the text\n * @param regex the regex\n * @return the string [ ]\n */", "public", "static", "String", "[", "]", "parse", "(", "String", "text", ",", "String", "regex", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "text", ")", ";", "if", "(", "!", "matcher", ".", "find", "(", ")", ")", "{", "return", "null", ";", "}", "int", "groupCount", "=", "matcher", ".", "groupCount", "(", ")", ";", "String", "[", "]", "result", "=", "new", "String", "[", "groupCount", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "groupCount", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "matcher", ".", "group", "(", "i", "+", "1", ")", ";", "}", "return", "result", ";", "}", "/**\n * Matches boolean.\n *\n * @param regex the regex\n * @param text the text\n * @return the boolean\n */", "public", "static", "boolean", "matches", "(", "String", "regex", ",", "String", "text", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "regex", ")", ";", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "text", ")", ";", "return", "matcher", ".", "matches", "(", ")", ";", "}", "}" ]
Provides utility methods regarding regular expressions.<br><br> Created: 22.09.2019 07:21:55
[ "Provides", "utility", "methods", "regarding", "regular", "expressions", ".", "<br", ">", "<br", ">", "Created", ":", "22", ".", "09", ".", "2019", "07", ":", "21", ":", "55" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe2b6ef934bc5cc205819a63aa5273fd4a2c9499
timtasse/vijava
src/main/java/com/vmware/vim25/VirtualTPMOption.java
[ "BSD-3-Clause" ]
Java
VirtualTPMOption
/** * This data object type contains the options for the virtual TPM class. * * @author Stefan Dilk <[email protected]> * @version 6.7 * @since 6.7 */
This data object type contains the options for the virtual TPM class.
[ "This", "data", "object", "type", "contains", "the", "options", "for", "the", "virtual", "TPM", "class", "." ]
public class VirtualTPMOption extends VirtualDeviceOption { private String[] supportedFirmware; @Override public String toString() { return "VirtualTPMOption{" + "supportedFirmware=" + Arrays.toString(supportedFirmware) + "} " + super.toString(); } public String[] getSupportedFirmware() { return supportedFirmware; } public void setSupportedFirmware(final String[] supportedFirmware) { this.supportedFirmware = supportedFirmware; } }
[ "public", "class", "VirtualTPMOption", "extends", "VirtualDeviceOption", "{", "private", "String", "[", "]", "supportedFirmware", ";", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "VirtualTPMOption{", "\"", "+", "\"", "supportedFirmware=", "\"", "+", "Arrays", ".", "toString", "(", "supportedFirmware", ")", "+", "\"", "} ", "\"", "+", "super", ".", "toString", "(", ")", ";", "}", "public", "String", "[", "]", "getSupportedFirmware", "(", ")", "{", "return", "supportedFirmware", ";", "}", "public", "void", "setSupportedFirmware", "(", "final", "String", "[", "]", "supportedFirmware", ")", "{", "this", ".", "supportedFirmware", "=", "supportedFirmware", ";", "}", "}" ]
This data object type contains the options for the virtual TPM class.
[ "This", "data", "object", "type", "contains", "the", "options", "for", "the", "virtual", "TPM", "class", "." ]
[]
[ { "param": "VirtualDeviceOption", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "VirtualDeviceOption", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe345afe1c8452e5901e7bc4d581f293e8058737
devzendo/mini-miser
src/main/java/org/devzendo/minimiser/wiring/lifecycle/WizardPageInitialisingLifecycle.java
[ "Apache-2.0" ]
Java
WizardPageInitialisingLifecycle
/** * Initialises the MiniMiserWizardPane toolkit. This needs to have * the left-hand graphic set, and the size used for the main * panel cached, as it's jarring to create the panel with a * filechooser every time, and have it resize to contain it. * * @author matt * */
Initialises the MiniMiserWizardPane toolkit. This needs to have the left-hand graphic set, and the size used for the main panel cached, as it's jarring to create the panel with a filechooser every time, and have it resize to contain it. @author matt
[ "Initialises", "the", "MiniMiserWizardPane", "toolkit", ".", "This", "needs", "to", "have", "the", "left", "-", "hand", "graphic", "set", "and", "the", "size", "used", "for", "the", "main", "panel", "cached", "as", "it", "'", "s", "jarring", "to", "create", "the", "panel", "with", "a", "filechooser", "every", "time", "and", "have", "it", "resize", "to", "contain", "it", ".", "@author", "matt" ]
public final class WizardPageInitialisingLifecycle implements Lifecycle { private final MiniMiserPrefs mPrefs; /** * @param prefs the preferences */ public WizardPageInitialisingLifecycle(final MiniMiserPrefs prefs) { mPrefs = prefs; } /** * {@inheritDoc} */ public void shutdown() { // nothing } /** * {@inheritDoc} */ public void startup() { GUIUtils.runOnEventThread(new Runnable() { public void run() { MiniMiserWizardPage.setLHGraphic(); MiniMiserWizardPage.getPanelDimension(mPrefs); } }); } }
[ "public", "final", "class", "WizardPageInitialisingLifecycle", "implements", "Lifecycle", "{", "private", "final", "MiniMiserPrefs", "mPrefs", ";", "/**\n * @param prefs the preferences\n */", "public", "WizardPageInitialisingLifecycle", "(", "final", "MiniMiserPrefs", "prefs", ")", "{", "mPrefs", "=", "prefs", ";", "}", "/**\n * {@inheritDoc}\n */", "public", "void", "shutdown", "(", ")", "{", "}", "/**\n * {@inheritDoc}\n */", "public", "void", "startup", "(", ")", "{", "GUIUtils", ".", "runOnEventThread", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "MiniMiserWizardPage", ".", "setLHGraphic", "(", ")", ";", "MiniMiserWizardPage", ".", "getPanelDimension", "(", "mPrefs", ")", ";", "}", "}", ")", ";", "}", "}" ]
Initialises the MiniMiserWizardPane toolkit.
[ "Initialises", "the", "MiniMiserWizardPane", "toolkit", "." ]
[ "// nothing" ]
[ { "param": "Lifecycle", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Lifecycle", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe3aa0c7b8d64cbab24714b9ea6da496f5c785bb
hansd/vert.x
src/main/java/org/vertx/java/core/net/NetServerBase.java
[ "Apache-2.0" ]
Java
NetServerBase
/** * Abstract base class for net servers * * @author <a href="http://tfox.org">Tim Fox</a> */
Abstract base class for net servers @author Tim Fox
[ "Abstract", "base", "class", "for", "net", "servers", "@author", "Tim", "Fox" ]
public abstract class NetServerBase extends NetBase { protected ClientAuth clientAuth = ClientAuth.NONE; /** * Set {@code required} to true if you want the server to request client authentication from any connecting clients. This * is an extra level of security in SSL, and requires clients to provide client certificates. Those certificates must be added * to the server trust store. * @return A reference to this, so multiple invocations can be chained together. */ public NetServerBase setClientAuthRequired(boolean required) { clientAuth = required ? ClientAuth.REQUIRED : ClientAuth.NONE; return this; } protected NetServerBase() { super(); connectionOptions.put("reuseAddress", true); //Not child since applies to the acceptor socket } }
[ "public", "abstract", "class", "NetServerBase", "extends", "NetBase", "{", "protected", "ClientAuth", "clientAuth", "=", "ClientAuth", ".", "NONE", ";", "/**\n * Set {@code required} to true if you want the server to request client authentication from any connecting clients. This\n * is an extra level of security in SSL, and requires clients to provide client certificates. Those certificates must be added\n * to the server trust store.\n * @return A reference to this, so multiple invocations can be chained together.\n */", "public", "NetServerBase", "setClientAuthRequired", "(", "boolean", "required", ")", "{", "clientAuth", "=", "required", "?", "ClientAuth", ".", "REQUIRED", ":", "ClientAuth", ".", "NONE", ";", "return", "this", ";", "}", "protected", "NetServerBase", "(", ")", "{", "super", "(", ")", ";", "connectionOptions", ".", "put", "(", "\"", "reuseAddress", "\"", ",", "true", ")", ";", "}", "}" ]
Abstract base class for net servers @author <a href="http://tfox.org">Tim Fox</a>
[ "Abstract", "base", "class", "for", "net", "servers", "@author", "<a", "href", "=", "\"", "http", ":", "//", "tfox", ".", "org", "\"", ">", "Tim", "Fox<", "/", "a", ">" ]
[ "//Not child since applies to the acceptor socket" ]
[ { "param": "NetBase", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "NetBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe4735e11914343abc34434ddc21df275b6ff49e
xuebaofeng/table-change-tool
src/main/java/bf/cg/Util.java
[ "MIT" ]
Java
Util
/** * @author Baofeng(Shawn) Xue on 2/8/16. */
@author Baofeng(Shawn) Xue on 2/8/16.
[ "@author", "Baofeng", "(", "Shawn", ")", "Xue", "on", "2", "/", "8", "/", "16", "." ]
public class Util { public static void main(String[] args) throws IOException { Files.lines(Paths.get("test")).distinct().sorted().forEach((s -> { System.out.println(String.format("'%s',", s)); })); } }
[ "public", "class", "Util", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "Files", ".", "lines", "(", "Paths", ".", "get", "(", "\"", "test", "\"", ")", ")", ".", "distinct", "(", ")", ".", "sorted", "(", ")", ".", "forEach", "(", "(", "s", "->", "{", "System", ".", "out", ".", "println", "(", "String", ".", "format", "(", "\"", "'%s',", "\"", ",", "s", ")", ")", ";", "}", ")", ")", ";", "}", "}" ]
@author Baofeng(Shawn) Xue on 2/8/16.
[ "@author", "Baofeng", "(", "Shawn", ")", "Xue", "on", "2", "/", "8", "/", "16", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe4a85a41940210f6e4532dba6dc71608e7fc80d
datazuul/com.datazuul.webapps--datazuul-cmslight-tapestry
src/main/java/com/datazuul/webapps/cmslight/pages/DateiNeu.java
[ "Apache-2.0" ]
Java
DateiNeu
/** * Page for creating/uploading a new file/directory. * * @author Ralf Eichinger */
Page for creating/uploading a new file/directory. @author Ralf Eichinger
[ "Page", "for", "creating", "/", "uploading", "a", "new", "file", "/", "directory", ".", "@author", "Ralf", "Eichinger" ]
public abstract class DateiNeu extends AppBasePage implements PageRenderListener { private static final Logger LOG = Logger.getLogger(DateiNeu.class); /* Navigationslink */ public abstract int getParentIndex(); public abstract void setParentIndex(int index); public abstract HRef getParent(); public abstract void setParent(HRef parent); public abstract String getFilepath(); public abstract void setFilepath(String filepath); public abstract IUploadFile getFile(); public abstract String getFileName(); public abstract String getFileType(); public abstract void setFileType(String filetype); public abstract File getTemplate(); public abstract void setTemplate(File o); private static final String TYPE_DIRECTORY = "directory"; private static final String TYPE_FILE = "file"; private TemplateSelectionModel templatesModel; public void pageBeginRender(PageEvent event) { logEnter(LOG, "DateiNeu"); setFileType(TYPE_FILE); } public void formSubmit(IRequestCycle cycle) { } public IPropertySelectionModel getTemplatesModel() { if (this.templatesModel == null) this.templatesModel = buildTemplatesModel(); return (IPropertySelectionModel) this.templatesModel; } private TemplateSelectionModel buildTemplatesModel() { ArrayList templates = new ArrayList(); Visit visit = (Visit) getVisit(); File templateDir = visit.getTemplateDir(); File[] children = templateDir.listFiles(); for (int i = 0; i < children.length; i++) { File child = children[i]; if (!child.isDirectory()) { templates.add(child); } } TemplateSelectionModel model = new TemplateSelectionModel(templates); return model; } /** * Listener invoked to change directory. */ public void changeDirectory(IRequestCycle cycle) { Object[] parameters = cycle.getServiceParameters(); String navigationTarget = (String) parameters[0]; DateiManager page = (DateiManager) cycle.getPage("DateiManager"); page.init(cycle, navigationTarget); } public void saveItem(IRequestCycle cycle) { Visit visit = (Visit) getVisit(); String filename = getFileName(); String filetype = getFileType(); File template = getTemplate(); IUploadFile uploadFile = getFile(); LOG.info("DateiNeu.saveItem: Dateiname: " + getFileName()); LOG.info("DateiNeu.saveItem: Dateityp: " + getFileType()); if (getTemplate() != null) { LOG.info("DateiNeu.saveItem: Vorlage: " + getTemplate().getName()); } if (getFile() != null) { LOG.info("DateiNeu.saveItem: Content-Type: " + getFile().getContentType()); } if ((filename == null || filename.equals("")) && Constants.FILE.equals(filetype)) { // prio 1 if (uploadFile != null && uploadFile.getSize() > 0) { filename = uploadFile.getFileName(); } else { if (template != null) { // prio 2 filename = template.getName(); } } } Folder parent = visit.getLastFolder(); File parentFile = parent.getFile(); File newFile = new File(parentFile, filename); if (!newFile.getParentFile().getAbsolutePath() .equals(parentFile.getAbsolutePath())) { addErrorMessage(getMessage("error.file.invalid.name")); return; } boolean created = false; try { if (filetype.equals(Constants.FILE)) { // fill file with content if (uploadFile.getFileName() != null && !"".equals(uploadFile.getFileName())) {// prio 1 // create file created = newFile.createNewFile(); if (created) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stream = uploadFile.getStream(); // write the file to the file specified OutputStream bos = new FileOutputStream(newFile); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); // close the stream stream.close(); } } else if (template != null) { if (!newFile.exists()) { FileUtils.copyFile(template, newFile); created = true; } } else { created = newFile.createNewFile(); } } else if (filetype.equals(Constants.DIRECTORY)) { created = newFile.mkdir(); } if (created == false) { addErrorMessage(format("error.file.exists", newFile.getName())); return; } } catch (IOException e) { addErrorMessage(format("error.file.write", newFile.getName())); return; } catch (SecurityException se) { addErrorMessage(format("error.file.write", newFile.getName())); return; } LOG.info("DateiNeu.saveItem: Datei " + newFile.getAbsolutePath() + " angelegt"); cycle.activate("DateiManager"); } public void init(IRequestCycle cycle, String filepath) { setFilepath(filepath); cycle.activate(this); } }
[ "public", "abstract", "class", "DateiNeu", "extends", "AppBasePage", "implements", "PageRenderListener", "{", "private", "static", "final", "Logger", "LOG", "=", "Logger", ".", "getLogger", "(", "DateiNeu", ".", "class", ")", ";", "/* Navigationslink */", "public", "abstract", "int", "getParentIndex", "(", ")", ";", "public", "abstract", "void", "setParentIndex", "(", "int", "index", ")", ";", "public", "abstract", "HRef", "getParent", "(", ")", ";", "public", "abstract", "void", "setParent", "(", "HRef", "parent", ")", ";", "public", "abstract", "String", "getFilepath", "(", ")", ";", "public", "abstract", "void", "setFilepath", "(", "String", "filepath", ")", ";", "public", "abstract", "IUploadFile", "getFile", "(", ")", ";", "public", "abstract", "String", "getFileName", "(", ")", ";", "public", "abstract", "String", "getFileType", "(", ")", ";", "public", "abstract", "void", "setFileType", "(", "String", "filetype", ")", ";", "public", "abstract", "File", "getTemplate", "(", ")", ";", "public", "abstract", "void", "setTemplate", "(", "File", "o", ")", ";", "private", "static", "final", "String", "TYPE_DIRECTORY", "=", "\"", "directory", "\"", ";", "private", "static", "final", "String", "TYPE_FILE", "=", "\"", "file", "\"", ";", "private", "TemplateSelectionModel", "templatesModel", ";", "public", "void", "pageBeginRender", "(", "PageEvent", "event", ")", "{", "logEnter", "(", "LOG", ",", "\"", "DateiNeu", "\"", ")", ";", "setFileType", "(", "TYPE_FILE", ")", ";", "}", "public", "void", "formSubmit", "(", "IRequestCycle", "cycle", ")", "{", "}", "public", "IPropertySelectionModel", "getTemplatesModel", "(", ")", "{", "if", "(", "this", ".", "templatesModel", "==", "null", ")", "this", ".", "templatesModel", "=", "buildTemplatesModel", "(", ")", ";", "return", "(", "IPropertySelectionModel", ")", "this", ".", "templatesModel", ";", "}", "private", "TemplateSelectionModel", "buildTemplatesModel", "(", ")", "{", "ArrayList", "templates", "=", "new", "ArrayList", "(", ")", ";", "Visit", "visit", "=", "(", "Visit", ")", "getVisit", "(", ")", ";", "File", "templateDir", "=", "visit", ".", "getTemplateDir", "(", ")", ";", "File", "[", "]", "children", "=", "templateDir", ".", "listFiles", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "File", "child", "=", "children", "[", "i", "]", ";", "if", "(", "!", "child", ".", "isDirectory", "(", ")", ")", "{", "templates", ".", "add", "(", "child", ")", ";", "}", "}", "TemplateSelectionModel", "model", "=", "new", "TemplateSelectionModel", "(", "templates", ")", ";", "return", "model", ";", "}", "/**\n\t * Listener invoked to change directory.\n\t */", "public", "void", "changeDirectory", "(", "IRequestCycle", "cycle", ")", "{", "Object", "[", "]", "parameters", "=", "cycle", ".", "getServiceParameters", "(", ")", ";", "String", "navigationTarget", "=", "(", "String", ")", "parameters", "[", "0", "]", ";", "DateiManager", "page", "=", "(", "DateiManager", ")", "cycle", ".", "getPage", "(", "\"", "DateiManager", "\"", ")", ";", "page", ".", "init", "(", "cycle", ",", "navigationTarget", ")", ";", "}", "public", "void", "saveItem", "(", "IRequestCycle", "cycle", ")", "{", "Visit", "visit", "=", "(", "Visit", ")", "getVisit", "(", ")", ";", "String", "filename", "=", "getFileName", "(", ")", ";", "String", "filetype", "=", "getFileType", "(", ")", ";", "File", "template", "=", "getTemplate", "(", ")", ";", "IUploadFile", "uploadFile", "=", "getFile", "(", ")", ";", "LOG", ".", "info", "(", "\"", "DateiNeu.saveItem: Dateiname: ", "\"", "+", "getFileName", "(", ")", ")", ";", "LOG", ".", "info", "(", "\"", "DateiNeu.saveItem: Dateityp: ", "\"", "+", "getFileType", "(", ")", ")", ";", "if", "(", "getTemplate", "(", ")", "!=", "null", ")", "{", "LOG", ".", "info", "(", "\"", "DateiNeu.saveItem: Vorlage: ", "\"", "+", "getTemplate", "(", ")", ".", "getName", "(", ")", ")", ";", "}", "if", "(", "getFile", "(", ")", "!=", "null", ")", "{", "LOG", ".", "info", "(", "\"", "DateiNeu.saveItem: Content-Type: ", "\"", "+", "getFile", "(", ")", ".", "getContentType", "(", ")", ")", ";", "}", "if", "(", "(", "filename", "==", "null", "||", "filename", ".", "equals", "(", "\"", "\"", ")", ")", "&&", "Constants", ".", "FILE", ".", "equals", "(", "filetype", ")", ")", "{", "if", "(", "uploadFile", "!=", "null", "&&", "uploadFile", ".", "getSize", "(", ")", ">", "0", ")", "{", "filename", "=", "uploadFile", ".", "getFileName", "(", ")", ";", "}", "else", "{", "if", "(", "template", "!=", "null", ")", "{", "filename", "=", "template", ".", "getName", "(", ")", ";", "}", "}", "}", "Folder", "parent", "=", "visit", ".", "getLastFolder", "(", ")", ";", "File", "parentFile", "=", "parent", ".", "getFile", "(", ")", ";", "File", "newFile", "=", "new", "File", "(", "parentFile", ",", "filename", ")", ";", "if", "(", "!", "newFile", ".", "getParentFile", "(", ")", ".", "getAbsolutePath", "(", ")", ".", "equals", "(", "parentFile", ".", "getAbsolutePath", "(", ")", ")", ")", "{", "addErrorMessage", "(", "getMessage", "(", "\"", "error.file.invalid.name", "\"", ")", ")", ";", "return", ";", "}", "boolean", "created", "=", "false", ";", "try", "{", "if", "(", "filetype", ".", "equals", "(", "Constants", ".", "FILE", ")", ")", "{", "if", "(", "uploadFile", ".", "getFileName", "(", ")", "!=", "null", "&&", "!", "\"", "\"", ".", "equals", "(", "uploadFile", ".", "getFileName", "(", ")", ")", ")", "{", "created", "=", "newFile", ".", "createNewFile", "(", ")", ";", "if", "(", "created", ")", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "InputStream", "stream", "=", "uploadFile", ".", "getStream", "(", ")", ";", "OutputStream", "bos", "=", "new", "FileOutputStream", "(", "newFile", ")", ";", "int", "bytesRead", "=", "0", ";", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "8192", "]", ";", "while", "(", "(", "bytesRead", "=", "stream", ".", "read", "(", "buffer", ",", "0", ",", "8192", ")", ")", "!=", "-", "1", ")", "{", "bos", ".", "write", "(", "buffer", ",", "0", ",", "bytesRead", ")", ";", "}", "bos", ".", "close", "(", ")", ";", "stream", ".", "close", "(", ")", ";", "}", "}", "else", "if", "(", "template", "!=", "null", ")", "{", "if", "(", "!", "newFile", ".", "exists", "(", ")", ")", "{", "FileUtils", ".", "copyFile", "(", "template", ",", "newFile", ")", ";", "created", "=", "true", ";", "}", "}", "else", "{", "created", "=", "newFile", ".", "createNewFile", "(", ")", ";", "}", "}", "else", "if", "(", "filetype", ".", "equals", "(", "Constants", ".", "DIRECTORY", ")", ")", "{", "created", "=", "newFile", ".", "mkdir", "(", ")", ";", "}", "if", "(", "created", "==", "false", ")", "{", "addErrorMessage", "(", "format", "(", "\"", "error.file.exists", "\"", ",", "newFile", ".", "getName", "(", ")", ")", ")", ";", "return", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "addErrorMessage", "(", "format", "(", "\"", "error.file.write", "\"", ",", "newFile", ".", "getName", "(", ")", ")", ")", ";", "return", ";", "}", "catch", "(", "SecurityException", "se", ")", "{", "addErrorMessage", "(", "format", "(", "\"", "error.file.write", "\"", ",", "newFile", ".", "getName", "(", ")", ")", ")", ";", "return", ";", "}", "LOG", ".", "info", "(", "\"", "DateiNeu.saveItem: Datei ", "\"", "+", "newFile", ".", "getAbsolutePath", "(", ")", "+", "\"", " angelegt", "\"", ")", ";", "cycle", ".", "activate", "(", "\"", "DateiManager", "\"", ")", ";", "}", "public", "void", "init", "(", "IRequestCycle", "cycle", ",", "String", "filepath", ")", "{", "setFilepath", "(", "filepath", ")", ";", "cycle", ".", "activate", "(", "this", ")", ";", "}", "}" ]
Page for creating/uploading a new file/directory.
[ "Page", "for", "creating", "/", "uploading", "a", "new", "file", "/", "directory", "." ]
[ "// prio 1", "// prio 2", "// fill file with content", "// prio 1", "// create file", "// write the file to the file specified", "// close the stream" ]
[ { "param": "AppBasePage", "type": null }, { "param": "PageRenderListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AppBasePage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "PageRenderListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe4fe262fa90561e5c99668b22293b94d1e721e5
emmanuelbernard/hibernate-validator
hibernate-validator/src/main/java/org/hibernate/validator/metadata/site/BeanConstraintSite.java
[ "Apache-2.0" ]
Java
BeanConstraintSite
/** * Instances of this class abstract the constraint type (class, method or field constraint) and give access to * meta data about the constraint. This allows a unified handling of constraints in the validator implementation. * * @author Hardy Ferentschik * @author Gunnar Morling */
Instances of this class abstract the constraint type (class, method or field constraint) and give access to meta data about the constraint. This allows a unified handling of constraints in the validator implementation. @author Hardy Ferentschik @author Gunnar Morling
[ "Instances", "of", "this", "class", "abstract", "the", "constraint", "type", "(", "class", "method", "or", "field", "constraint", ")", "and", "give", "access", "to", "meta", "data", "about", "the", "constraint", ".", "This", "allows", "a", "unified", "handling", "of", "constraints", "in", "the", "validator", "implementation", ".", "@author", "Hardy", "Ferentschik", "@author", "Gunnar", "Morling" ]
public class BeanConstraintSite<T> implements ConstraintSite { /** * The member the constraint was defined on. */ private final Member member; /** * The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a * class level constraint. */ private final String propertyName; /** * The class of the bean hosting this constraint. */ private final Class<T> beanClass; /** * @param beanClass The class in which the constraint is defined on * @param member The member on which the constraint is defined on, {@code null} if it is a class constraint} */ public BeanConstraintSite(Class<T> beanClass, Member member) { this.member = member; if ( this.member != null ) { this.propertyName = ReflectionHelper.getPropertyName( member ); if ( member instanceof Method && propertyName == null ) { // can happen if member is a Method which does not follow the bean convention throw new ValidationException( "Annotated methods must follow the JavaBeans naming convention. " + member.getName() + "() does not." ); } } else { this.propertyName = null; } this.beanClass = beanClass; } public Class<T> getBeanClass() { return beanClass; } public Member getMember() { return member; } /** * @return The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a * class level constraint. */ public String getPropertyName() { return propertyName; } /** * @param o the object from which to retrieve the value. * * @return Returns the value for this constraint from the specified object. Depending on the type either the value itself * is returned of method or field access is used to access the value. */ public Object getValue(Object o) { if ( member == null ) { return o; } else { return ReflectionHelper.getValue( member, o ); } } public Type typeOfAnnotatedElement() { Type t; if ( member == null ) { t = beanClass; } else { t = ReflectionHelper.typeOf( member ); if ( t instanceof Class && ( (Class<?>) t ).isPrimitive() ) { t = ReflectionHelper.boxedType( t ); } } return t; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append( "BeanConstraintSite" ); sb.append( "{beanClass=" ).append( beanClass ); sb.append( ", member=" ).append( member ); sb.append( ", propertyName='" ).append( propertyName ).append( '\'' ); sb.append( '}' ); return sb.toString(); } }
[ "public", "class", "BeanConstraintSite", "<", "T", ">", "implements", "ConstraintSite", "{", "/**\n\t * The member the constraint was defined on.\n\t */", "private", "final", "Member", "member", ";", "/**\n\t * The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a\n\t * class level constraint.\n\t */", "private", "final", "String", "propertyName", ";", "/**\n\t * The class of the bean hosting this constraint.\n\t */", "private", "final", "Class", "<", "T", ">", "beanClass", ";", "/**\n\t * @param beanClass The class in which the constraint is defined on\n\t * @param member The member on which the constraint is defined on, {@code null} if it is a class constraint}\n\t */", "public", "BeanConstraintSite", "(", "Class", "<", "T", ">", "beanClass", ",", "Member", "member", ")", "{", "this", ".", "member", "=", "member", ";", "if", "(", "this", ".", "member", "!=", "null", ")", "{", "this", ".", "propertyName", "=", "ReflectionHelper", ".", "getPropertyName", "(", "member", ")", ";", "if", "(", "member", "instanceof", "Method", "&&", "propertyName", "==", "null", ")", "{", "throw", "new", "ValidationException", "(", "\"", "Annotated methods must follow the JavaBeans naming convention. ", "\"", "+", "member", ".", "getName", "(", ")", "+", "\"", "() does not.", "\"", ")", ";", "}", "}", "else", "{", "this", ".", "propertyName", "=", "null", ";", "}", "this", ".", "beanClass", "=", "beanClass", ";", "}", "public", "Class", "<", "T", ">", "getBeanClass", "(", ")", "{", "return", "beanClass", ";", "}", "public", "Member", "getMember", "(", ")", "{", "return", "member", ";", "}", "/**\n\t * @return The JavaBeans name of the field/property the constraint was placed on. {@code null} if this is a\n\t * class level constraint.\n\t */", "public", "String", "getPropertyName", "(", ")", "{", "return", "propertyName", ";", "}", "/**\n\t * @param o the object from which to retrieve the value.\n\t *\n\t * @return Returns the value for this constraint from the specified object. Depending on the type either the value itself\n\t * is returned of method or field access is used to access the value.\n\t */", "public", "Object", "getValue", "(", "Object", "o", ")", "{", "if", "(", "member", "==", "null", ")", "{", "return", "o", ";", "}", "else", "{", "return", "ReflectionHelper", ".", "getValue", "(", "member", ",", "o", ")", ";", "}", "}", "public", "Type", "typeOfAnnotatedElement", "(", ")", "{", "Type", "t", ";", "if", "(", "member", "==", "null", ")", "{", "t", "=", "beanClass", ";", "}", "else", "{", "t", "=", "ReflectionHelper", ".", "typeOf", "(", "member", ")", ";", "if", "(", "t", "instanceof", "Class", "&&", "(", "(", "Class", "<", "?", ">", ")", "t", ")", ".", "isPrimitive", "(", ")", ")", "{", "t", "=", "ReflectionHelper", ".", "boxedType", "(", "t", ")", ";", "}", "}", "return", "t", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "\"", "BeanConstraintSite", "\"", ")", ";", "sb", ".", "append", "(", "\"", "{beanClass=", "\"", ")", ".", "append", "(", "beanClass", ")", ";", "sb", ".", "append", "(", "\"", ", member=", "\"", ")", ".", "append", "(", "member", ")", ";", "sb", ".", "append", "(", "\"", ", propertyName='", "\"", ")", ".", "append", "(", "propertyName", ")", ".", "append", "(", "'\\''", ")", ";", "sb", ".", "append", "(", "'}'", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}" ]
Instances of this class abstract the constraint type (class, method or field constraint) and give access to meta data about the constraint.
[ "Instances", "of", "this", "class", "abstract", "the", "constraint", "type", "(", "class", "method", "or", "field", "constraint", ")", "and", "give", "access", "to", "meta", "data", "about", "the", "constraint", "." ]
[ "// can happen if member is a Method which does not follow the bean convention" ]
[ { "param": "ConstraintSite", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ConstraintSite", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe52247d18f3431b0676ff2feb0fc34145342a61
Limmen/distributed_networking_project
ID2212project_assignment1/src/main/java/limmen/id2212/nog/server/Listener.java
[ "MIT" ]
Java
Listener
/** * Listener thread that will listen on a specific port for * incomming TCP-connections. Spawns client-handlers with TSV-file to handle * client connections. * @author kim */
Listener thread that will listen on a specific port for incomming TCP-connections. Spawns client-handlers with TSV-file to handle client connections. @author kim
[ "Listener", "thread", "that", "will", "listen", "on", "a", "specific", "port", "for", "incomming", "TCP", "-", "connections", ".", "Spawns", "client", "-", "handlers", "with", "TSV", "-", "file", "to", "handle", "client", "connections", ".", "@author", "kim" ]
public class Listener implements Runnable { private final int PORT; private final File tsvFile; private boolean running; private ServerSocket serverSocket; /** * Alternative constructor if port is not specified, default port is 8080. * @param path */ public Listener(String path){ tsvFile = new File(path); PORT = 8080; } /** * Class constructor. * @param path path to tsv-file * @param port port to listen for tcp-connections */ public Listener(String path, int port){ tsvFile = new File(path); PORT = port; } /** * listen-loop */ @Override public void run() { running = true; try { serverSocket = new ServerSocket(PORT); while (running) { Socket clientSocket = serverSocket.accept(); new Thread(new ClientHandler(clientSocket, tsvFile)).start(); } } catch (IOException e) { System.err.println("Could not listen on port: " + PORT); cleanUp(); terminate(); } } /** * Clean up the serversocket. */ private void cleanUp(){ try{ serverSocket.close(); } catch(Exception e){ running = false; } } /** * Terminates this thread */ private void terminate(){ running = false; } /** * get port number * @return port */ public int getPort(){ return serverSocket.getLocalPort(); } /** * get hostname * @return hostname */ public String getHost(){ return serverSocket.getInetAddress().toString(); } }
[ "public", "class", "Listener", "implements", "Runnable", "{", "private", "final", "int", "PORT", ";", "private", "final", "File", "tsvFile", ";", "private", "boolean", "running", ";", "private", "ServerSocket", "serverSocket", ";", "/**\n * Alternative constructor if port is not specified, default port is 8080.\n * @param path\n */", "public", "Listener", "(", "String", "path", ")", "{", "tsvFile", "=", "new", "File", "(", "path", ")", ";", "PORT", "=", "8080", ";", "}", "/**\n * Class constructor.\n * @param path path to tsv-file\n * @param port port to listen for tcp-connections\n */", "public", "Listener", "(", "String", "path", ",", "int", "port", ")", "{", "tsvFile", "=", "new", "File", "(", "path", ")", ";", "PORT", "=", "port", ";", "}", "/**\n * listen-loop\n */", "@", "Override", "public", "void", "run", "(", ")", "{", "running", "=", "true", ";", "try", "{", "serverSocket", "=", "new", "ServerSocket", "(", "PORT", ")", ";", "while", "(", "running", ")", "{", "Socket", "clientSocket", "=", "serverSocket", ".", "accept", "(", ")", ";", "new", "Thread", "(", "new", "ClientHandler", "(", "clientSocket", ",", "tsvFile", ")", ")", ".", "start", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"", "Could not listen on port: ", "\"", "+", "PORT", ")", ";", "cleanUp", "(", ")", ";", "terminate", "(", ")", ";", "}", "}", "/**\n * Clean up the serversocket.\n */", "private", "void", "cleanUp", "(", ")", "{", "try", "{", "serverSocket", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "running", "=", "false", ";", "}", "}", "/**\n * Terminates this thread\n */", "private", "void", "terminate", "(", ")", "{", "running", "=", "false", ";", "}", "/**\n * get port number\n * @return port\n */", "public", "int", "getPort", "(", ")", "{", "return", "serverSocket", ".", "getLocalPort", "(", ")", ";", "}", "/**\n * get hostname\n * @return hostname\n */", "public", "String", "getHost", "(", ")", "{", "return", "serverSocket", ".", "getInetAddress", "(", ")", ".", "toString", "(", ")", ";", "}", "}" ]
Listener thread that will listen on a specific port for incomming TCP-connections.
[ "Listener", "thread", "that", "will", "listen", "on", "a", "specific", "port", "for", "incomming", "TCP", "-", "connections", "." ]
[]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe5253651ea2807d158e63f28cb72f885a21afd8
geodb/db3dcore
src/de/uos/igf/db3d/dbms/geom/Rectangle3D.java
[ "Apache-2.0" ]
Java
Rectangle3D
/** * Class Rectangle3D - represents faces of a minimum bounding box oriented to * axes in the 3rd dimension. <br> * Provides geometric operations like intersects, intersection computation... * * @author Wolfgang Baer / University of Osnabrueck */
Class Rectangle3D - represents faces of a minimum bounding box oriented to axes in the 3rd dimension. Provides geometric operations like intersects, intersection computation @author Wolfgang Baer / University of Osnabrueck
[ "Class", "Rectangle3D", "-", "represents", "faces", "of", "a", "minimum", "bounding", "box", "oriented", "to", "axes", "in", "the", "3rd", "dimension", ".", "Provides", "geometric", "operations", "like", "intersects", "intersection", "computation", "@author", "Wolfgang", "Baer", "/", "University", "of", "Osnabrueck" ]
public class Rectangle3D { /* geometry */ /* point 0 */ private Point3D zero; /* point 1 */ private Point3D one; /* point 2 */ private Point3D two; /* point 3 */ private Point3D three; /** * Constructor for single points. <br> * Constructs a Rectangle3D object with given Point3Ds p0, p1, p2, p3. * Points must be in order p0->p1->p2->p3 - so that there is no edge between * p0 and p2 and between p1 and p3, respectively p0 is opposite corner to p2 * and p1 to p3. <br> * Validity is not tested ! * * @param p0 * Point3D 0 * @param p1 * Point3D 1 * @param p2 * Point3D 2 * @param p3 * Point3D 3 */ public Rectangle3D(Point3D p0, Point3D p1, Point3D p2, Point3D p3) { this.zero = p0; this.one = p1; this.two = p2; this.three = p3; } /** * Returns point at given index. * * @param index * int index of the point * @return Point3D at the given index. * @throws IllegalStateException * - if index is not 0, 1, 2 or 3. */ public Point3D getPoint(int index) { switch (index) { case 0: return this.zero; case 1: return this.one; case 2: return this.two; case 3: return this.three; default: // FIXME Fix this weird switch(index) stuff throw new IllegalStateException(Db3dSimpleResourceBundle .getString("db3d.geom.rectonlyfour")); } } /** * Returns the points as an array of length = 4.<br> * Order is zero, one, two and three. * * @return Point3D[] with the points of this. */ public Point3D[] getPoints() { Point3D[] points = { this.zero, this.one, this.two, this.three }; return points; } /** * Returns Segment3D object for point i (in direction (i+1)). Returns * <code>null</null> if case of flat rectangle when point i equals point (i+1). * * @param index * int index of the point * @return Segment3D. * @throws IllegalStateException * - if the index of a Point3D in a Rectangle3D is not in the * interval [0, 3]. */ public Segment3D getSegment(int index) { if (this.getPoint(index).equals(this.getPoint((index + 1) % 4))) return null; return new Segment3D(this.getPoint(index), this .getPoint((index + 1) % 4), null); } /** * Returns the segments of this rectangle. Returns an empty array if the * rectangle is a point. * * @return Segment3D[] of this. * @throws IllegalStateException * - if the index of a Point3D in a Rectangle3D is not in the * interval [0, 3]. */ public Segment3D[] getSegments() { if (this.getPoint(0).equals(this.getPoint(2))) return new Segment3D[0]; if (this.getPoint(0).equals(this.getPoint(1))) return new Segment3D[] { this.getSegment(1) }; if (this.getPoint(0).equals(this.getPoint(3))) return new Segment3D[] { this.getSegment(0) }; Segment3D[] seg = new Segment3D[4]; for (int i = 0; i < 4; i++) { seg[i] = this.getSegment(i); } return seg; } /** * Sets the given point at given index. * * @param index * int index of the point * @param point * Point3D to be set * @throws IllegalStateException * if index is not 0, 1, 2 or 3. */ public void setPoint(int index, Point3D point) { switch (index) { case 0: this.zero = point; break; case 1: this.one = point; break; case 2: this.two = point; break; case 3: this.three = point; break; default: // FIXME Fix this weird switch(index) stuff throw new IllegalStateException(Db3dSimpleResourceBundle .getString("db3d.geom.rectonlyfour")); } } /** * Returns the intersection of this with given line.<br> * * @param line * Line3D for intersection * @param sop * ScalarOperator * @return SimpleGeoObj - result of intersection. * @throws IllegalStateException * - if the intersectsInt(Line3D line, ScalarOperator sop) * method of the class Line3D (which computes the intersection * of two lines) called by this method returns a value that is * not -2, -1, 0 or 1. * @throws ArithmeticException * - if norm equals zero in epsilon range. This exception * originates in the method normalize(ScalarOperator) of the * class Vector3D. */ public SimpleGeoObj intersectionInPlane(Line3D line, ScalarOperator sop) { SimpleGeoObj obj = null; EquivalentableHashSet pointHS = new EquivalentableHashSet(10, sop, Equivalentable.GEOMETRY_EQUIVALENT); for (int n = 0; n < 4; n++) { // for all segments int k = (n + 1) % 4; Segment3D seg = new Segment3D(this.getPoint(n), this.getPoint(k), sop); obj = seg.intersection(line, sop); if (obj != null) { if (obj.getType() == SimpleGeoObj.SEGMENT3D) return obj; // else obj must be of type POINT3D pointHS.add(obj); } } Point3D[] points = (Point3D[]) pointHS.toArray(new Point3D[pointHS .size()]); int length = points.length; if (length == 1) return points[0]; if (length == 2) return new Segment3D(points[0], points[1], sop); return null; // if line doesn't intersect rectangle } /** * Returns intersection result of this with plane.<br> * Result can be <code>null</code>, Point3D, Segment3D or Wireframe3D. * * @param plane * Plane3D for intersection * @param sop * ScalarOperator * @return SimpleGeoObj - result of intersection. * @throws IllegalStateException * - if the index of a Point3D in a Rectangle3D is not in the * interval [0, 3]. * @throws IllegalStateException * - signals Problems with the dimension of the wireframe. * @throws ArithmeticException * - if norm equals zero in epsilon range. This exception * originates in the method normalize(ScalarOperator) of the * class Vector3D. */ public SimpleGeoObj intersection(Plane3D plane, ScalarOperator sop) { Segment3D[] seg = this.getSegments(); int length = seg.length; if (length == 0) return this.getPoint(0).intersection(plane, sop); EquivalentableHashSet pointHS = new EquivalentableHashSet(6, sop, Equivalentable.GEOMETRY_EQUIVALENT); int segCounter = 0; for (int i = 0; i < length; i++) { SimpleGeoObj obj = seg[i].intersection(plane, sop); if (obj != null) { if (obj.getType() == SimpleGeoObj.POINT3D) pointHS.add(obj); if (obj.getType() == SimpleGeoObj.SEGMENT3D) { segCounter++; pointHS.add(seg[i].getPoint(0)); pointHS.add(seg[i].getPoint(1)); if (segCounter == 2) { Wireframe3D wf = new Wireframe3D(sop); wf.add(seg); return wf; } } } } Iterator<Point3D> it = pointHS.iterator(); if (pointHS.size() == 2) return new Segment3D(it.next(), it.next(), sop); else if (pointHS.size() == 1) return it.next(); else return null; } @Override /** * Converts this to string. * @return String with the information of this. */ public String toString() { return "Rectangle3D [one=" + one + ", three=" + three + ", two=" + two + ", zero=" + zero + "]"; } }
[ "public", "class", "Rectangle3D", "{", "/* geometry */", "/* point 0 */", "private", "Point3D", "zero", ";", "/* point 1 */", "private", "Point3D", "one", ";", "/* point 2 */", "private", "Point3D", "two", ";", "/* point 3 */", "private", "Point3D", "three", ";", "/**\n\t * Constructor for single points. <br>\n\t * Constructs a Rectangle3D object with given Point3Ds p0, p1, p2, p3.\n\t * Points must be in order p0->p1->p2->p3 - so that there is no edge between\n\t * p0 and p2 and between p1 and p3, respectively p0 is opposite corner to p2\n\t * and p1 to p3. <br>\n\t * Validity is not tested !\n\t * \n\t * @param p0\n\t * Point3D 0\n\t * @param p1\n\t * Point3D 1\n\t * @param p2\n\t * Point3D 2\n\t * @param p3\n\t * Point3D 3\n\t */", "public", "Rectangle3D", "(", "Point3D", "p0", ",", "Point3D", "p1", ",", "Point3D", "p2", ",", "Point3D", "p3", ")", "{", "this", ".", "zero", "=", "p0", ";", "this", ".", "one", "=", "p1", ";", "this", ".", "two", "=", "p2", ";", "this", ".", "three", "=", "p3", ";", "}", "/**\n\t * Returns point at given index.\n\t * \n\t * @param index\n\t * int index of the point\n\t * @return Point3D at the given index.\n\t * @throws IllegalStateException\n\t * - if index is not 0, 1, 2 or 3.\n\t */", "public", "Point3D", "getPoint", "(", "int", "index", ")", "{", "switch", "(", "index", ")", "{", "case", "0", ":", "return", "this", ".", "zero", ";", "case", "1", ":", "return", "this", ".", "one", ";", "case", "2", ":", "return", "this", ".", "two", ";", "case", "3", ":", "return", "this", ".", "three", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "Db3dSimpleResourceBundle", ".", "getString", "(", "\"", "db3d.geom.rectonlyfour", "\"", ")", ")", ";", "}", "}", "/**\n\t * Returns the points as an array of length = 4.<br>\n\t * Order is zero, one, two and three.\n\t * \n\t * @return Point3D[] with the points of this.\n\t */", "public", "Point3D", "[", "]", "getPoints", "(", ")", "{", "Point3D", "[", "]", "points", "=", "{", "this", ".", "zero", ",", "this", ".", "one", ",", "this", ".", "two", ",", "this", ".", "three", "}", ";", "return", "points", ";", "}", "/**\n\t * Returns Segment3D object for point i (in direction (i+1)). Returns\n\t * <code>null</null> if case of flat rectangle when point i equals point (i+1).\n\t * \n\t * @param index\n\t * int index of the point\n\t * @return Segment3D.\n\t * @throws IllegalStateException\n\t * - if the index of a Point3D in a Rectangle3D is not in the\n\t * interval [0, 3].\n\t */", "public", "Segment3D", "getSegment", "(", "int", "index", ")", "{", "if", "(", "this", ".", "getPoint", "(", "index", ")", ".", "equals", "(", "this", ".", "getPoint", "(", "(", "index", "+", "1", ")", "%", "4", ")", ")", ")", "return", "null", ";", "return", "new", "Segment3D", "(", "this", ".", "getPoint", "(", "index", ")", ",", "this", ".", "getPoint", "(", "(", "index", "+", "1", ")", "%", "4", ")", ",", "null", ")", ";", "}", "/**\n\t * Returns the segments of this rectangle. Returns an empty array if the\n\t * rectangle is a point.\n\t * \n\t * @return Segment3D[] of this.\n\t * @throws IllegalStateException\n\t * - if the index of a Point3D in a Rectangle3D is not in the\n\t * interval [0, 3].\n\t */", "public", "Segment3D", "[", "]", "getSegments", "(", ")", "{", "if", "(", "this", ".", "getPoint", "(", "0", ")", ".", "equals", "(", "this", ".", "getPoint", "(", "2", ")", ")", ")", "return", "new", "Segment3D", "[", "0", "]", ";", "if", "(", "this", ".", "getPoint", "(", "0", ")", ".", "equals", "(", "this", ".", "getPoint", "(", "1", ")", ")", ")", "return", "new", "Segment3D", "[", "]", "{", "this", ".", "getSegment", "(", "1", ")", "}", ";", "if", "(", "this", ".", "getPoint", "(", "0", ")", ".", "equals", "(", "this", ".", "getPoint", "(", "3", ")", ")", ")", "return", "new", "Segment3D", "[", "]", "{", "this", ".", "getSegment", "(", "0", ")", "}", ";", "Segment3D", "[", "]", "seg", "=", "new", "Segment3D", "[", "4", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "seg", "[", "i", "]", "=", "this", ".", "getSegment", "(", "i", ")", ";", "}", "return", "seg", ";", "}", "/**\n\t * Sets the given point at given index.\n\t * \n\t * @param index\n\t * int index of the point\n\t * @param point\n\t * Point3D to be set\n\t * @throws IllegalStateException\n\t * if index is not 0, 1, 2 or 3.\n\t */", "public", "void", "setPoint", "(", "int", "index", ",", "Point3D", "point", ")", "{", "switch", "(", "index", ")", "{", "case", "0", ":", "this", ".", "zero", "=", "point", ";", "break", ";", "case", "1", ":", "this", ".", "one", "=", "point", ";", "break", ";", "case", "2", ":", "this", ".", "two", "=", "point", ";", "break", ";", "case", "3", ":", "this", ".", "three", "=", "point", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "Db3dSimpleResourceBundle", ".", "getString", "(", "\"", "db3d.geom.rectonlyfour", "\"", ")", ")", ";", "}", "}", "/**\n\t * Returns the intersection of this with given line.<br>\n\t * \n\t * @param line\n\t * Line3D for intersection\n\t * @param sop\n\t * ScalarOperator\n\t * @return SimpleGeoObj - result of intersection.\n\t * @throws IllegalStateException\n\t * - if the intersectsInt(Line3D line, ScalarOperator sop)\n\t * method of the class Line3D (which computes the intersection\n\t * of two lines) called by this method returns a value that is\n\t * not -2, -1, 0 or 1.\n\t * @throws ArithmeticException\n\t * - if norm equals zero in epsilon range. This exception\n\t * originates in the method normalize(ScalarOperator) of the\n\t * class Vector3D.\n\t */", "public", "SimpleGeoObj", "intersectionInPlane", "(", "Line3D", "line", ",", "ScalarOperator", "sop", ")", "{", "SimpleGeoObj", "obj", "=", "null", ";", "EquivalentableHashSet", "pointHS", "=", "new", "EquivalentableHashSet", "(", "10", ",", "sop", ",", "Equivalentable", ".", "GEOMETRY_EQUIVALENT", ")", ";", "for", "(", "int", "n", "=", "0", ";", "n", "<", "4", ";", "n", "++", ")", "{", "int", "k", "=", "(", "n", "+", "1", ")", "%", "4", ";", "Segment3D", "seg", "=", "new", "Segment3D", "(", "this", ".", "getPoint", "(", "n", ")", ",", "this", ".", "getPoint", "(", "k", ")", ",", "sop", ")", ";", "obj", "=", "seg", ".", "intersection", "(", "line", ",", "sop", ")", ";", "if", "(", "obj", "!=", "null", ")", "{", "if", "(", "obj", ".", "getType", "(", ")", "==", "SimpleGeoObj", ".", "SEGMENT3D", ")", "return", "obj", ";", "pointHS", ".", "add", "(", "obj", ")", ";", "}", "}", "Point3D", "[", "]", "points", "=", "(", "Point3D", "[", "]", ")", "pointHS", ".", "toArray", "(", "new", "Point3D", "[", "pointHS", ".", "size", "(", ")", "]", ")", ";", "int", "length", "=", "points", ".", "length", ";", "if", "(", "length", "==", "1", ")", "return", "points", "[", "0", "]", ";", "if", "(", "length", "==", "2", ")", "return", "new", "Segment3D", "(", "points", "[", "0", "]", ",", "points", "[", "1", "]", ",", "sop", ")", ";", "return", "null", ";", "}", "/**\n\t * Returns intersection result of this with plane.<br>\n\t * Result can be <code>null</code>, Point3D, Segment3D or Wireframe3D.\n\t * \n\t * @param plane\n\t * Plane3D for intersection\n\t * @param sop\n\t * ScalarOperator\n\t * @return SimpleGeoObj - result of intersection.\n\t * @throws IllegalStateException\n\t * - if the index of a Point3D in a Rectangle3D is not in the\n\t * interval [0, 3].\n\t * @throws IllegalStateException\n\t * - signals Problems with the dimension of the wireframe.\n\t * @throws ArithmeticException\n\t * - if norm equals zero in epsilon range. This exception\n\t * originates in the method normalize(ScalarOperator) of the\n\t * class Vector3D.\n\t */", "public", "SimpleGeoObj", "intersection", "(", "Plane3D", "plane", ",", "ScalarOperator", "sop", ")", "{", "Segment3D", "[", "]", "seg", "=", "this", ".", "getSegments", "(", ")", ";", "int", "length", "=", "seg", ".", "length", ";", "if", "(", "length", "==", "0", ")", "return", "this", ".", "getPoint", "(", "0", ")", ".", "intersection", "(", "plane", ",", "sop", ")", ";", "EquivalentableHashSet", "pointHS", "=", "new", "EquivalentableHashSet", "(", "6", ",", "sop", ",", "Equivalentable", ".", "GEOMETRY_EQUIVALENT", ")", ";", "int", "segCounter", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "SimpleGeoObj", "obj", "=", "seg", "[", "i", "]", ".", "intersection", "(", "plane", ",", "sop", ")", ";", "if", "(", "obj", "!=", "null", ")", "{", "if", "(", "obj", ".", "getType", "(", ")", "==", "SimpleGeoObj", ".", "POINT3D", ")", "pointHS", ".", "add", "(", "obj", ")", ";", "if", "(", "obj", ".", "getType", "(", ")", "==", "SimpleGeoObj", ".", "SEGMENT3D", ")", "{", "segCounter", "++", ";", "pointHS", ".", "add", "(", "seg", "[", "i", "]", ".", "getPoint", "(", "0", ")", ")", ";", "pointHS", ".", "add", "(", "seg", "[", "i", "]", ".", "getPoint", "(", "1", ")", ")", ";", "if", "(", "segCounter", "==", "2", ")", "{", "Wireframe3D", "wf", "=", "new", "Wireframe3D", "(", "sop", ")", ";", "wf", ".", "add", "(", "seg", ")", ";", "return", "wf", ";", "}", "}", "}", "}", "Iterator", "<", "Point3D", ">", "it", "=", "pointHS", ".", "iterator", "(", ")", ";", "if", "(", "pointHS", ".", "size", "(", ")", "==", "2", ")", "return", "new", "Segment3D", "(", "it", ".", "next", "(", ")", ",", "it", ".", "next", "(", ")", ",", "sop", ")", ";", "else", "if", "(", "pointHS", ".", "size", "(", ")", "==", "1", ")", "return", "it", ".", "next", "(", ")", ";", "else", "return", "null", ";", "}", "@", "Override", "/**\n\t * Converts this to string.\n\t * @return String with the information of this.\n\t */", "public", "String", "toString", "(", ")", "{", "return", "\"", "Rectangle3D [one=", "\"", "+", "one", "+", "\"", ", three=", "\"", "+", "three", "+", "\"", ", two=", "\"", "+", "two", "+", "\"", ", zero=", "\"", "+", "zero", "+", "\"", "]", "\"", ";", "}", "}" ]
Class Rectangle3D - represents faces of a minimum bounding box oriented to axes in the 3rd dimension.
[ "Class", "Rectangle3D", "-", "represents", "faces", "of", "a", "minimum", "bounding", "box", "oriented", "to", "axes", "in", "the", "3rd", "dimension", "." ]
[ "// FIXME Fix this weird switch(index) stuff", "// FIXME Fix this weird switch(index) stuff", "// for all segments", "// else obj must be of type POINT3D", "// if line doesn't intersect rectangle" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe58831653457d51b3cec9b9785b5f31d15e03e9
j-hudecek/hmftools
ensembl-db/src/main/java/org/ensembl/database/homo_sapiens_core/tables/records/CoordSystemRecord.java
[ "MIT" ]
Java
CoordSystemRecord
/** * This class is generated by jOOQ. */
This class is generated by jOOQ.
[ "This", "class", "is", "generated", "by", "jOOQ", "." ]
@Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CoordSystemRecord extends UpdatableRecordImpl<CoordSystemRecord> implements Record6<UInteger, UInteger, String, String, Integer, String> { private static final long serialVersionUID = -127119356; /** * Setter for <code>homo_sapiens_core_89_37.coord_system.coord_system_id</code>. */ public void setCoordSystemId(UInteger value) { set(0, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.coord_system_id</code>. */ public UInteger getCoordSystemId() { return (UInteger) get(0); } /** * Setter for <code>homo_sapiens_core_89_37.coord_system.species_id</code>. */ public void setSpeciesId(UInteger value) { set(1, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.species_id</code>. */ public UInteger getSpeciesId() { return (UInteger) get(1); } /** * Setter for <code>homo_sapiens_core_89_37.coord_system.name</code>. */ public void setName(String value) { set(2, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.name</code>. */ public String getName() { return (String) get(2); } /** * Setter for <code>homo_sapiens_core_89_37.coord_system.version</code>. */ public void setVersion(String value) { set(3, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.version</code>. */ public String getVersion() { return (String) get(3); } /** * Setter for <code>homo_sapiens_core_89_37.coord_system.rank</code>. */ public void setRank(Integer value) { set(4, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.rank</code>. */ public Integer getRank() { return (Integer) get(4); } /** * Setter for <code>homo_sapiens_core_89_37.coord_system.attrib</code>. */ public void setAttrib(String value) { set(5, value); } /** * Getter for <code>homo_sapiens_core_89_37.coord_system.attrib</code>. */ public String getAttrib() { return (String) get(5); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<UInteger> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record6 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row6<UInteger, UInteger, String, String, Integer, String> fieldsRow() { return (Row6) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row6<UInteger, UInteger, String, String, Integer, String> valuesRow() { return (Row6) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<UInteger> field1() { return CoordSystem.COORD_SYSTEM.COORD_SYSTEM_ID; } /** * {@inheritDoc} */ @Override public Field<UInteger> field2() { return CoordSystem.COORD_SYSTEM.SPECIES_ID; } /** * {@inheritDoc} */ @Override public Field<String> field3() { return CoordSystem.COORD_SYSTEM.NAME; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return CoordSystem.COORD_SYSTEM.VERSION; } /** * {@inheritDoc} */ @Override public Field<Integer> field5() { return CoordSystem.COORD_SYSTEM.RANK; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return CoordSystem.COORD_SYSTEM.ATTRIB; } /** * {@inheritDoc} */ @Override public UInteger value1() { return getCoordSystemId(); } /** * {@inheritDoc} */ @Override public UInteger value2() { return getSpeciesId(); } /** * {@inheritDoc} */ @Override public String value3() { return getName(); } /** * {@inheritDoc} */ @Override public String value4() { return getVersion(); } /** * {@inheritDoc} */ @Override public Integer value5() { return getRank(); } /** * {@inheritDoc} */ @Override public String value6() { return getAttrib(); } /** * {@inheritDoc} */ @Override public CoordSystemRecord value1(UInteger value) { setCoordSystemId(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord value2(UInteger value) { setSpeciesId(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord value3(String value) { setName(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord value4(String value) { setVersion(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord value5(Integer value) { setRank(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord value6(String value) { setAttrib(value); return this; } /** * {@inheritDoc} */ @Override public CoordSystemRecord values(UInteger value1, UInteger value2, String value3, String value4, Integer value5, String value6) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached CoordSystemRecord */ public CoordSystemRecord() { super(CoordSystem.COORD_SYSTEM); } /** * Create a detached, initialised CoordSystemRecord */ public CoordSystemRecord(UInteger coordSystemId, UInteger speciesId, String name, String version, Integer rank, String attrib) { super(CoordSystem.COORD_SYSTEM); set(0, coordSystemId); set(1, speciesId); set(2, name); set(3, version); set(4, rank); set(5, attrib); } }
[ "@", "Generated", "(", "value", "=", "{", "\"", "http://www.jooq.org", "\"", ",", "\"", "jOOQ version:3.9.5", "\"", "}", ",", "comments", "=", "\"", "This class is generated by jOOQ", "\"", ")", "@", "SuppressWarnings", "(", "{", "\"", "all", "\"", ",", "\"", "unchecked", "\"", ",", "\"", "rawtypes", "\"", "}", ")", "public", "class", "CoordSystemRecord", "extends", "UpdatableRecordImpl", "<", "CoordSystemRecord", ">", "implements", "Record6", "<", "UInteger", ",", "UInteger", ",", "String", ",", "String", ",", "Integer", ",", "String", ">", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "127119356", ";", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.coord_system_id</code>.\n */", "public", "void", "setCoordSystemId", "(", "UInteger", "value", ")", "{", "set", "(", "0", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.coord_system_id</code>.\n */", "public", "UInteger", "getCoordSystemId", "(", ")", "{", "return", "(", "UInteger", ")", "get", "(", "0", ")", ";", "}", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.species_id</code>.\n */", "public", "void", "setSpeciesId", "(", "UInteger", "value", ")", "{", "set", "(", "1", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.species_id</code>.\n */", "public", "UInteger", "getSpeciesId", "(", ")", "{", "return", "(", "UInteger", ")", "get", "(", "1", ")", ";", "}", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.name</code>.\n */", "public", "void", "setName", "(", "String", "value", ")", "{", "set", "(", "2", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.name</code>.\n */", "public", "String", "getName", "(", ")", "{", "return", "(", "String", ")", "get", "(", "2", ")", ";", "}", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.version</code>.\n */", "public", "void", "setVersion", "(", "String", "value", ")", "{", "set", "(", "3", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.version</code>.\n */", "public", "String", "getVersion", "(", ")", "{", "return", "(", "String", ")", "get", "(", "3", ")", ";", "}", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.rank</code>.\n */", "public", "void", "setRank", "(", "Integer", "value", ")", "{", "set", "(", "4", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.rank</code>.\n */", "public", "Integer", "getRank", "(", ")", "{", "return", "(", "Integer", ")", "get", "(", "4", ")", ";", "}", "/**\n * Setter for <code>homo_sapiens_core_89_37.coord_system.attrib</code>.\n */", "public", "void", "setAttrib", "(", "String", "value", ")", "{", "set", "(", "5", ",", "value", ")", ";", "}", "/**\n * Getter for <code>homo_sapiens_core_89_37.coord_system.attrib</code>.\n */", "public", "String", "getAttrib", "(", ")", "{", "return", "(", "String", ")", "get", "(", "5", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Record1", "<", "UInteger", ">", "key", "(", ")", "{", "return", "(", "Record1", ")", "super", ".", "key", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Row6", "<", "UInteger", ",", "UInteger", ",", "String", ",", "String", ",", "Integer", ",", "String", ">", "fieldsRow", "(", ")", "{", "return", "(", "Row6", ")", "super", ".", "fieldsRow", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Row6", "<", "UInteger", ",", "UInteger", ",", "String", ",", "String", ",", "Integer", ",", "String", ">", "valuesRow", "(", ")", "{", "return", "(", "Row6", ")", "super", ".", "valuesRow", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "UInteger", ">", "field1", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "COORD_SYSTEM_ID", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "UInteger", ">", "field2", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "SPECIES_ID", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "String", ">", "field3", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "NAME", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "String", ">", "field4", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "VERSION", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "Integer", ">", "field5", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "RANK", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Field", "<", "String", ">", "field6", "(", ")", "{", "return", "CoordSystem", ".", "COORD_SYSTEM", ".", "ATTRIB", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "UInteger", "value1", "(", ")", "{", "return", "getCoordSystemId", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "UInteger", "value2", "(", ")", "{", "return", "getSpeciesId", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "String", "value3", "(", ")", "{", "return", "getName", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "String", "value4", "(", ")", "{", "return", "getVersion", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "Integer", "value5", "(", ")", "{", "return", "getRank", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "String", "value6", "(", ")", "{", "return", "getAttrib", "(", ")", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value1", "(", "UInteger", "value", ")", "{", "setCoordSystemId", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value2", "(", "UInteger", "value", ")", "{", "setSpeciesId", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value3", "(", "String", "value", ")", "{", "setName", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value4", "(", "String", "value", ")", "{", "setVersion", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value5", "(", "Integer", "value", ")", "{", "setRank", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "value6", "(", "String", "value", ")", "{", "setAttrib", "(", "value", ")", ";", "return", "this", ";", "}", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "CoordSystemRecord", "values", "(", "UInteger", "value1", ",", "UInteger", "value2", ",", "String", "value3", ",", "String", "value4", ",", "Integer", "value5", ",", "String", "value6", ")", "{", "value1", "(", "value1", ")", ";", "value2", "(", "value2", ")", ";", "value3", "(", "value3", ")", ";", "value4", "(", "value4", ")", ";", "value5", "(", "value5", ")", ";", "value6", "(", "value6", ")", ";", "return", "this", ";", "}", "/**\n * Create a detached CoordSystemRecord\n */", "public", "CoordSystemRecord", "(", ")", "{", "super", "(", "CoordSystem", ".", "COORD_SYSTEM", ")", ";", "}", "/**\n * Create a detached, initialised CoordSystemRecord\n */", "public", "CoordSystemRecord", "(", "UInteger", "coordSystemId", ",", "UInteger", "speciesId", ",", "String", "name", ",", "String", "version", ",", "Integer", "rank", ",", "String", "attrib", ")", "{", "super", "(", "CoordSystem", ".", "COORD_SYSTEM", ")", ";", "set", "(", "0", ",", "coordSystemId", ")", ";", "set", "(", "1", ",", "speciesId", ")", ";", "set", "(", "2", ",", "name", ")", ";", "set", "(", "3", ",", "version", ")", ";", "set", "(", "4", ",", "rank", ")", ";", "set", "(", "5", ",", "attrib", ")", ";", "}", "}" ]
This class is generated by jOOQ.
[ "This", "class", "is", "generated", "by", "jOOQ", "." ]
[ "// -------------------------------------------------------------------------", "// Primary key information", "// -------------------------------------------------------------------------", "// -------------------------------------------------------------------------", "// Record6 type implementation", "// -------------------------------------------------------------------------", "// -------------------------------------------------------------------------", "// Constructors", "// -------------------------------------------------------------------------" ]
[ { "param": "Record6<UInteger, UInteger, String, String, Integer, String>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Record6<UInteger, UInteger, String, String, Integer, String>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe5f2ef748eae1aa3f806dc26be8e0ad96c475a7
suvarchal/IDV-dev-old
src/ucar/unidata/idv/ui/DataControlDialog.java
[ "CNRI-Jython" ]
Java
DataControlDialog
/** * This class provides a list of the display controls and the data selection dialog * * @author Jeff McWhirter * @version $Revision: 1.98 $ */
This class provides a list of the display controls and the data selection dialog @author Jeff McWhirter @version $Revision: 1.98 $
[ "This", "class", "provides", "a", "list", "of", "the", "display", "controls", "and", "the", "data", "selection", "dialog", "@author", "Jeff", "McWhirter", "@version", "$Revision", ":", "1", ".", "98", "$" ]
public class DataControlDialog implements ActionListener { /** Reference to the idv */ private IntegratedDataViewer idv; /** The JDialog window object */ private JDialog dialog; /** The gui contents */ JComponent contents; /** Should we layout the display/control lists horizontally */ private boolean horizontalOrientation = false; /** * We keep a list of the buttons that can be used for creation * so we can enable/disable all them as needed. */ List createBtns = new ArrayList(); /** A mutex for when we enable/disable the create buttons */ private Object ENABLE_MUTEX = new Object(); /** The top label */ JLabel label; /** The JTree that holds the {@link ucar.unidata.idv.ControlDescriptor} hierarchy */ JTree controlTree; /** A mutex for accesing the control tree */ private Object CONTROLTREE_MUTEX; /** The root of the {@link ucar.unidata.idv.ControlDescriptor} hierarchy */ DefaultMutableTreeNode controlTreeRoot; /** THe tree model used for the control descriptors */ DefaultTreeModel controlTreeModel; /** Mapping from ControlDescriptor to tree node */ private Hashtable cdToNode = new Hashtable(); /** * The first control descriptor we show. * Keep this around so we can always have one selected * when a new tree is created. */ private ControlDescriptor firstCd; /** The wrapper for the display list */ JComponent displayScroller; /** The data selection widget */ private DataSelectionWidget dataSelectionWidget; /** The data source */ DataSource dataSource; /** The data choice */ DataChoice dataChoice; /** This class can be in its own window or be part of an other gui */ private boolean inOwnWindow = true; /** * Constructor for when we are a part of the {@link DataSelector} * * @param idv Reference to the IDV * @param inOwnWindow Should this object be in its own window * @param horizontalOrientation Show display/times hor? * */ public DataControlDialog(IntegratedDataViewer idv, boolean inOwnWindow, boolean horizontalOrientation) { this.inOwnWindow = inOwnWindow; this.horizontalOrientation = horizontalOrientation; init(idv, null, 50, 50); } /** * Constructor for configuring a {@link ucar.unidata.data.DataChoice} * * @param idv Reference to the IDV * @param dataChoice The {@link ucar.unidata.data.DataChoice} we are configuring * @param x X position on the screen to show window * @param y Y position on the screen to show window * */ public DataControlDialog(IntegratedDataViewer idv, DataChoice dataChoice, int x, int y) { init(idv, dataChoice, x, y); } /** * Initialize the gui. Popup a new Window if required. * * @param idv The IDV * @param dataChoice The {@link DataChoice} we are configuring (or null) * @param windowX X position on the screen to show window * @param windowY Y position on the screen to show window */ private void init(IntegratedDataViewer idv, DataChoice dataChoice, int windowX, int windowY) { this.idv = idv; this.dataChoice = dataChoice; contents = doMakeDataChoiceDialog(dataChoice); if (inOwnWindow) { doMakeWindow(GuiUtils.centerBottom(contents, GuiUtils.makeApplyOkCancelButtons(this)), windowX, windowY, "Select Display"); } } /** * We keep track of the "Create" buttons so we can enable/disable them * * @param b The create button to add into the list */ public void addCreateButton(JButton b) { createBtns.add(b); b.setEnabled(getSelectedControl() != null); } /** * Return the gui contents * @return The gui contents */ public JComponent getContents() { return contents; } /** * Utility to set the cursor on the gui contents * * @param cursor The cursor to set */ public void setCursor(Cursor cursor) { contents.setCursor(cursor); } /** * Set the data source * * @param ds The new data source */ public void setDataSource(DataSource ds) { dataSource = ds; } /** * Called by the DataSelector to handle when the data source has changed * * @param dataSource The data source that changed */ public void dataSourceChanged(DataSource dataSource) { if (this.dataSource == null) { setDataChoice(dataChoice); return; } if (this.dataSource != dataSource) { return; } dataSelectionWidget.dataSourceChanged(dataSource); } /** * Return the {@link ucar.unidata.idv.ControlDescriptor} that is currently selected * * @return Selected ControlDescriptor */ protected ControlDescriptor getSelectedControl() { if (controlTree == null) { return null; } List l = getSelectedControlsFromTree(); if (l.size() > 0) { return (ControlDescriptor) l.get(0); } else { return null; } } /** * Find and return the list of {@link ucar.unidata.idv.ControlDescriptor}-s * that have been selected in the JTree * * @return List of control descriptors */ private List getSelectedControlsFromTree() { TreePath[] paths; synchronized (CONTROLTREE_MUTEX) { paths = controlTree.getSelectionModel().getSelectionPaths(); } List descriptors = new ArrayList(); if (paths == null) { return descriptors; } for (int i = 0; i < paths.length; i++) { Object last = paths[i].getLastPathComponent(); if (last == null) { continue; } Object object = ((DefaultMutableTreeNode) last).getUserObject(); if ( !(object instanceof ControlDescriptor)) { continue; } descriptors.add(object); } return descriptors; } /** * Find and return the array of selected {@link ucar.unidata.idv.ControlDescriptor}-s * * @return Select control descriptors */ public Object[] getSelectedControls() { return getSelectedControlsFromTree().toArray(); } /** * Add the given list of {@link ucar.unidata.idv.ControlDescriptor}-s * int othe Tree. * * @param v List of new {@link ucar.unidata.idv.ControlDescriptor}-s */ private void setControlList(Vector v) { synchronized (CONTROLTREE_MUTEX) { List openCds = new ArrayList(); Enumeration paths = controlTree.getExpandedDescendants( new TreePath(controlTreeRoot.getPath())); if (paths != null) { while (paths.hasMoreElements()) { TreePath path = (TreePath) paths.nextElement(); DefaultMutableTreeNode last = (DefaultMutableTreeNode) path.getLastPathComponent(); Enumeration nodeChildren = last.children(); while (nodeChildren.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) nodeChildren .nextElement(); if (child.getUserObject() instanceof ControlDescriptor) { openCds.add(child.getUserObject()); } } } } cdToNode = new Hashtable(); firstCd = null; controlTreeRoot.removeAllChildren(); List leafNodes = new ArrayList(); Hashtable nodes = new Hashtable(); for (int i = 0; i < v.size(); i++) { ControlDescriptor cd = (ControlDescriptor) v.get(i); String displayCategory = cd.getDisplayCategory(); DefaultMutableTreeNode parentNode = controlTreeRoot; String catSoFar = ""; List cats = StringUtil.split(displayCategory, "/", true, true); for (int catIdx = 0; catIdx < cats.size(); catIdx++) { String subCat = (String) cats.get(catIdx); catSoFar = catSoFar + "/" + subCat; DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.get(catSoFar); if (node == null) { node = new DefaultMutableTreeNode(subCat); parentNode.add(node); nodes.put(catSoFar, node); } parentNode = node; } if (firstCd == null) { firstCd = cd; } DefaultMutableTreeNode node = new DefaultMutableTreeNode(cd); leafNodes.add(node); cdToNode.put(cd, node); parentNode.add(node); } //Trim out single child category nodes. for (int i = 0; i < leafNodes.size(); i++) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) leafNodes.get(i); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent(); if (parent == controlTreeRoot) { continue; } if (parent.getChildCount() == 1) { DefaultMutableTreeNode grandParent = (DefaultMutableTreeNode) parent.getParent(); if ((grandParent == controlTreeRoot) || (grandParent.getChildCount() == 1)) { node.removeFromParent(); grandParent.add(node); parent.removeFromParent(); } } } controlTreeModel.nodeStructureChanged(controlTreeRoot); for (int i = 0; i < openCds.size(); i++) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) cdToNode.get(openCds.get(i)); if (node != null) { TreePath path = new TreePath(controlTreeModel.getPathToRoot(node)); //Here we do an addSelectionPath as well as the the expand path //because the expandPath does not seem to work. controlTree.addSelectionPath(path); controlTree.expandPath(path); } } //Now, clear the selection, hopefully leaving the expanded paths expanded. controlTree.clearSelection(); checkSettings(); } } /** * Expand the JTree out to the node that represents the * given {@link ucar.unidata.idv.ControlDescriptor} * * @param cd The selected {@link ucar.unidata.idv.ControlDescriptor} */ private void setSelectedControl(ControlDescriptor cd) { synchronized (CONTROLTREE_MUTEX) { if (cd == null) { cd = firstCd; } if (cd == null) { return; } DefaultMutableTreeNode node = (DefaultMutableTreeNode) cdToNode.get(cd); if (node == null) { return; } TreePath path = new TreePath(controlTreeModel.getPathToRoot(node)); controlTree.addSelectionPath(path); controlTree.expandPath(path); } } /** * Show help for the DisplayControl represented by the selected control descriptor */ private void showControlHelp() { Object selected = getSelectedControl(); if (selected == null) { idv.getIdvUIManager().showHelp("idv.data.fieldselector"); } else { ((ControlDescriptor) selected).showHelp(); } } /** * Be notified of a change to the display templates */ public void displayTemplatesChanged() { setDataChoice(dataChoice); } /** * Set the {@link ucar.unidata.data.DataChoice} we are representing * * @param dc The current {@link ucar.unidata.data.DataChoice} */ public synchronized void setDataChoice(DataChoice dc) { dataChoice = dc; if (dataChoice == null) { setControlList(new Vector()); dataSelectionWidget.setTimes(new ArrayList(), new ArrayList()); dataSelectionWidget.updateSelectionTab(null, null); return; } ControlDescriptor selected = getSelectedControl(); Vector newList = new Vector( ControlDescriptor.getApplicableControlDescriptors( dataChoice.getCategories(), idv.getControlDescriptors(true))); setControlList(newList); if ( !newList.contains(selected)) { selected = null; } setSelectedControl(selected); if (label != null) { label.setText("Choose a display for data: " + dataChoice); } List sources = new ArrayList(); dataChoice.getDataSources(sources); sources = Misc.makeUnique(sources); List selectedTimes = dataChoice.getSelectedDateTimes(); //A hack - data choices that have no times at all have a non-null but empty list of selected times. List times = dataChoice.getAllDateTimes(); if (false && (selectedTimes != null)) { List allTimes = dataChoice.getAllDateTimes(); //Now, convert the (possible) indices to actual datetimes selectedTimes = DataSourceImpl.getDateTimes(selectedTimes, allTimes); dataSelectionWidget.setTimes(selectedTimes, selectedTimes); } else { dataSelectionWidget.setTimes(times, selectedTimes); } if (sources.size() == 1) { DataSource dataSource = (DataSource) sources.get(0); //If the widget thinks this is a new data source then we need to reset the times list if (dataSelectionWidget.updateSelectionTab(dataSource, dc)) { dataSelectionWidget.setTimes(times, selectedTimes); } } else { dataSelectionWidget.updateSelectionTab(null, dc); } } /** * Return the {@link ucar.unidata.data.DataSource} we are configuring * * @return The {@link ucar.unidata.data.DataSource} */ public DataSource getDataSource() { return dataSource; } /** * Get the {@link ucar.unidata.data.DataChoice} we are representing * * @return The current {@link ucar.unidata.data.DataChoice} */ public DataChoice getDataChoice() { return dataChoice; } /** * Class ControlTree shows the display controls. * * * @author IDV Development Team * @version $Revision: 1.98 $ */ private class ControlTree extends JTree { /** tooltip to use */ private String defaultToolTip = "Click here and press F1 for help"; /** * ctor */ public ControlTree() { setRootVisible(false); setShowsRootHandles(true); setToggleClickCount(1); setToolTipText(defaultToolTip); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() { public Component getTreeCellRendererComponent(JTree theTree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(theTree, value, sel, expanded, leaf, row, hasFocus); if ( !(value instanceof DefaultMutableTreeNode)) { return this; } Object object = ((DefaultMutableTreeNode) value).getUserObject(); if ( !(object instanceof ControlDescriptor)) { return this; } ControlDescriptor cd = (ControlDescriptor) object; if (cd.getIcon() != null) { ImageIcon icon = GuiUtils.getImageIcon(cd.getIcon(), false); // setIcon(icon); } return this; } }; setCellRenderer(renderer); } /** * get the tooltip * * @param event mouse event * * @return Tooltip */ public String getToolTipText(MouseEvent event) { if (getSelectedControl() == null) { return defaultToolTip; } return defaultToolTip + " on this display type"; } /** * Find the tooltip * * @param event mouse event * * @return tooltip */ private String findToolTipText(MouseEvent event) { TreePath path = getPathForLocation(event.getX(), event.getY()); if (path == null) { return defaultToolTip; } Object last = path.getLastPathComponent(); if (last == null) { return defaultToolTip; } if ( !(last instanceof DefaultMutableTreeNode)) { return defaultToolTip; } Object object = ((DefaultMutableTreeNode) last).getUserObject(); if ( !(object instanceof ControlDescriptor)) { return defaultToolTip; } ControlDescriptor cd = (ControlDescriptor) object; return cd.getToolTipText(); } } /** * _more_ */ private void controlTreeChanged() { Object[] cd = getSelectedControls(); synchronized (ENABLE_MUTEX) { for (int i = 0; i < createBtns.size(); i++) { ((JButton) createBtns.get(i)).setEnabled(cd.length > 0); } } if (dataSelectionWidget != null) { List levels = null; if (cd.length == 1) { levels = ((ControlDescriptor) cd[0]).getLevels(); } dataSelectionWidget.setLevelsFromDisplay(levels); } } /** * Make the GUI for configuring a {@link ucar.unidata.data.DataChoice} * * @param dataChoice The DataChoice * @return The GUI */ public JComponent doMakeDataChoiceDialog(DataChoice dataChoice) { controlTree = new ControlTree(); CONTROLTREE_MUTEX = controlTree.getTreeLock(); controlTreeRoot = new DefaultMutableTreeNode("Displays"); controlTreeModel = new DefaultTreeModel(controlTreeRoot); controlTree.setModel(controlTreeModel); DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) controlTree.getCellRenderer(); renderer.setOpenIcon(null); renderer.setClosedIcon(null); renderer.setLeafIcon(null); Font f = renderer.getFont(); controlTree.setRowHeight(18); // renderer.setFont (f.deriveFont (14.0f)); controlTree.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == e.VK_F1) { showControlHelp(); } } }); controlTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { checkSettings(); Misc.run(new Runnable() { public void run() { controlTreeChanged(); } }); } }); controlTree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { doOk(); } //For now let's not publicize this facility // if (true) {return;} if (SwingUtilities.isRightMouseButton(e)) { //TBD if (true) { return; } final ControlDescriptor cd = getSelectedControl(); if (cd == null) { return; } JPopupMenu menu = new JPopupMenu(); JMenuItem mi = new JMenuItem( "Create this display whenever the data is loaded"); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { idv.getAutoDisplayEditor() .addDisplayForDataSource(getDataChoice(), cd); } }); List dataSources = new ArrayList(); getDataChoice().getDataSources(dataSources); if (dataSources.size() > 0) { menu.add(mi); } mi = new JMenuItem("Edit automatic display creation"); mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { idv.showAutoDisplayEditor(); } }); menu.add(mi); menu.show(controlTree, e.getX(), e.getY()); } } }); displayScroller = GuiUtils.makeScrollPane(controlTree, 200, 150); displayScroller.setBorder(null); dataSelectionWidget = new DataSelectionWidget(idv); if (horizontalOrientation) { displayScroller.setPreferredSize(new Dimension(150, 35)); contents = GuiUtils.hsplit(dataSelectionWidget.getContents(), displayScroller); } else { displayScroller.setPreferredSize(new Dimension(200, 150)); dataSelectionWidget.getContents().setPreferredSize( new Dimension(200, 200)); contents = GuiUtils.vsplit(displayScroller, dataSelectionWidget.getContents(), 150, 0.5); } if (inOwnWindow) { contents = GuiUtils.topCenter(GuiUtils.inset(label = new JLabel(" "), 5), contents); } setDataChoice(dataChoice); return contents; } /** * Check settings */ private void checkSettings() { Object[] cd = getSelectedControls(); dataSelectionWidget.updateSettings((ControlDescriptor) ((cd.length > 0) ? cd[0] : null)); } /** * Get the data selection widget * * @return data selection widget */ public DataSelectionWidget getDataSelectionWidget() { return dataSelectionWidget; } /** * Make a new window with the given GUI contents and position * it at the given screen location * * @param contents Gui contents * @param x Screen x * @param y Screen y */ protected void doMakeWindow(JComponent contents, int x, int y) { doMakeWindow(contents, x, y, "Select Display"); } /** * Make a new window with the given GUI contents with the given * window title and position it at the given screen location * * @param contents Gui contents * @param x Screen x * @param y Screen y * @param title Window title */ private void doMakeWindow(JComponent contents, int x, int y, String title) { dialog = GuiUtils.createDialog(title, true); Container cpane = dialog.getContentPane(); cpane.setLayout(new BorderLayout()); cpane.add("Center", GuiUtils.inset(contents, 5)); dialog.setLocation(x, y); dialog.pack(); dialog.setVisible(true); } /** * Dispose of the dialog window (if it is created) * and remove this object from the IDV's list of * DataControlDialog-s */ public void dispose() { if (dialog != null) { dialog.dispose(); } idv.getIdvUIManager().removeDCD(this); } /** * Calls dispose, nulls out references (for leaks), etc. */ public void doClose() { if ( !inOwnWindow) { return; } if (dialog != null) { dialog.setVisible(false); } dispose(); idv = null; dataSource = null; dataChoice = null; } /** * Call doApply and close the window */ public void doOk() { doApply(); if (inOwnWindow) { doClose(); } } /** * Call the IDV's processDialog method. The IDV figures out what to do. */ private void doApply() { idv.getIdvUIManager().processDialog(this); } /** * Handle OK, APPLY and CANCEL events * * @param event The event */ public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals(GuiUtils.CMD_OK)) { doOk(); } else if (event.getActionCommand().equals(GuiUtils.CMD_APPLY)) { doApply(); } else if (event.getActionCommand().equals(GuiUtils.CMD_CANCEL)) { doClose(); } } }
[ "public", "class", "DataControlDialog", "implements", "ActionListener", "{", "/** Reference to the idv */", "private", "IntegratedDataViewer", "idv", ";", "/** The JDialog window object */", "private", "JDialog", "dialog", ";", "/** The gui contents */", "JComponent", "contents", ";", "/** Should we layout the display/control lists horizontally */", "private", "boolean", "horizontalOrientation", "=", "false", ";", "/**\n * We keep a list of the buttons that can be used for creation\n * so we can enable/disable all them as needed.\n */", "List", "createBtns", "=", "new", "ArrayList", "(", ")", ";", "/** A mutex for when we enable/disable the create buttons */", "private", "Object", "ENABLE_MUTEX", "=", "new", "Object", "(", ")", ";", "/** The top label */", "JLabel", "label", ";", "/** The JTree that holds the {@link ucar.unidata.idv.ControlDescriptor} hierarchy */", "JTree", "controlTree", ";", "/** A mutex for accesing the control tree */", "private", "Object", "CONTROLTREE_MUTEX", ";", "/** The root of the {@link ucar.unidata.idv.ControlDescriptor} hierarchy */", "DefaultMutableTreeNode", "controlTreeRoot", ";", "/** THe tree model used for the control descriptors */", "DefaultTreeModel", "controlTreeModel", ";", "/** Mapping from ControlDescriptor to tree node */", "private", "Hashtable", "cdToNode", "=", "new", "Hashtable", "(", ")", ";", "/**\n * The first control descriptor we show.\n * Keep this around so we can always have one selected\n * when a new tree is created.\n */", "private", "ControlDescriptor", "firstCd", ";", "/** The wrapper for the display list */", "JComponent", "displayScroller", ";", "/** The data selection widget */", "private", "DataSelectionWidget", "dataSelectionWidget", ";", "/** The data source */", "DataSource", "dataSource", ";", "/** The data choice */", "DataChoice", "dataChoice", ";", "/** This class can be in its own window or be part of an other gui */", "private", "boolean", "inOwnWindow", "=", "true", ";", "/**\n * Constructor for when we are a part of the {@link DataSelector}\n *\n * @param idv Reference to the IDV\n * @param inOwnWindow Should this object be in its own window\n * @param horizontalOrientation Show display/times hor?\n *\n */", "public", "DataControlDialog", "(", "IntegratedDataViewer", "idv", ",", "boolean", "inOwnWindow", ",", "boolean", "horizontalOrientation", ")", "{", "this", ".", "inOwnWindow", "=", "inOwnWindow", ";", "this", ".", "horizontalOrientation", "=", "horizontalOrientation", ";", "init", "(", "idv", ",", "null", ",", "50", ",", "50", ")", ";", "}", "/**\n * Constructor for configuring a {@link ucar.unidata.data.DataChoice}\n *\n * @param idv Reference to the IDV\n * @param dataChoice The {@link ucar.unidata.data.DataChoice} we are configuring\n * @param x X position on the screen to show window\n * @param y Y position on the screen to show window\n *\n */", "public", "DataControlDialog", "(", "IntegratedDataViewer", "idv", ",", "DataChoice", "dataChoice", ",", "int", "x", ",", "int", "y", ")", "{", "init", "(", "idv", ",", "dataChoice", ",", "x", ",", "y", ")", ";", "}", "/**\n * Initialize the gui. Popup a new Window if required.\n *\n * @param idv The IDV\n * @param dataChoice The {@link DataChoice} we are configuring (or null)\n * @param windowX X position on the screen to show window\n * @param windowY Y position on the screen to show window\n */", "private", "void", "init", "(", "IntegratedDataViewer", "idv", ",", "DataChoice", "dataChoice", ",", "int", "windowX", ",", "int", "windowY", ")", "{", "this", ".", "idv", "=", "idv", ";", "this", ".", "dataChoice", "=", "dataChoice", ";", "contents", "=", "doMakeDataChoiceDialog", "(", "dataChoice", ")", ";", "if", "(", "inOwnWindow", ")", "{", "doMakeWindow", "(", "GuiUtils", ".", "centerBottom", "(", "contents", ",", "GuiUtils", ".", "makeApplyOkCancelButtons", "(", "this", ")", ")", ",", "windowX", ",", "windowY", ",", "\"", "Select Display", "\"", ")", ";", "}", "}", "/**\n * We keep track of the \"Create\" buttons so we can enable/disable them\n *\n * @param b The create button to add into the list\n */", "public", "void", "addCreateButton", "(", "JButton", "b", ")", "{", "createBtns", ".", "add", "(", "b", ")", ";", "b", ".", "setEnabled", "(", "getSelectedControl", "(", ")", "!=", "null", ")", ";", "}", "/**\n * Return the gui contents\n * @return The gui contents\n */", "public", "JComponent", "getContents", "(", ")", "{", "return", "contents", ";", "}", "/**\n * Utility to set the cursor on the gui contents\n *\n * @param cursor The cursor to set\n */", "public", "void", "setCursor", "(", "Cursor", "cursor", ")", "{", "contents", ".", "setCursor", "(", "cursor", ")", ";", "}", "/**\n * Set the data source\n *\n * @param ds The new data source\n */", "public", "void", "setDataSource", "(", "DataSource", "ds", ")", "{", "dataSource", "=", "ds", ";", "}", "/**\n * Called by the DataSelector to handle when the data source has changed\n *\n * @param dataSource The data source that changed\n */", "public", "void", "dataSourceChanged", "(", "DataSource", "dataSource", ")", "{", "if", "(", "this", ".", "dataSource", "==", "null", ")", "{", "setDataChoice", "(", "dataChoice", ")", ";", "return", ";", "}", "if", "(", "this", ".", "dataSource", "!=", "dataSource", ")", "{", "return", ";", "}", "dataSelectionWidget", ".", "dataSourceChanged", "(", "dataSource", ")", ";", "}", "/**\n * Return the {@link ucar.unidata.idv.ControlDescriptor} that is currently selected\n *\n * @return Selected ControlDescriptor\n */", "protected", "ControlDescriptor", "getSelectedControl", "(", ")", "{", "if", "(", "controlTree", "==", "null", ")", "{", "return", "null", ";", "}", "List", "l", "=", "getSelectedControlsFromTree", "(", ")", ";", "if", "(", "l", ".", "size", "(", ")", ">", "0", ")", "{", "return", "(", "ControlDescriptor", ")", "l", ".", "get", "(", "0", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", "/**\n * Find and return the list of {@link ucar.unidata.idv.ControlDescriptor}-s\n * that have been selected in the JTree\n *\n * @return List of control descriptors\n */", "private", "List", "getSelectedControlsFromTree", "(", ")", "{", "TreePath", "[", "]", "paths", ";", "synchronized", "(", "CONTROLTREE_MUTEX", ")", "{", "paths", "=", "controlTree", ".", "getSelectionModel", "(", ")", ".", "getSelectionPaths", "(", ")", ";", "}", "List", "descriptors", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "paths", "==", "null", ")", "{", "return", "descriptors", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "i", "++", ")", "{", "Object", "last", "=", "paths", "[", "i", "]", ".", "getLastPathComponent", "(", ")", ";", "if", "(", "last", "==", "null", ")", "{", "continue", ";", "}", "Object", "object", "=", "(", "(", "DefaultMutableTreeNode", ")", "last", ")", ".", "getUserObject", "(", ")", ";", "if", "(", "!", "(", "object", "instanceof", "ControlDescriptor", ")", ")", "{", "continue", ";", "}", "descriptors", ".", "add", "(", "object", ")", ";", "}", "return", "descriptors", ";", "}", "/**\n * Find and return the array of selected {@link ucar.unidata.idv.ControlDescriptor}-s\n *\n * @return Select control descriptors\n */", "public", "Object", "[", "]", "getSelectedControls", "(", ")", "{", "return", "getSelectedControlsFromTree", "(", ")", ".", "toArray", "(", ")", ";", "}", "/**\n * Add the given list of {@link ucar.unidata.idv.ControlDescriptor}-s\n * int othe Tree.\n *\n * @param v List of new {@link ucar.unidata.idv.ControlDescriptor}-s\n */", "private", "void", "setControlList", "(", "Vector", "v", ")", "{", "synchronized", "(", "CONTROLTREE_MUTEX", ")", "{", "List", "openCds", "=", "new", "ArrayList", "(", ")", ";", "Enumeration", "paths", "=", "controlTree", ".", "getExpandedDescendants", "(", "new", "TreePath", "(", "controlTreeRoot", ".", "getPath", "(", ")", ")", ")", ";", "if", "(", "paths", "!=", "null", ")", "{", "while", "(", "paths", ".", "hasMoreElements", "(", ")", ")", "{", "TreePath", "path", "=", "(", "TreePath", ")", "paths", ".", "nextElement", "(", ")", ";", "DefaultMutableTreeNode", "last", "=", "(", "DefaultMutableTreeNode", ")", "path", ".", "getLastPathComponent", "(", ")", ";", "Enumeration", "nodeChildren", "=", "last", ".", "children", "(", ")", ";", "while", "(", "nodeChildren", ".", "hasMoreElements", "(", ")", ")", "{", "DefaultMutableTreeNode", "child", "=", "(", "DefaultMutableTreeNode", ")", "nodeChildren", ".", "nextElement", "(", ")", ";", "if", "(", "child", ".", "getUserObject", "(", ")", "instanceof", "ControlDescriptor", ")", "{", "openCds", ".", "add", "(", "child", ".", "getUserObject", "(", ")", ")", ";", "}", "}", "}", "}", "cdToNode", "=", "new", "Hashtable", "(", ")", ";", "firstCd", "=", "null", ";", "controlTreeRoot", ".", "removeAllChildren", "(", ")", ";", "List", "leafNodes", "=", "new", "ArrayList", "(", ")", ";", "Hashtable", "nodes", "=", "new", "Hashtable", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "v", ".", "size", "(", ")", ";", "i", "++", ")", "{", "ControlDescriptor", "cd", "=", "(", "ControlDescriptor", ")", "v", ".", "get", "(", "i", ")", ";", "String", "displayCategory", "=", "cd", ".", "getDisplayCategory", "(", ")", ";", "DefaultMutableTreeNode", "parentNode", "=", "controlTreeRoot", ";", "String", "catSoFar", "=", "\"", "\"", ";", "List", "cats", "=", "StringUtil", ".", "split", "(", "displayCategory", ",", "\"", "/", "\"", ",", "true", ",", "true", ")", ";", "for", "(", "int", "catIdx", "=", "0", ";", "catIdx", "<", "cats", ".", "size", "(", ")", ";", "catIdx", "++", ")", "{", "String", "subCat", "=", "(", "String", ")", "cats", ".", "get", "(", "catIdx", ")", ";", "catSoFar", "=", "catSoFar", "+", "\"", "/", "\"", "+", "subCat", ";", "DefaultMutableTreeNode", "node", "=", "(", "DefaultMutableTreeNode", ")", "nodes", ".", "get", "(", "catSoFar", ")", ";", "if", "(", "node", "==", "null", ")", "{", "node", "=", "new", "DefaultMutableTreeNode", "(", "subCat", ")", ";", "parentNode", ".", "add", "(", "node", ")", ";", "nodes", ".", "put", "(", "catSoFar", ",", "node", ")", ";", "}", "parentNode", "=", "node", ";", "}", "if", "(", "firstCd", "==", "null", ")", "{", "firstCd", "=", "cd", ";", "}", "DefaultMutableTreeNode", "node", "=", "new", "DefaultMutableTreeNode", "(", "cd", ")", ";", "leafNodes", ".", "add", "(", "node", ")", ";", "cdToNode", ".", "put", "(", "cd", ",", "node", ")", ";", "parentNode", ".", "add", "(", "node", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "leafNodes", ".", "size", "(", ")", ";", "i", "++", ")", "{", "DefaultMutableTreeNode", "node", "=", "(", "DefaultMutableTreeNode", ")", "leafNodes", ".", "get", "(", "i", ")", ";", "DefaultMutableTreeNode", "parent", "=", "(", "DefaultMutableTreeNode", ")", "node", ".", "getParent", "(", ")", ";", "if", "(", "parent", "==", "controlTreeRoot", ")", "{", "continue", ";", "}", "if", "(", "parent", ".", "getChildCount", "(", ")", "==", "1", ")", "{", "DefaultMutableTreeNode", "grandParent", "=", "(", "DefaultMutableTreeNode", ")", "parent", ".", "getParent", "(", ")", ";", "if", "(", "(", "grandParent", "==", "controlTreeRoot", ")", "||", "(", "grandParent", ".", "getChildCount", "(", ")", "==", "1", ")", ")", "{", "node", ".", "removeFromParent", "(", ")", ";", "grandParent", ".", "add", "(", "node", ")", ";", "parent", ".", "removeFromParent", "(", ")", ";", "}", "}", "}", "controlTreeModel", ".", "nodeStructureChanged", "(", "controlTreeRoot", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "openCds", ".", "size", "(", ")", ";", "i", "++", ")", "{", "DefaultMutableTreeNode", "node", "=", "(", "DefaultMutableTreeNode", ")", "cdToNode", ".", "get", "(", "openCds", ".", "get", "(", "i", ")", ")", ";", "if", "(", "node", "!=", "null", ")", "{", "TreePath", "path", "=", "new", "TreePath", "(", "controlTreeModel", ".", "getPathToRoot", "(", "node", ")", ")", ";", "controlTree", ".", "addSelectionPath", "(", "path", ")", ";", "controlTree", ".", "expandPath", "(", "path", ")", ";", "}", "}", "controlTree", ".", "clearSelection", "(", ")", ";", "checkSettings", "(", ")", ";", "}", "}", "/**\n * Expand the JTree out to the node that represents the\n * given {@link ucar.unidata.idv.ControlDescriptor}\n *\n * @param cd The selected {@link ucar.unidata.idv.ControlDescriptor}\n */", "private", "void", "setSelectedControl", "(", "ControlDescriptor", "cd", ")", "{", "synchronized", "(", "CONTROLTREE_MUTEX", ")", "{", "if", "(", "cd", "==", "null", ")", "{", "cd", "=", "firstCd", ";", "}", "if", "(", "cd", "==", "null", ")", "{", "return", ";", "}", "DefaultMutableTreeNode", "node", "=", "(", "DefaultMutableTreeNode", ")", "cdToNode", ".", "get", "(", "cd", ")", ";", "if", "(", "node", "==", "null", ")", "{", "return", ";", "}", "TreePath", "path", "=", "new", "TreePath", "(", "controlTreeModel", ".", "getPathToRoot", "(", "node", ")", ")", ";", "controlTree", ".", "addSelectionPath", "(", "path", ")", ";", "controlTree", ".", "expandPath", "(", "path", ")", ";", "}", "}", "/**\n * Show help for the DisplayControl represented by the selected control descriptor\n */", "private", "void", "showControlHelp", "(", ")", "{", "Object", "selected", "=", "getSelectedControl", "(", ")", ";", "if", "(", "selected", "==", "null", ")", "{", "idv", ".", "getIdvUIManager", "(", ")", ".", "showHelp", "(", "\"", "idv.data.fieldselector", "\"", ")", ";", "}", "else", "{", "(", "(", "ControlDescriptor", ")", "selected", ")", ".", "showHelp", "(", ")", ";", "}", "}", "/**\n * Be notified of a change to the display templates\n */", "public", "void", "displayTemplatesChanged", "(", ")", "{", "setDataChoice", "(", "dataChoice", ")", ";", "}", "/**\n * Set the {@link ucar.unidata.data.DataChoice} we are representing\n *\n * @param dc The current {@link ucar.unidata.data.DataChoice}\n */", "public", "synchronized", "void", "setDataChoice", "(", "DataChoice", "dc", ")", "{", "dataChoice", "=", "dc", ";", "if", "(", "dataChoice", "==", "null", ")", "{", "setControlList", "(", "new", "Vector", "(", ")", ")", ";", "dataSelectionWidget", ".", "setTimes", "(", "new", "ArrayList", "(", ")", ",", "new", "ArrayList", "(", ")", ")", ";", "dataSelectionWidget", ".", "updateSelectionTab", "(", "null", ",", "null", ")", ";", "return", ";", "}", "ControlDescriptor", "selected", "=", "getSelectedControl", "(", ")", ";", "Vector", "newList", "=", "new", "Vector", "(", "ControlDescriptor", ".", "getApplicableControlDescriptors", "(", "dataChoice", ".", "getCategories", "(", ")", ",", "idv", ".", "getControlDescriptors", "(", "true", ")", ")", ")", ";", "setControlList", "(", "newList", ")", ";", "if", "(", "!", "newList", ".", "contains", "(", "selected", ")", ")", "{", "selected", "=", "null", ";", "}", "setSelectedControl", "(", "selected", ")", ";", "if", "(", "label", "!=", "null", ")", "{", "label", ".", "setText", "(", "\"", "Choose a display for data: ", "\"", "+", "dataChoice", ")", ";", "}", "List", "sources", "=", "new", "ArrayList", "(", ")", ";", "dataChoice", ".", "getDataSources", "(", "sources", ")", ";", "sources", "=", "Misc", ".", "makeUnique", "(", "sources", ")", ";", "List", "selectedTimes", "=", "dataChoice", ".", "getSelectedDateTimes", "(", ")", ";", "List", "times", "=", "dataChoice", ".", "getAllDateTimes", "(", ")", ";", "if", "(", "false", "&&", "(", "selectedTimes", "!=", "null", ")", ")", "{", "List", "allTimes", "=", "dataChoice", ".", "getAllDateTimes", "(", ")", ";", "selectedTimes", "=", "DataSourceImpl", ".", "getDateTimes", "(", "selectedTimes", ",", "allTimes", ")", ";", "dataSelectionWidget", ".", "setTimes", "(", "selectedTimes", ",", "selectedTimes", ")", ";", "}", "else", "{", "dataSelectionWidget", ".", "setTimes", "(", "times", ",", "selectedTimes", ")", ";", "}", "if", "(", "sources", ".", "size", "(", ")", "==", "1", ")", "{", "DataSource", "dataSource", "=", "(", "DataSource", ")", "sources", ".", "get", "(", "0", ")", ";", "if", "(", "dataSelectionWidget", ".", "updateSelectionTab", "(", "dataSource", ",", "dc", ")", ")", "{", "dataSelectionWidget", ".", "setTimes", "(", "times", ",", "selectedTimes", ")", ";", "}", "}", "else", "{", "dataSelectionWidget", ".", "updateSelectionTab", "(", "null", ",", "dc", ")", ";", "}", "}", "/**\n * Return the {@link ucar.unidata.data.DataSource} we are configuring\n *\n * @return The {@link ucar.unidata.data.DataSource}\n */", "public", "DataSource", "getDataSource", "(", ")", "{", "return", "dataSource", ";", "}", "/**\n * Get the {@link ucar.unidata.data.DataChoice} we are representing\n *\n * @return The current {@link ucar.unidata.data.DataChoice}\n */", "public", "DataChoice", "getDataChoice", "(", ")", "{", "return", "dataChoice", ";", "}", "/**\n * Class ControlTree shows the display controls.\n *\n *\n * @author IDV Development Team\n * @version $Revision: 1.98 $\n */", "private", "class", "ControlTree", "extends", "JTree", "{", "/** tooltip to use */", "private", "String", "defaultToolTip", "=", "\"", "Click here and press F1 for help", "\"", ";", "/**\n * ctor\n */", "public", "ControlTree", "(", ")", "{", "setRootVisible", "(", "false", ")", ";", "setShowsRootHandles", "(", "true", ")", ";", "setToggleClickCount", "(", "1", ")", ";", "setToolTipText", "(", "defaultToolTip", ")", ";", "DefaultTreeCellRenderer", "renderer", "=", "new", "DefaultTreeCellRenderer", "(", ")", "{", "public", "Component", "getTreeCellRendererComponent", "(", "JTree", "theTree", ",", "Object", "value", ",", "boolean", "sel", ",", "boolean", "expanded", ",", "boolean", "leaf", ",", "int", "row", ",", "boolean", "hasFocus", ")", "{", "super", ".", "getTreeCellRendererComponent", "(", "theTree", ",", "value", ",", "sel", ",", "expanded", ",", "leaf", ",", "row", ",", "hasFocus", ")", ";", "if", "(", "!", "(", "value", "instanceof", "DefaultMutableTreeNode", ")", ")", "{", "return", "this", ";", "}", "Object", "object", "=", "(", "(", "DefaultMutableTreeNode", ")", "value", ")", ".", "getUserObject", "(", ")", ";", "if", "(", "!", "(", "object", "instanceof", "ControlDescriptor", ")", ")", "{", "return", "this", ";", "}", "ControlDescriptor", "cd", "=", "(", "ControlDescriptor", ")", "object", ";", "if", "(", "cd", ".", "getIcon", "(", ")", "!=", "null", ")", "{", "ImageIcon", "icon", "=", "GuiUtils", ".", "getImageIcon", "(", "cd", ".", "getIcon", "(", ")", ",", "false", ")", ";", "}", "return", "this", ";", "}", "}", ";", "setCellRenderer", "(", "renderer", ")", ";", "}", "/**\n * get the tooltip\n *\n * @param event mouse event\n *\n * @return Tooltip\n */", "public", "String", "getToolTipText", "(", "MouseEvent", "event", ")", "{", "if", "(", "getSelectedControl", "(", ")", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "return", "defaultToolTip", "+", "\"", " on this display type", "\"", ";", "}", "/**\n * Find the tooltip\n *\n * @param event mouse event\n *\n * @return tooltip\n */", "private", "String", "findToolTipText", "(", "MouseEvent", "event", ")", "{", "TreePath", "path", "=", "getPathForLocation", "(", "event", ".", "getX", "(", ")", ",", "event", ".", "getY", "(", ")", ")", ";", "if", "(", "path", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "Object", "last", "=", "path", ".", "getLastPathComponent", "(", ")", ";", "if", "(", "last", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "if", "(", "!", "(", "last", "instanceof", "DefaultMutableTreeNode", ")", ")", "{", "return", "defaultToolTip", ";", "}", "Object", "object", "=", "(", "(", "DefaultMutableTreeNode", ")", "last", ")", ".", "getUserObject", "(", ")", ";", "if", "(", "!", "(", "object", "instanceof", "ControlDescriptor", ")", ")", "{", "return", "defaultToolTip", ";", "}", "ControlDescriptor", "cd", "=", "(", "ControlDescriptor", ")", "object", ";", "return", "cd", ".", "getToolTipText", "(", ")", ";", "}", "}", "/**\n * _more_\n */", "private", "void", "controlTreeChanged", "(", ")", "{", "Object", "[", "]", "cd", "=", "getSelectedControls", "(", ")", ";", "synchronized", "(", "ENABLE_MUTEX", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "createBtns", ".", "size", "(", ")", ";", "i", "++", ")", "{", "(", "(", "JButton", ")", "createBtns", ".", "get", "(", "i", ")", ")", ".", "setEnabled", "(", "cd", ".", "length", ">", "0", ")", ";", "}", "}", "if", "(", "dataSelectionWidget", "!=", "null", ")", "{", "List", "levels", "=", "null", ";", "if", "(", "cd", ".", "length", "==", "1", ")", "{", "levels", "=", "(", "(", "ControlDescriptor", ")", "cd", "[", "0", "]", ")", ".", "getLevels", "(", ")", ";", "}", "dataSelectionWidget", ".", "setLevelsFromDisplay", "(", "levels", ")", ";", "}", "}", "/**\n * Make the GUI for configuring a {@link ucar.unidata.data.DataChoice}\n *\n * @param dataChoice The DataChoice\n * @return The GUI\n */", "public", "JComponent", "doMakeDataChoiceDialog", "(", "DataChoice", "dataChoice", ")", "{", "controlTree", "=", "new", "ControlTree", "(", ")", ";", "CONTROLTREE_MUTEX", "=", "controlTree", ".", "getTreeLock", "(", ")", ";", "controlTreeRoot", "=", "new", "DefaultMutableTreeNode", "(", "\"", "Displays", "\"", ")", ";", "controlTreeModel", "=", "new", "DefaultTreeModel", "(", "controlTreeRoot", ")", ";", "controlTree", ".", "setModel", "(", "controlTreeModel", ")", ";", "DefaultTreeCellRenderer", "renderer", "=", "(", "DefaultTreeCellRenderer", ")", "controlTree", ".", "getCellRenderer", "(", ")", ";", "renderer", ".", "setOpenIcon", "(", "null", ")", ";", "renderer", ".", "setClosedIcon", "(", "null", ")", ";", "renderer", ".", "setLeafIcon", "(", "null", ")", ";", "Font", "f", "=", "renderer", ".", "getFont", "(", ")", ";", "controlTree", ".", "setRowHeight", "(", "18", ")", ";", "controlTree", ".", "addKeyListener", "(", "new", "KeyAdapter", "(", ")", "{", "public", "void", "keyPressed", "(", "KeyEvent", "e", ")", "{", "if", "(", "e", ".", "getKeyCode", "(", ")", "==", "e", ".", "VK_F1", ")", "{", "showControlHelp", "(", ")", ";", "}", "}", "}", ")", ";", "controlTree", ".", "addTreeSelectionListener", "(", "new", "TreeSelectionListener", "(", ")", "{", "public", "void", "valueChanged", "(", "TreeSelectionEvent", "e", ")", "{", "checkSettings", "(", ")", ";", "Misc", ".", "run", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "controlTreeChanged", "(", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "controlTree", ".", "addMouseListener", "(", "new", "MouseAdapter", "(", ")", "{", "public", "void", "mouseClicked", "(", "MouseEvent", "e", ")", "{", "if", "(", "e", ".", "getClickCount", "(", ")", "==", "2", ")", "{", "doOk", "(", ")", ";", "}", "if", "(", "SwingUtilities", ".", "isRightMouseButton", "(", "e", ")", ")", "{", "if", "(", "true", ")", "{", "return", ";", "}", "final", "ControlDescriptor", "cd", "=", "getSelectedControl", "(", ")", ";", "if", "(", "cd", "==", "null", ")", "{", "return", ";", "}", "JPopupMenu", "menu", "=", "new", "JPopupMenu", "(", ")", ";", "JMenuItem", "mi", "=", "new", "JMenuItem", "(", "\"", "Create this display whenever the data is loaded", "\"", ")", ";", "mi", ".", "addActionListener", "(", "new", "ActionListener", "(", ")", "{", "public", "void", "actionPerformed", "(", "ActionEvent", "ae", ")", "{", "idv", ".", "getAutoDisplayEditor", "(", ")", ".", "addDisplayForDataSource", "(", "getDataChoice", "(", ")", ",", "cd", ")", ";", "}", "}", ")", ";", "List", "dataSources", "=", "new", "ArrayList", "(", ")", ";", "getDataChoice", "(", ")", ".", "getDataSources", "(", "dataSources", ")", ";", "if", "(", "dataSources", ".", "size", "(", ")", ">", "0", ")", "{", "menu", ".", "add", "(", "mi", ")", ";", "}", "mi", "=", "new", "JMenuItem", "(", "\"", "Edit automatic display creation", "\"", ")", ";", "mi", ".", "addActionListener", "(", "new", "ActionListener", "(", ")", "{", "public", "void", "actionPerformed", "(", "ActionEvent", "ae", ")", "{", "idv", ".", "showAutoDisplayEditor", "(", ")", ";", "}", "}", ")", ";", "menu", ".", "add", "(", "mi", ")", ";", "menu", ".", "show", "(", "controlTree", ",", "e", ".", "getX", "(", ")", ",", "e", ".", "getY", "(", ")", ")", ";", "}", "}", "}", ")", ";", "displayScroller", "=", "GuiUtils", ".", "makeScrollPane", "(", "controlTree", ",", "200", ",", "150", ")", ";", "displayScroller", ".", "setBorder", "(", "null", ")", ";", "dataSelectionWidget", "=", "new", "DataSelectionWidget", "(", "idv", ")", ";", "if", "(", "horizontalOrientation", ")", "{", "displayScroller", ".", "setPreferredSize", "(", "new", "Dimension", "(", "150", ",", "35", ")", ")", ";", "contents", "=", "GuiUtils", ".", "hsplit", "(", "dataSelectionWidget", ".", "getContents", "(", ")", ",", "displayScroller", ")", ";", "}", "else", "{", "displayScroller", ".", "setPreferredSize", "(", "new", "Dimension", "(", "200", ",", "150", ")", ")", ";", "dataSelectionWidget", ".", "getContents", "(", ")", ".", "setPreferredSize", "(", "new", "Dimension", "(", "200", ",", "200", ")", ")", ";", "contents", "=", "GuiUtils", ".", "vsplit", "(", "displayScroller", ",", "dataSelectionWidget", ".", "getContents", "(", ")", ",", "150", ",", "0.5", ")", ";", "}", "if", "(", "inOwnWindow", ")", "{", "contents", "=", "GuiUtils", ".", "topCenter", "(", "GuiUtils", ".", "inset", "(", "label", "=", "new", "JLabel", "(", "\"", " ", "\"", ")", ",", "5", ")", ",", "contents", ")", ";", "}", "setDataChoice", "(", "dataChoice", ")", ";", "return", "contents", ";", "}", "/**\n * Check settings\n */", "private", "void", "checkSettings", "(", ")", "{", "Object", "[", "]", "cd", "=", "getSelectedControls", "(", ")", ";", "dataSelectionWidget", ".", "updateSettings", "(", "(", "ControlDescriptor", ")", "(", "(", "cd", ".", "length", ">", "0", ")", "?", "cd", "[", "0", "]", ":", "null", ")", ")", ";", "}", "/**\n * Get the data selection widget\n *\n * @return data selection widget\n */", "public", "DataSelectionWidget", "getDataSelectionWidget", "(", ")", "{", "return", "dataSelectionWidget", ";", "}", "/**\n * Make a new window with the given GUI contents and position\n * it at the given screen location\n *\n * @param contents Gui contents\n * @param x Screen x\n * @param y Screen y\n */", "protected", "void", "doMakeWindow", "(", "JComponent", "contents", ",", "int", "x", ",", "int", "y", ")", "{", "doMakeWindow", "(", "contents", ",", "x", ",", "y", ",", "\"", "Select Display", "\"", ")", ";", "}", "/**\n * Make a new window with the given GUI contents with the given\n * window title and position it at the given screen location\n *\n * @param contents Gui contents\n * @param x Screen x\n * @param y Screen y\n * @param title Window title\n */", "private", "void", "doMakeWindow", "(", "JComponent", "contents", ",", "int", "x", ",", "int", "y", ",", "String", "title", ")", "{", "dialog", "=", "GuiUtils", ".", "createDialog", "(", "title", ",", "true", ")", ";", "Container", "cpane", "=", "dialog", ".", "getContentPane", "(", ")", ";", "cpane", ".", "setLayout", "(", "new", "BorderLayout", "(", ")", ")", ";", "cpane", ".", "add", "(", "\"", "Center", "\"", ",", "GuiUtils", ".", "inset", "(", "contents", ",", "5", ")", ")", ";", "dialog", ".", "setLocation", "(", "x", ",", "y", ")", ";", "dialog", ".", "pack", "(", ")", ";", "dialog", ".", "setVisible", "(", "true", ")", ";", "}", "/**\n * Dispose of the dialog window (if it is created)\n * and remove this object from the IDV's list of\n * DataControlDialog-s\n */", "public", "void", "dispose", "(", ")", "{", "if", "(", "dialog", "!=", "null", ")", "{", "dialog", ".", "dispose", "(", ")", ";", "}", "idv", ".", "getIdvUIManager", "(", ")", ".", "removeDCD", "(", "this", ")", ";", "}", "/**\n * Calls dispose, nulls out references (for leaks), etc.\n */", "public", "void", "doClose", "(", ")", "{", "if", "(", "!", "inOwnWindow", ")", "{", "return", ";", "}", "if", "(", "dialog", "!=", "null", ")", "{", "dialog", ".", "setVisible", "(", "false", ")", ";", "}", "dispose", "(", ")", ";", "idv", "=", "null", ";", "dataSource", "=", "null", ";", "dataChoice", "=", "null", ";", "}", "/**\n * Call doApply and close the window\n */", "public", "void", "doOk", "(", ")", "{", "doApply", "(", ")", ";", "if", "(", "inOwnWindow", ")", "{", "doClose", "(", ")", ";", "}", "}", "/**\n * Call the IDV's processDialog method. The IDV figures out what to do.\n */", "private", "void", "doApply", "(", ")", "{", "idv", ".", "getIdvUIManager", "(", ")", ".", "processDialog", "(", "this", ")", ";", "}", "/**\n * Handle OK, APPLY and CANCEL events\n *\n * @param event The event\n */", "public", "void", "actionPerformed", "(", "ActionEvent", "event", ")", "{", "if", "(", "event", ".", "getActionCommand", "(", ")", ".", "equals", "(", "GuiUtils", ".", "CMD_OK", ")", ")", "{", "doOk", "(", ")", ";", "}", "else", "if", "(", "event", ".", "getActionCommand", "(", ")", ".", "equals", "(", "GuiUtils", ".", "CMD_APPLY", ")", ")", "{", "doApply", "(", ")", ";", "}", "else", "if", "(", "event", ".", "getActionCommand", "(", ")", ".", "equals", "(", "GuiUtils", ".", "CMD_CANCEL", ")", ")", "{", "doClose", "(", ")", ";", "}", "}", "}" ]
This class provides a list of the display controls and the data selection dialog @author Jeff McWhirter @version $Revision: 1.98 $
[ "This", "class", "provides", "a", "list", "of", "the", "display", "controls", "and", "the", "data", "selection", "dialog", "@author", "Jeff", "McWhirter", "@version", "$Revision", ":", "1", ".", "98", "$" ]
[ "//Trim out single child category nodes.", "//Here we do an addSelectionPath as well as the the expand path", "//because the expandPath does not seem to work.", "//Now, clear the selection, hopefully leaving the expanded paths expanded.", "//A hack - data choices that have no times at all have a non-null but empty list of selected times.", "//Now, convert the (possible) indices to actual datetimes", "//If the widget thinks this is a new data source then we need to reset the times list", "// setIcon(icon);", "// renderer.setFont (f.deriveFont (14.0f));", "//For now let's not publicize this facility", "// if (true) {return;}", "//TBD" ]
[ { "param": "ActionListener", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ActionListener", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe5f2ef748eae1aa3f806dc26be8e0ad96c475a7
suvarchal/IDV-dev-old
src/ucar/unidata/idv/ui/DataControlDialog.java
[ "CNRI-Jython" ]
Java
ControlTree
/** * Class ControlTree shows the display controls. * * * @author IDV Development Team * @version $Revision: 1.98 $ */
Class ControlTree shows the display controls. @author IDV Development Team @version $Revision: 1.98 $
[ "Class", "ControlTree", "shows", "the", "display", "controls", ".", "@author", "IDV", "Development", "Team", "@version", "$Revision", ":", "1", ".", "98", "$" ]
private class ControlTree extends JTree { /** tooltip to use */ private String defaultToolTip = "Click here and press F1 for help"; /** * ctor */ public ControlTree() { setRootVisible(false); setShowsRootHandles(true); setToggleClickCount(1); setToolTipText(defaultToolTip); DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() { public Component getTreeCellRendererComponent(JTree theTree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(theTree, value, sel, expanded, leaf, row, hasFocus); if ( !(value instanceof DefaultMutableTreeNode)) { return this; } Object object = ((DefaultMutableTreeNode) value).getUserObject(); if ( !(object instanceof ControlDescriptor)) { return this; } ControlDescriptor cd = (ControlDescriptor) object; if (cd.getIcon() != null) { ImageIcon icon = GuiUtils.getImageIcon(cd.getIcon(), false); // setIcon(icon); } return this; } }; setCellRenderer(renderer); } /** * get the tooltip * * @param event mouse event * * @return Tooltip */ public String getToolTipText(MouseEvent event) { if (getSelectedControl() == null) { return defaultToolTip; } return defaultToolTip + " on this display type"; } /** * Find the tooltip * * @param event mouse event * * @return tooltip */ private String findToolTipText(MouseEvent event) { TreePath path = getPathForLocation(event.getX(), event.getY()); if (path == null) { return defaultToolTip; } Object last = path.getLastPathComponent(); if (last == null) { return defaultToolTip; } if ( !(last instanceof DefaultMutableTreeNode)) { return defaultToolTip; } Object object = ((DefaultMutableTreeNode) last).getUserObject(); if ( !(object instanceof ControlDescriptor)) { return defaultToolTip; } ControlDescriptor cd = (ControlDescriptor) object; return cd.getToolTipText(); } }
[ "private", "class", "ControlTree", "extends", "JTree", "{", "/** tooltip to use */", "private", "String", "defaultToolTip", "=", "\"", "Click here and press F1 for help", "\"", ";", "/**\n * ctor\n */", "public", "ControlTree", "(", ")", "{", "setRootVisible", "(", "false", ")", ";", "setShowsRootHandles", "(", "true", ")", ";", "setToggleClickCount", "(", "1", ")", ";", "setToolTipText", "(", "defaultToolTip", ")", ";", "DefaultTreeCellRenderer", "renderer", "=", "new", "DefaultTreeCellRenderer", "(", ")", "{", "public", "Component", "getTreeCellRendererComponent", "(", "JTree", "theTree", ",", "Object", "value", ",", "boolean", "sel", ",", "boolean", "expanded", ",", "boolean", "leaf", ",", "int", "row", ",", "boolean", "hasFocus", ")", "{", "super", ".", "getTreeCellRendererComponent", "(", "theTree", ",", "value", ",", "sel", ",", "expanded", ",", "leaf", ",", "row", ",", "hasFocus", ")", ";", "if", "(", "!", "(", "value", "instanceof", "DefaultMutableTreeNode", ")", ")", "{", "return", "this", ";", "}", "Object", "object", "=", "(", "(", "DefaultMutableTreeNode", ")", "value", ")", ".", "getUserObject", "(", ")", ";", "if", "(", "!", "(", "object", "instanceof", "ControlDescriptor", ")", ")", "{", "return", "this", ";", "}", "ControlDescriptor", "cd", "=", "(", "ControlDescriptor", ")", "object", ";", "if", "(", "cd", ".", "getIcon", "(", ")", "!=", "null", ")", "{", "ImageIcon", "icon", "=", "GuiUtils", ".", "getImageIcon", "(", "cd", ".", "getIcon", "(", ")", ",", "false", ")", ";", "}", "return", "this", ";", "}", "}", ";", "setCellRenderer", "(", "renderer", ")", ";", "}", "/**\n * get the tooltip\n *\n * @param event mouse event\n *\n * @return Tooltip\n */", "public", "String", "getToolTipText", "(", "MouseEvent", "event", ")", "{", "if", "(", "getSelectedControl", "(", ")", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "return", "defaultToolTip", "+", "\"", " on this display type", "\"", ";", "}", "/**\n * Find the tooltip\n *\n * @param event mouse event\n *\n * @return tooltip\n */", "private", "String", "findToolTipText", "(", "MouseEvent", "event", ")", "{", "TreePath", "path", "=", "getPathForLocation", "(", "event", ".", "getX", "(", ")", ",", "event", ".", "getY", "(", ")", ")", ";", "if", "(", "path", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "Object", "last", "=", "path", ".", "getLastPathComponent", "(", ")", ";", "if", "(", "last", "==", "null", ")", "{", "return", "defaultToolTip", ";", "}", "if", "(", "!", "(", "last", "instanceof", "DefaultMutableTreeNode", ")", ")", "{", "return", "defaultToolTip", ";", "}", "Object", "object", "=", "(", "(", "DefaultMutableTreeNode", ")", "last", ")", ".", "getUserObject", "(", ")", ";", "if", "(", "!", "(", "object", "instanceof", "ControlDescriptor", ")", ")", "{", "return", "defaultToolTip", ";", "}", "ControlDescriptor", "cd", "=", "(", "ControlDescriptor", ")", "object", ";", "return", "cd", ".", "getToolTipText", "(", ")", ";", "}", "}" ]
Class ControlTree shows the display controls.
[ "Class", "ControlTree", "shows", "the", "display", "controls", "." ]
[ "// setIcon(icon);" ]
[ { "param": "JTree", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "JTree", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe5fd24681f64d83e44cbf9d46a1cb37c1d759e6
theghia/SalsaAUI
src/components/functions/gsf/DynamicGameDifficultyBalancing.java
[ "MIT" ]
Java
DynamicGameDifficultyBalancing
/** * DynamicGameDifficultyBalancing Class that implements the GameStatusFunction interface as this class' objective is * to determine what State object should be visited next while the simulation is running to keep the user engaging * with the system. * * @author Gareth Iguasnia * @date 20/02/2020 */
DynamicGameDifficultyBalancing Class that implements the GameStatusFunction interface as this class' objective is to determine what State object should be visited next while the simulation is running to keep the user engaging with the system. @author Gareth Iguasnia @date 20/02/2020
[ "DynamicGameDifficultyBalancing", "Class", "that", "implements", "the", "GameStatusFunction", "interface", "as", "this", "class", "'", "objective", "is", "to", "determine", "what", "State", "object", "should", "be", "visited", "next", "while", "the", "simulation", "is", "running", "to", "keep", "the", "user", "engaging", "with", "the", "system", ".", "@author", "Gareth", "Iguasnia", "@date", "20", "/", "02", "/", "2020" ]
public abstract class DynamicGameDifficultyBalancing implements GameStatusFunction { // This is the threshold that the user's error value needs to surpass in order for the difficulty to be increased private double THRESHOLD = 0.82; // In this design, we only choose a state that has been deemed as easier/harder. // If there is a choice, then we randomly choose. This behaviour can be modified by other GameStatusFunctions private Random randomGenerator; /** * Constructor for the DynamicGameDifficultyBalancing Class */ public DynamicGameDifficultyBalancing() { randomGenerator = new Random(); } public double getThreshold() { return THRESHOLD; } @Override public State getNextState(State currentState) { // Getting the neighbouring states ArrayList<State> neighbours = currentState.getNeighbours(); // The next State that will be decided in this logic State nextState = null; // To be used if there is no average error value associated to the current state ArrayList<State> unexploredNeighbours = sortNeighbours(neighbours, currentState, 5); ArrayList<State> exploredNeighbours = sortNeighbours(neighbours, currentState, 6); // To be used if the user needs to be challenged ArrayList<State> harderExploredNeighbours = sortNeighbours(neighbours, currentState, 1); ArrayList<State> harderUnexploredNeighbours = sortNeighbours(neighbours, currentState, 2); // To be used if the user has struggled on the current state ArrayList<State> easierExploredNeighbours = sortNeighbours(neighbours, currentState, 3); ArrayList<State> easierUnexploredNeighbours = sortNeighbours(neighbours, currentState, 4); // If there are no error values recorded for this state - hence not explored by our definition if (!currentState.hasBeenExplored()) { // If there are unexplored State objects - they take priority if (!unexploredNeighbours.isEmpty()) nextState = chooseRandomState(unexploredNeighbours); // If no unexplored State objects, then just randomly move onto a new State else { nextState = chooseRandomState(exploredNeighbours); } } // There are some error values associated to this state else { // We need to move to a harder state if (currentState.getCurrentAverageErrorValue() > THRESHOLD) { if (!harderUnexploredNeighbours.isEmpty()) // Unexplored State objects have priority nextState = chooseRandomState(harderUnexploredNeighbours); // If all neighbouring State objects have been explored, then choose a harder, explored State object else if (!harderExploredNeighbours.isEmpty()) nextState = chooseRandomState(harderExploredNeighbours); // If all neighbouring states are not harder than the current State, then see if there are any // easier unexplored State objects else if (!easierUnexploredNeighbours.isEmpty()) nextState = chooseRandomState(easierUnexploredNeighbours); // If we reach this block of code, then it means that all neighbouring states have been visited and // are all easier than the current state. Pick the state with the lowest average error value? else if (!easierExploredNeighbours.isEmpty()) nextState = chooseRandomState(easierExploredNeighbours); } // We need to move to an easier/same level state else { if (!easierUnexploredNeighbours.isEmpty()) // Unexplored State objects have priority nextState = chooseRandomState(easierUnexploredNeighbours); // If all easier neighbouring states have been explored, then choose an easier explored state else if (!easierExploredNeighbours.isEmpty()) nextState = chooseRandomState(easierExploredNeighbours); // If all neighbouring states are not easier, then try to choose a "harder", unexplored state else if (!harderUnexploredNeighbours.isEmpty()) nextState = chooseRandomState(harderUnexploredNeighbours); // No -> No-> N0 -> Pick the state with the highest average error value? else if (!harderExploredNeighbours.isEmpty()) nextState = chooseRandomState(harderExploredNeighbours); } } return nextState; } /** * Method to to be overridden to determine what State objects would be set as the hard and explored neighbours * * @param sorted An ArrayList of the states that will be the hard and explored neighbours * @param potentialNeighbour The state to check whether it will be a neighbour * @param currentState The state that the game is currently on */ public abstract void sortHardAndExplored(ArrayList<State> sorted, State potentialNeighbour, State currentState); /** * Method to be overridden to determine what State objects would be set as hard and unexplored neighbours * * @param sorted An ArrayList of the states that will be the hard and unexplored neighbours * @param potentialNeighbour The state to check whether it will be a neighbour * @param currentState The state that the game is currently on */ public abstract void sortHardAndUnexplored(ArrayList<State> sorted, State potentialNeighbour, State currentState); /** * Method to be overriden to determine what State objects would be set as easy and explored neighbours * * @param sorted An ArrayList of the states that will be the easy and explored neighbours * @param potentialNeighbour The state to check whether it will be a neighbour * @param currentState The state that the game is currently on */ public abstract void sortEasyAndExplored(ArrayList<State> sorted, State potentialNeighbour, State currentState); /** * Method to be overridden to determine what State objects would be set as easy and unexplored neighbours * * @param sorted An ArrayList of the states that will be the easy and unexplored neighbours * @param potentialNeighbour The state to check whether it will be a neighbour * @param currentState The state that the game is currently on */ public abstract void sortEasyAndUnexplored(ArrayList<State> sorted, State potentialNeighbour, State currentState); /* Helper method to randomly returns a State object from an ArrayList of State objects */ private State chooseRandomState(ArrayList<State> possibleCandidates) { // Randomly choosing an index number int rndIndex = this.randomGenerator.nextInt(possibleCandidates.size()); return possibleCandidates.get(rndIndex); } /* * Helper method sorts the neighbouring states into a list of easier/harder and/or un/explored states * Code: * 1 - Returns an ArrayList of Harder, Explored State objects * 2 - Returns an ArrayList of Harder, Unexplored State objects * 3 - Returns an ArrayList of Easier/Same level, Explored State objects * 4 - Returns an ArrayList of Easier, Unexplored State objects * 5 - Returns an ArrayList of Unexplored State objects * 6 - Returns an ArrayList of Explored State objects */ private ArrayList<State> sortNeighbours(ArrayList<State> neighbours, State currentState, int code) { // either create 3 private methods ORRR this is an abstract class // that overrides this method... ArrayList<State> sorted = new ArrayList<State>(); for (State state: neighbours) { // Harder, explored if (code == 1 && state.hasBeenExplored()) { sortHardAndExplored(sorted, state, currentState); } // Harder, unexplored states else if (code == 2 && !state.hasBeenExplored()) { // What determines a harder state? sortHardAndUnexplored(sorted, state, currentState); } // Easier/Same level, explored states else if (code == 3 && state.hasBeenExplored()) { sortEasyAndExplored(sorted, state, currentState); } // Easier, unexplored states else if (code == 4 && !state.hasBeenExplored()) { // What determines an easier state? sortEasyAndUnexplored(sorted, state, currentState); } // Unexplored states else if (code == 5 && !state.hasBeenExplored()) sorted.add(state); // Explored states else if (code == 6 && state.hasBeenExplored()) sorted.add(state); } return sorted; } }
[ "public", "abstract", "class", "DynamicGameDifficultyBalancing", "implements", "GameStatusFunction", "{", "private", "double", "THRESHOLD", "=", "0.82", ";", "private", "Random", "randomGenerator", ";", "/**\n * Constructor for the DynamicGameDifficultyBalancing Class\n */", "public", "DynamicGameDifficultyBalancing", "(", ")", "{", "randomGenerator", "=", "new", "Random", "(", ")", ";", "}", "public", "double", "getThreshold", "(", ")", "{", "return", "THRESHOLD", ";", "}", "@", "Override", "public", "State", "getNextState", "(", "State", "currentState", ")", "{", "ArrayList", "<", "State", ">", "neighbours", "=", "currentState", ".", "getNeighbours", "(", ")", ";", "State", "nextState", "=", "null", ";", "ArrayList", "<", "State", ">", "unexploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "5", ")", ";", "ArrayList", "<", "State", ">", "exploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "6", ")", ";", "ArrayList", "<", "State", ">", "harderExploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "1", ")", ";", "ArrayList", "<", "State", ">", "harderUnexploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "2", ")", ";", "ArrayList", "<", "State", ">", "easierExploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "3", ")", ";", "ArrayList", "<", "State", ">", "easierUnexploredNeighbours", "=", "sortNeighbours", "(", "neighbours", ",", "currentState", ",", "4", ")", ";", "if", "(", "!", "currentState", ".", "hasBeenExplored", "(", ")", ")", "{", "if", "(", "!", "unexploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "unexploredNeighbours", ")", ";", "else", "{", "nextState", "=", "chooseRandomState", "(", "exploredNeighbours", ")", ";", "}", "}", "else", "{", "if", "(", "currentState", ".", "getCurrentAverageErrorValue", "(", ")", ">", "THRESHOLD", ")", "{", "if", "(", "!", "harderUnexploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "harderUnexploredNeighbours", ")", ";", "else", "if", "(", "!", "harderExploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "harderExploredNeighbours", ")", ";", "else", "if", "(", "!", "easierUnexploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "easierUnexploredNeighbours", ")", ";", "else", "if", "(", "!", "easierExploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "easierExploredNeighbours", ")", ";", "}", "else", "{", "if", "(", "!", "easierUnexploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "easierUnexploredNeighbours", ")", ";", "else", "if", "(", "!", "easierExploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "easierExploredNeighbours", ")", ";", "else", "if", "(", "!", "harderUnexploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "harderUnexploredNeighbours", ")", ";", "else", "if", "(", "!", "harderExploredNeighbours", ".", "isEmpty", "(", ")", ")", "nextState", "=", "chooseRandomState", "(", "harderExploredNeighbours", ")", ";", "}", "}", "return", "nextState", ";", "}", "/**\n * Method to to be overridden to determine what State objects would be set as the hard and explored neighbours\n *\n * @param sorted An ArrayList of the states that will be the hard and explored neighbours\n * @param potentialNeighbour The state to check whether it will be a neighbour\n * @param currentState The state that the game is currently on\n */", "public", "abstract", "void", "sortHardAndExplored", "(", "ArrayList", "<", "State", ">", "sorted", ",", "State", "potentialNeighbour", ",", "State", "currentState", ")", ";", "/**\n * Method to be overridden to determine what State objects would be set as hard and unexplored neighbours\n *\n * @param sorted An ArrayList of the states that will be the hard and unexplored neighbours\n * @param potentialNeighbour The state to check whether it will be a neighbour\n * @param currentState The state that the game is currently on\n */", "public", "abstract", "void", "sortHardAndUnexplored", "(", "ArrayList", "<", "State", ">", "sorted", ",", "State", "potentialNeighbour", ",", "State", "currentState", ")", ";", "/**\n * Method to be overriden to determine what State objects would be set as easy and explored neighbours\n *\n * @param sorted An ArrayList of the states that will be the easy and explored neighbours\n * @param potentialNeighbour The state to check whether it will be a neighbour\n * @param currentState The state that the game is currently on\n */", "public", "abstract", "void", "sortEasyAndExplored", "(", "ArrayList", "<", "State", ">", "sorted", ",", "State", "potentialNeighbour", ",", "State", "currentState", ")", ";", "/**\n * Method to be overridden to determine what State objects would be set as easy and unexplored neighbours\n *\n * @param sorted An ArrayList of the states that will be the easy and unexplored neighbours\n * @param potentialNeighbour The state to check whether it will be a neighbour\n * @param currentState The state that the game is currently on\n */", "public", "abstract", "void", "sortEasyAndUnexplored", "(", "ArrayList", "<", "State", ">", "sorted", ",", "State", "potentialNeighbour", ",", "State", "currentState", ")", ";", "/* Helper method to randomly returns a State object from an ArrayList of State objects */", "private", "State", "chooseRandomState", "(", "ArrayList", "<", "State", ">", "possibleCandidates", ")", "{", "int", "rndIndex", "=", "this", ".", "randomGenerator", ".", "nextInt", "(", "possibleCandidates", ".", "size", "(", ")", ")", ";", "return", "possibleCandidates", ".", "get", "(", "rndIndex", ")", ";", "}", "/*\n * Helper method sorts the neighbouring states into a list of easier/harder and/or un/explored states\n * Code:\n * 1 - Returns an ArrayList of Harder, Explored State objects\n * 2 - Returns an ArrayList of Harder, Unexplored State objects\n * 3 - Returns an ArrayList of Easier/Same level, Explored State objects\n * 4 - Returns an ArrayList of Easier, Unexplored State objects\n * 5 - Returns an ArrayList of Unexplored State objects\n * 6 - Returns an ArrayList of Explored State objects\n */", "private", "ArrayList", "<", "State", ">", "sortNeighbours", "(", "ArrayList", "<", "State", ">", "neighbours", ",", "State", "currentState", ",", "int", "code", ")", "{", "ArrayList", "<", "State", ">", "sorted", "=", "new", "ArrayList", "<", "State", ">", "(", ")", ";", "for", "(", "State", "state", ":", "neighbours", ")", "{", "if", "(", "code", "==", "1", "&&", "state", ".", "hasBeenExplored", "(", ")", ")", "{", "sortHardAndExplored", "(", "sorted", ",", "state", ",", "currentState", ")", ";", "}", "else", "if", "(", "code", "==", "2", "&&", "!", "state", ".", "hasBeenExplored", "(", ")", ")", "{", "sortHardAndUnexplored", "(", "sorted", ",", "state", ",", "currentState", ")", ";", "}", "else", "if", "(", "code", "==", "3", "&&", "state", ".", "hasBeenExplored", "(", ")", ")", "{", "sortEasyAndExplored", "(", "sorted", ",", "state", ",", "currentState", ")", ";", "}", "else", "if", "(", "code", "==", "4", "&&", "!", "state", ".", "hasBeenExplored", "(", ")", ")", "{", "sortEasyAndUnexplored", "(", "sorted", ",", "state", ",", "currentState", ")", ";", "}", "else", "if", "(", "code", "==", "5", "&&", "!", "state", ".", "hasBeenExplored", "(", ")", ")", "sorted", ".", "add", "(", "state", ")", ";", "else", "if", "(", "code", "==", "6", "&&", "state", ".", "hasBeenExplored", "(", ")", ")", "sorted", ".", "add", "(", "state", ")", ";", "}", "return", "sorted", ";", "}", "}" ]
DynamicGameDifficultyBalancing Class that implements the GameStatusFunction interface as this class' objective is to determine what State object should be visited next while the simulation is running to keep the user engaging with the system.
[ "DynamicGameDifficultyBalancing", "Class", "that", "implements", "the", "GameStatusFunction", "interface", "as", "this", "class", "'", "objective", "is", "to", "determine", "what", "State", "object", "should", "be", "visited", "next", "while", "the", "simulation", "is", "running", "to", "keep", "the", "user", "engaging", "with", "the", "system", "." ]
[ "// This is the threshold that the user's error value needs to surpass in order for the difficulty to be increased", "// In this design, we only choose a state that has been deemed as easier/harder.", "// If there is a choice, then we randomly choose. This behaviour can be modified by other GameStatusFunctions", "// Getting the neighbouring states", "// The next State that will be decided in this logic", "// To be used if there is no average error value associated to the current state", "// To be used if the user needs to be challenged", "// To be used if the user has struggled on the current state", "// If there are no error values recorded for this state - hence not explored by our definition", "// If there are unexplored State objects - they take priority", "// If no unexplored State objects, then just randomly move onto a new State", "// There are some error values associated to this state", "// We need to move to a harder state", "// Unexplored State objects have priority", "// If all neighbouring State objects have been explored, then choose a harder, explored State object", "// If all neighbouring states are not harder than the current State, then see if there are any", "// easier unexplored State objects", "// If we reach this block of code, then it means that all neighbouring states have been visited and", "// are all easier than the current state. Pick the state with the lowest average error value?", "// We need to move to an easier/same level state", "// Unexplored State objects have priority", "// If all easier neighbouring states have been explored, then choose an easier explored state", "// If all neighbouring states are not easier, then try to choose a \"harder\", unexplored state", "// No -> No-> N0 -> Pick the state with the highest average error value?", "// Randomly choosing an index number", "// either create 3 private methods ORRR this is an abstract class", "// that overrides this method...", "// Harder, explored", "// Harder, unexplored states", "// What determines a harder state?", "// Easier/Same level, explored states", "// Easier, unexplored states", "// What determines an easier state?", "// Unexplored states", "// Explored states" ]
[ { "param": "GameStatusFunction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GameStatusFunction", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe60f5e963eafd954f6a028d31402c20812fa022
greatsean/365browser
app/src/main/java/org/chromium/chrome/browser/compositor/layouts/eventfilter/BlackHoleEventFilter.java
[ "Apache-2.0" ]
Java
BlackHoleEventFilter
/** * A {@link BlackHoleEventFilter} eats all the events coming its way with no side effects. */
A BlackHoleEventFilter eats all the events coming its way with no side effects.
[ "A", "BlackHoleEventFilter", "eats", "all", "the", "events", "coming", "its", "way", "with", "no", "side", "effects", "." ]
public class BlackHoleEventFilter extends EventFilter { /** * Creates a {@link BlackHoleEventFilter}. * @param context A {@link Context} instance. * @param host A {@link EventFilterHost} instance. */ public BlackHoleEventFilter(Context context) { super(context); } @Override public boolean onInterceptTouchEventInternal(MotionEvent e, boolean isKeyboardShowing) { return true; } @Override public boolean onTouchEventInternal(MotionEvent e) { return true; } }
[ "public", "class", "BlackHoleEventFilter", "extends", "EventFilter", "{", "/**\n * Creates a {@link BlackHoleEventFilter}.\n * @param context A {@link Context} instance.\n * @param host A {@link EventFilterHost} instance.\n */", "public", "BlackHoleEventFilter", "(", "Context", "context", ")", "{", "super", "(", "context", ")", ";", "}", "@", "Override", "public", "boolean", "onInterceptTouchEventInternal", "(", "MotionEvent", "e", ",", "boolean", "isKeyboardShowing", ")", "{", "return", "true", ";", "}", "@", "Override", "public", "boolean", "onTouchEventInternal", "(", "MotionEvent", "e", ")", "{", "return", "true", ";", "}", "}" ]
A {@link BlackHoleEventFilter} eats all the events coming its way with no side effects.
[ "A", "{", "@link", "BlackHoleEventFilter", "}", "eats", "all", "the", "events", "coming", "its", "way", "with", "no", "side", "effects", "." ]
[]
[ { "param": "EventFilter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EventFilter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe64e124beef63c94531f021538e61e161f6803c
ramtej/qi4j-sdk
samples/dci-cargo/dcisample_b/src/main/java/org/qi4j/sample/dcicargo/sample_b/context/interaction/handling/inspection/event/InspectUnloadedCargo.java
[ "Apache-2.0" ]
Java
InspectUnloadedCargo
/** * Inspect Unloaded Cargo (subfunction use case) * * This is one the variations of the {@link com.marcgrue.dcisample_b.context.interaction.handling.inspection.InspectCargoDeliveryStatus} use case. */
Inspect Unloaded Cargo (subfunction use case) This is one the variations of the com.marcgrue.dcisample_b.context.interaction.handling.inspection.InspectCargoDeliveryStatus use case.
[ "Inspect", "Unloaded", "Cargo", "(", "subfunction", "use", "case", ")", "This", "is", "one", "the", "variations", "of", "the", "com", ".", "marcgrue", ".", "dcisample_b", ".", "context", ".", "interaction", ".", "handling", ".", "inspection", ".", "InspectCargoDeliveryStatus", "use", "case", "." ]
public class InspectUnloadedCargo extends Context { DeliveryInspectorRole deliveryInspector; HandlingEvent unloadEvent; Location unloadLocation; Voyage voyage; RouteSpecification routeSpecification; Location destination; Itinerary itinerary; Integer itineraryProgressIndex; boolean wasMisdirected; public InspectUnloadedCargo( Cargo cargo, HandlingEvent handlingEvent ) { deliveryInspector = rolePlayer( DeliveryInspectorRole.class, cargo ); unloadEvent = handlingEvent; unloadLocation = unloadEvent.location().get(); voyage = unloadEvent.voyage().get(); routeSpecification = cargo.routeSpecification().get(); destination = routeSpecification.destination().get(); itinerary = cargo.itinerary().get(); wasMisdirected = cargo.delivery().get().isMisdirected().get(); // Before inspection itineraryProgressIndex = cargo.delivery().get().itineraryProgressIndex().get(); } public void inspect() throws InspectionException { // Pre-conditions if( unloadEvent == null || !unloadEvent.handlingEventType() .get() .equals( UNLOAD ) || unloadLocation.equals( destination ) ) { throw new InspectionFailedException( "Can only inspect unloaded cargo that hasn't arrived at destination." ); } deliveryInspector.inspectUnloadedCargo(); } @Mixins( DeliveryInspectorRole.Mixin.class ) public interface DeliveryInspectorRole { void setContext( InspectUnloadedCargo context ); void inspectUnloadedCargo() throws InspectionException; class Mixin extends RoleMixin<InspectUnloadedCargo> implements DeliveryInspectorRole { @This Cargo cargo; Delivery newDelivery; public void inspectUnloadedCargo() throws InspectionException { // Step 1 - Collect known delivery data ValueBuilder<Delivery> newDeliveryBuilder = vbf.newValueBuilder( Delivery.class ); newDelivery = newDeliveryBuilder.prototype(); newDelivery.timestamp().set( new Date() ); newDelivery.lastHandlingEvent().set( c.unloadEvent ); newDelivery.transportStatus().set( IN_PORT ); newDelivery.isUnloadedAtDestination().set( false ); // Step 2 - Verify cargo is routed if( c.itinerary == null ) { newDelivery.routingStatus().set( NOT_ROUTED ); newDelivery.itineraryProgressIndex().set( 0 ); cargo.delivery().set( newDeliveryBuilder.newInstance() ); throw new CargoNotRoutedException( c.unloadEvent ); } if( !c.routeSpecification.isSatisfiedBy( c.itinerary ) ) { newDelivery.routingStatus().set( MISROUTED ); newDelivery.itineraryProgressIndex().set( 0 ); cargo.delivery().set( newDeliveryBuilder.newInstance() ); throw new CargoMisroutedException( c.unloadEvent, c.routeSpecification, c.itinerary ); } newDelivery.routingStatus().set( ROUTED ); newDelivery.eta().set( c.itinerary.eta() ); // Current itinerary progress newDelivery.itineraryProgressIndex().set( c.itineraryProgressIndex ); // Step 3 - Verify cargo is on track Leg plannedCarrierMovement = c.itinerary.leg( c.itineraryProgressIndex ); if( plannedCarrierMovement == null ) { throw new InspectionFailedException( "Itinerary progress index '" + c.itineraryProgressIndex + "' is invalid!" ); } Integer itineraryProgressIndex; // if (c.wasMisdirected && c.unloadLocation.equals( c.routeSpecification.origin().get() )) if( c.unloadLocation.equals( c.routeSpecification.origin().get() ) ) // if (c.itineraryProgressIndex == -1) { /** * Unloading in the origin of a route specification of a misdirected cargo * tells us that the cargo has been re-routed (re-routing while on board a * carrier sets new origin of route specification to arrival location of * current carrier movement). * * Since the current unload was related to the old itinerary, we don't verify * the misdirection status against the new itinerary. * * The itinerary index starts over from the first leg of the new itinerary * */ itineraryProgressIndex = 0; } else if( !plannedCarrierMovement.unloadLocation().get().equals( c.unloadLocation ) ) { newDelivery.isMisdirected().set( true ); cargo.delivery().set( newDeliveryBuilder.newInstance() ); throw new CargoMisdirectedException( c.unloadEvent, "Itinerary expected unload in " + plannedCarrierMovement.unloadLocation() .get() ); } else if( !plannedCarrierMovement.voyage().get().equals( c.voyage ) ) { // Do we care if cargo unloads from an unexpected carrier? itineraryProgressIndex = c.itineraryProgressIndex + 1; } else { // Cargo delivery has progressed and we expect a load in next itinerary leg load location itineraryProgressIndex = c.itineraryProgressIndex + 1; } newDelivery.isMisdirected().set( false ); // Modify itinerary progress index according to misdirection status newDelivery.itineraryProgressIndex().set( itineraryProgressIndex ); // Step 4 - Determine next expected handling event Leg nextCarrierMovement = c.itinerary.leg( itineraryProgressIndex ); ValueBuilder<NextHandlingEvent> nextHandlingEvent = vbf.newValueBuilder( NextHandlingEvent.class ); nextHandlingEvent.prototype().handlingEventType().set( LOAD ); nextHandlingEvent.prototype().location().set( nextCarrierMovement.loadLocation().get() ); nextHandlingEvent.prototype().time().set( nextCarrierMovement.loadTime().get() ); nextHandlingEvent.prototype().voyage().set( nextCarrierMovement.voyage().get() ); newDelivery.nextHandlingEvent().set( nextHandlingEvent.newInstance() ); // Step 5 - Save cargo delivery snapshot cargo.delivery().set( newDeliveryBuilder.newInstance() ); } } } }
[ "public", "class", "InspectUnloadedCargo", "extends", "Context", "{", "DeliveryInspectorRole", "deliveryInspector", ";", "HandlingEvent", "unloadEvent", ";", "Location", "unloadLocation", ";", "Voyage", "voyage", ";", "RouteSpecification", "routeSpecification", ";", "Location", "destination", ";", "Itinerary", "itinerary", ";", "Integer", "itineraryProgressIndex", ";", "boolean", "wasMisdirected", ";", "public", "InspectUnloadedCargo", "(", "Cargo", "cargo", ",", "HandlingEvent", "handlingEvent", ")", "{", "deliveryInspector", "=", "rolePlayer", "(", "DeliveryInspectorRole", ".", "class", ",", "cargo", ")", ";", "unloadEvent", "=", "handlingEvent", ";", "unloadLocation", "=", "unloadEvent", ".", "location", "(", ")", ".", "get", "(", ")", ";", "voyage", "=", "unloadEvent", ".", "voyage", "(", ")", ".", "get", "(", ")", ";", "routeSpecification", "=", "cargo", ".", "routeSpecification", "(", ")", ".", "get", "(", ")", ";", "destination", "=", "routeSpecification", ".", "destination", "(", ")", ".", "get", "(", ")", ";", "itinerary", "=", "cargo", ".", "itinerary", "(", ")", ".", "get", "(", ")", ";", "wasMisdirected", "=", "cargo", ".", "delivery", "(", ")", ".", "get", "(", ")", ".", "isMisdirected", "(", ")", ".", "get", "(", ")", ";", "itineraryProgressIndex", "=", "cargo", ".", "delivery", "(", ")", ".", "get", "(", ")", ".", "itineraryProgressIndex", "(", ")", ".", "get", "(", ")", ";", "}", "public", "void", "inspect", "(", ")", "throws", "InspectionException", "{", "if", "(", "unloadEvent", "==", "null", "||", "!", "unloadEvent", ".", "handlingEventType", "(", ")", ".", "get", "(", ")", ".", "equals", "(", "UNLOAD", ")", "||", "unloadLocation", ".", "equals", "(", "destination", ")", ")", "{", "throw", "new", "InspectionFailedException", "(", "\"", "Can only inspect unloaded cargo that hasn't arrived at destination.", "\"", ")", ";", "}", "deliveryInspector", ".", "inspectUnloadedCargo", "(", ")", ";", "}", "@", "Mixins", "(", "DeliveryInspectorRole", ".", "Mixin", ".", "class", ")", "public", "interface", "DeliveryInspectorRole", "{", "void", "setContext", "(", "InspectUnloadedCargo", "context", ")", ";", "void", "inspectUnloadedCargo", "(", ")", "throws", "InspectionException", ";", "class", "Mixin", "extends", "RoleMixin", "<", "InspectUnloadedCargo", ">", "implements", "DeliveryInspectorRole", "{", "@", "This", "Cargo", "cargo", ";", "Delivery", "newDelivery", ";", "public", "void", "inspectUnloadedCargo", "(", ")", "throws", "InspectionException", "{", "ValueBuilder", "<", "Delivery", ">", "newDeliveryBuilder", "=", "vbf", ".", "newValueBuilder", "(", "Delivery", ".", "class", ")", ";", "newDelivery", "=", "newDeliveryBuilder", ".", "prototype", "(", ")", ";", "newDelivery", ".", "timestamp", "(", ")", ".", "set", "(", "new", "Date", "(", ")", ")", ";", "newDelivery", ".", "lastHandlingEvent", "(", ")", ".", "set", "(", "c", ".", "unloadEvent", ")", ";", "newDelivery", ".", "transportStatus", "(", ")", ".", "set", "(", "IN_PORT", ")", ";", "newDelivery", ".", "isUnloadedAtDestination", "(", ")", ".", "set", "(", "false", ")", ";", "if", "(", "c", ".", "itinerary", "==", "null", ")", "{", "newDelivery", ".", "routingStatus", "(", ")", ".", "set", "(", "NOT_ROUTED", ")", ";", "newDelivery", ".", "itineraryProgressIndex", "(", ")", ".", "set", "(", "0", ")", ";", "cargo", ".", "delivery", "(", ")", ".", "set", "(", "newDeliveryBuilder", ".", "newInstance", "(", ")", ")", ";", "throw", "new", "CargoNotRoutedException", "(", "c", ".", "unloadEvent", ")", ";", "}", "if", "(", "!", "c", ".", "routeSpecification", ".", "isSatisfiedBy", "(", "c", ".", "itinerary", ")", ")", "{", "newDelivery", ".", "routingStatus", "(", ")", ".", "set", "(", "MISROUTED", ")", ";", "newDelivery", ".", "itineraryProgressIndex", "(", ")", ".", "set", "(", "0", ")", ";", "cargo", ".", "delivery", "(", ")", ".", "set", "(", "newDeliveryBuilder", ".", "newInstance", "(", ")", ")", ";", "throw", "new", "CargoMisroutedException", "(", "c", ".", "unloadEvent", ",", "c", ".", "routeSpecification", ",", "c", ".", "itinerary", ")", ";", "}", "newDelivery", ".", "routingStatus", "(", ")", ".", "set", "(", "ROUTED", ")", ";", "newDelivery", ".", "eta", "(", ")", ".", "set", "(", "c", ".", "itinerary", ".", "eta", "(", ")", ")", ";", "newDelivery", ".", "itineraryProgressIndex", "(", ")", ".", "set", "(", "c", ".", "itineraryProgressIndex", ")", ";", "Leg", "plannedCarrierMovement", "=", "c", ".", "itinerary", ".", "leg", "(", "c", ".", "itineraryProgressIndex", ")", ";", "if", "(", "plannedCarrierMovement", "==", "null", ")", "{", "throw", "new", "InspectionFailedException", "(", "\"", "Itinerary progress index '", "\"", "+", "c", ".", "itineraryProgressIndex", "+", "\"", "' is invalid!", "\"", ")", ";", "}", "Integer", "itineraryProgressIndex", ";", "if", "(", "c", ".", "unloadLocation", ".", "equals", "(", "c", ".", "routeSpecification", ".", "origin", "(", ")", ".", "get", "(", ")", ")", ")", "{", "/**\n * Unloading in the origin of a route specification of a misdirected cargo\n * tells us that the cargo has been re-routed (re-routing while on board a\n * carrier sets new origin of route specification to arrival location of\n * current carrier movement).\n *\n * Since the current unload was related to the old itinerary, we don't verify\n * the misdirection status against the new itinerary.\n *\n * The itinerary index starts over from the first leg of the new itinerary\n * */", "itineraryProgressIndex", "=", "0", ";", "}", "else", "if", "(", "!", "plannedCarrierMovement", ".", "unloadLocation", "(", ")", ".", "get", "(", ")", ".", "equals", "(", "c", ".", "unloadLocation", ")", ")", "{", "newDelivery", ".", "isMisdirected", "(", ")", ".", "set", "(", "true", ")", ";", "cargo", ".", "delivery", "(", ")", ".", "set", "(", "newDeliveryBuilder", ".", "newInstance", "(", ")", ")", ";", "throw", "new", "CargoMisdirectedException", "(", "c", ".", "unloadEvent", ",", "\"", "Itinerary expected unload in ", "\"", "+", "plannedCarrierMovement", ".", "unloadLocation", "(", ")", ".", "get", "(", ")", ")", ";", "}", "else", "if", "(", "!", "plannedCarrierMovement", ".", "voyage", "(", ")", ".", "get", "(", ")", ".", "equals", "(", "c", ".", "voyage", ")", ")", "{", "itineraryProgressIndex", "=", "c", ".", "itineraryProgressIndex", "+", "1", ";", "}", "else", "{", "itineraryProgressIndex", "=", "c", ".", "itineraryProgressIndex", "+", "1", ";", "}", "newDelivery", ".", "isMisdirected", "(", ")", ".", "set", "(", "false", ")", ";", "newDelivery", ".", "itineraryProgressIndex", "(", ")", ".", "set", "(", "itineraryProgressIndex", ")", ";", "Leg", "nextCarrierMovement", "=", "c", ".", "itinerary", ".", "leg", "(", "itineraryProgressIndex", ")", ";", "ValueBuilder", "<", "NextHandlingEvent", ">", "nextHandlingEvent", "=", "vbf", ".", "newValueBuilder", "(", "NextHandlingEvent", ".", "class", ")", ";", "nextHandlingEvent", ".", "prototype", "(", ")", ".", "handlingEventType", "(", ")", ".", "set", "(", "LOAD", ")", ";", "nextHandlingEvent", ".", "prototype", "(", ")", ".", "location", "(", ")", ".", "set", "(", "nextCarrierMovement", ".", "loadLocation", "(", ")", ".", "get", "(", ")", ")", ";", "nextHandlingEvent", ".", "prototype", "(", ")", ".", "time", "(", ")", ".", "set", "(", "nextCarrierMovement", ".", "loadTime", "(", ")", ".", "get", "(", ")", ")", ";", "nextHandlingEvent", ".", "prototype", "(", ")", ".", "voyage", "(", ")", ".", "set", "(", "nextCarrierMovement", ".", "voyage", "(", ")", ".", "get", "(", ")", ")", ";", "newDelivery", ".", "nextHandlingEvent", "(", ")", ".", "set", "(", "nextHandlingEvent", ".", "newInstance", "(", ")", ")", ";", "cargo", ".", "delivery", "(", ")", ".", "set", "(", "newDeliveryBuilder", ".", "newInstance", "(", ")", ")", ";", "}", "}", "}", "}" ]
Inspect Unloaded Cargo (subfunction use case) This is one the variations of the {@link com.marcgrue.dcisample_b.context.interaction.handling.inspection.InspectCargoDeliveryStatus} use case.
[ "Inspect", "Unloaded", "Cargo", "(", "subfunction", "use", "case", ")", "This", "is", "one", "the", "variations", "of", "the", "{", "@link", "com", ".", "marcgrue", ".", "dcisample_b", ".", "context", ".", "interaction", ".", "handling", ".", "inspection", ".", "InspectCargoDeliveryStatus", "}", "use", "case", "." ]
[ "// Before inspection", "// Pre-conditions", "// Step 1 - Collect known delivery data", "// Step 2 - Verify cargo is routed", "// Current itinerary progress", "// Step 3 - Verify cargo is on track", "// if (c.wasMisdirected && c.unloadLocation.equals( c.routeSpecification.origin().get() ))", "// if (c.itineraryProgressIndex == -1)", "// Do we care if cargo unloads from an unexpected carrier?", "// Cargo delivery has progressed and we expect a load in next itinerary leg load location", "// Modify itinerary progress index according to misdirection status", "// Step 4 - Determine next expected handling event", "// Step 5 - Save cargo delivery snapshot" ]
[ { "param": "Context", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Context", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe6a47ba5e53b8e6dcf184135ad96c3796ae29e5
zou-zhicheng/awesome-java
book-spring-5-recipes/ch16/recipe_16_2_ii/src/test/java/com/apress/springrecipes/bank/AccountServiceImplStubTests.java
[ "Apache-2.0" ]
Java
AccountDaoStub
/** * Partially implemented stub implementation for the {@code AccountDao} */
Partially implemented stub implementation for the AccountDao
[ "Partially", "implemented", "stub", "implementation", "for", "the", "AccountDao" ]
private static class AccountDaoStub implements AccountDao { private String accountNo; private double balance; public void createAccount(Account account) {} public void removeAccount(Account account) {} public Account findAccount(String accountNo) { return new Account(this.accountNo, this.balance); } public void updateAccount(Account account) { this.accountNo = account.getAccountNo(); this.balance = account.getBalance(); } }
[ "private", "static", "class", "AccountDaoStub", "implements", "AccountDao", "{", "private", "String", "accountNo", ";", "private", "double", "balance", ";", "public", "void", "createAccount", "(", "Account", "account", ")", "{", "}", "public", "void", "removeAccount", "(", "Account", "account", ")", "{", "}", "public", "Account", "findAccount", "(", "String", "accountNo", ")", "{", "return", "new", "Account", "(", "this", ".", "accountNo", ",", "this", ".", "balance", ")", ";", "}", "public", "void", "updateAccount", "(", "Account", "account", ")", "{", "this", ".", "accountNo", "=", "account", ".", "getAccountNo", "(", ")", ";", "this", ".", "balance", "=", "account", ".", "getBalance", "(", ")", ";", "}", "}" ]
Partially implemented stub implementation for the {@code AccountDao}
[ "Partially", "implemented", "stub", "implementation", "for", "the", "{", "@code", "AccountDao", "}" ]
[]
[ { "param": "AccountDao", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AccountDao", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe6bca3028b445c35283af2ab8890d9b9f391903
go2zo/infobip-api-java-client
src/main/java/infobip/api/client/GetCampaignDetails.java
[ "Apache-2.0" ]
Java
GetCampaignDetails
/** * This is a generated class and is not intended for modification! */
This is a generated class and is not intended for modification!
[ "This", "is", "a", "generated", "class", "and", "is", "not", "intended", "for", "modification!" ]
public class GetCampaignDetails { private final Configuration configuration; public GetCampaignDetails(Configuration configuration) { this.configuration = configuration; } interface GetCampaignDetailsService { @GET("/omni/1/campaigns/{campaignKey}") Campaign execute(@Path("campaignKey") String campaignKey); } public Campaign execute(String campaignKey) { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(configuration.getBaseUrl()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(new TimeoutClientProvider(configuration).get()) .build(); GetCampaignDetailsService service = retrofit.create(GetCampaignDetailsService.class); return service.execute(campaignKey); } }
[ "public", "class", "GetCampaignDetails", "{", "private", "final", "Configuration", "configuration", ";", "public", "GetCampaignDetails", "(", "Configuration", "configuration", ")", "{", "this", ".", "configuration", "=", "configuration", ";", "}", "interface", "GetCampaignDetailsService", "{", "@", "GET", "(", "\"", "/omni/1/campaigns/{campaignKey}", "\"", ")", "Campaign", "execute", "(", "@", "Path", "(", "\"", "campaignKey", "\"", ")", "String", "campaignKey", ")", ";", "}", "public", "Campaign", "execute", "(", "String", "campaignKey", ")", "{", "Gson", "gson", "=", "new", "GsonBuilder", "(", ")", ".", "setDateFormat", "(", "\"", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "\"", ")", ".", "create", "(", ")", ";", "Retrofit", "retrofit", "=", "new", "Retrofit", ".", "Builder", "(", ")", ".", "baseUrl", "(", "configuration", ".", "getBaseUrl", "(", ")", ")", ".", "addConverterFactory", "(", "GsonConverterFactory", ".", "create", "(", "gson", ")", ")", ".", "client", "(", "new", "TimeoutClientProvider", "(", "configuration", ")", ".", "get", "(", ")", ")", ".", "build", "(", ")", ";", "GetCampaignDetailsService", "service", "=", "retrofit", ".", "create", "(", "GetCampaignDetailsService", ".", "class", ")", ";", "return", "service", ".", "execute", "(", "campaignKey", ")", ";", "}", "}" ]
This is a generated class and is not intended for modification!
[ "This", "is", "a", "generated", "class", "and", "is", "not", "intended", "for", "modification!" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe6c068828abf3f771eb0c4bda61ece9fc055e73
hocyadav/Java
JavaConcepts-Recycle/dec/circularLL_31th_dec/CircularLL_add_print.java
[ "MIT" ]
Java
NodeC
/** * * @author Hariom Yadav | 31-Dec-2019 * */
@author Hariom Yadav | 31-Dec-2019
[ "@author", "Hariom", "Yadav", "|", "31", "-", "Dec", "-", "2019" ]
class NodeC{ int data; NodeC next; public NodeC(int d) { data = d; } }
[ "class", "NodeC", "{", "int", "data", ";", "NodeC", "next", ";", "public", "NodeC", "(", "int", "d", ")", "{", "data", "=", "d", ";", "}", "}" ]
@author Hariom Yadav | 31-Dec-2019
[ "@author", "Hariom", "Yadav", "|", "31", "-", "Dec", "-", "2019" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe6cefb00581eafc68ec64adaaa7b3f037825d6a
ulkeba/openolat
src/main/java/org/olat/admin/user/ChangeUserPasswordForm.java
[ "Apache-2.0" ]
Java
ChangeUserPasswordForm
/** * Initial Date: Jul 14, 2003 * * @author gnaegi<br> * Comment: * Form for changing a user password. */
@author gnaegi Comment: Form for changing a user password.
[ "@author", "gnaegi", "Comment", ":", "Form", "for", "changing", "a", "user", "password", "." ]
public class ChangeUserPasswordForm extends FormBasicController { TextElement pass1; TextElement pass2; TextElement username; String password = ""; private Identity userIdentity; /** * Constructor for user pwd forms. * * @param UserRequest * @param WindowControl * @param Identity of which password is to be changed */ public ChangeUserPasswordForm(UserRequest ureq, WindowControl wControl, Identity treatedIdentity) { super(ureq, wControl, null, Util.createPackageTranslator(ChangePasswordForm.class, ureq.getLocale())); userIdentity = treatedIdentity; initForm(ureq); } @Override public boolean validateFormLogic (UserRequest ureq) { boolean newIsValid = UserManager.getInstance().syntaxCheckOlatPassword(pass1.getValue()); if (!newIsValid) pass1.setErrorKey("form.checkPassword", null); boolean newDoesMatch = pass1.getValue().equals(pass2.getValue()); if(!newDoesMatch) pass1.setErrorKey("error.password.nomatch", null); if (newIsValid && newDoesMatch) return true; pass1.setValue(""); pass2.setValue(""); return false; } @Override protected void formOK(UserRequest ureq) { password = pass1.getValue(); pass1.setValue(""); pass2.setValue(""); fireEvent (ureq, Event.DONE_EVENT); } protected String getNewPassword () { return password; } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { setFormTitle("form.password.new1"); setFormDescription("form.please.enter.new"); username = uifactory.addTextElement("username", "form.username", 255, userIdentity.getName(), formLayout); username.setEnabled(false); pass1 = uifactory.addPasswordElement("pass1", "form.password.new1", 255, "", formLayout); pass2 = uifactory.addPasswordElement("pass2", "form.password.new2", 255, "", formLayout); uifactory.addFormSubmitButton("submit", formLayout); } @Override protected void doDispose() { // } }
[ "public", "class", "ChangeUserPasswordForm", "extends", "FormBasicController", "{", "TextElement", "pass1", ";", "TextElement", "pass2", ";", "TextElement", "username", ";", "String", "password", "=", "\"", "\"", ";", "private", "Identity", "userIdentity", ";", "/**\n\t * Constructor for user pwd forms.\n\t * \n\t * @param UserRequest\n\t * @param WindowControl\n\t * @param Identity of which password is to be changed\n\t */", "public", "ChangeUserPasswordForm", "(", "UserRequest", "ureq", ",", "WindowControl", "wControl", ",", "Identity", "treatedIdentity", ")", "{", "super", "(", "ureq", ",", "wControl", ",", "null", ",", "Util", ".", "createPackageTranslator", "(", "ChangePasswordForm", ".", "class", ",", "ureq", ".", "getLocale", "(", ")", ")", ")", ";", "userIdentity", "=", "treatedIdentity", ";", "initForm", "(", "ureq", ")", ";", "}", "@", "Override", "public", "boolean", "validateFormLogic", "(", "UserRequest", "ureq", ")", "{", "boolean", "newIsValid", "=", "UserManager", ".", "getInstance", "(", ")", ".", "syntaxCheckOlatPassword", "(", "pass1", ".", "getValue", "(", ")", ")", ";", "if", "(", "!", "newIsValid", ")", "pass1", ".", "setErrorKey", "(", "\"", "form.checkPassword", "\"", ",", "null", ")", ";", "boolean", "newDoesMatch", "=", "pass1", ".", "getValue", "(", ")", ".", "equals", "(", "pass2", ".", "getValue", "(", ")", ")", ";", "if", "(", "!", "newDoesMatch", ")", "pass1", ".", "setErrorKey", "(", "\"", "error.password.nomatch", "\"", ",", "null", ")", ";", "if", "(", "newIsValid", "&&", "newDoesMatch", ")", "return", "true", ";", "pass1", ".", "setValue", "(", "\"", "\"", ")", ";", "pass2", ".", "setValue", "(", "\"", "\"", ")", ";", "return", "false", ";", "}", "@", "Override", "protected", "void", "formOK", "(", "UserRequest", "ureq", ")", "{", "password", "=", "pass1", ".", "getValue", "(", ")", ";", "pass1", ".", "setValue", "(", "\"", "\"", ")", ";", "pass2", ".", "setValue", "(", "\"", "\"", ")", ";", "fireEvent", "(", "ureq", ",", "Event", ".", "DONE_EVENT", ")", ";", "}", "protected", "String", "getNewPassword", "(", ")", "{", "return", "password", ";", "}", "@", "Override", "protected", "void", "initForm", "(", "FormItemContainer", "formLayout", ",", "Controller", "listener", ",", "UserRequest", "ureq", ")", "{", "setFormTitle", "(", "\"", "form.password.new1", "\"", ")", ";", "setFormDescription", "(", "\"", "form.please.enter.new", "\"", ")", ";", "username", "=", "uifactory", ".", "addTextElement", "(", "\"", "username", "\"", ",", "\"", "form.username", "\"", ",", "255", ",", "userIdentity", ".", "getName", "(", ")", ",", "formLayout", ")", ";", "username", ".", "setEnabled", "(", "false", ")", ";", "pass1", "=", "uifactory", ".", "addPasswordElement", "(", "\"", "pass1", "\"", ",", "\"", "form.password.new1", "\"", ",", "255", ",", "\"", "\"", ",", "formLayout", ")", ";", "pass2", "=", "uifactory", ".", "addPasswordElement", "(", "\"", "pass2", "\"", ",", "\"", "form.password.new2", "\"", ",", "255", ",", "\"", "\"", ",", "formLayout", ")", ";", "uifactory", ".", "addFormSubmitButton", "(", "\"", "submit", "\"", ",", "formLayout", ")", ";", "}", "@", "Override", "protected", "void", "doDispose", "(", ")", "{", "}", "}" ]
Initial Date: Jul 14, 2003
[ "Initial", "Date", ":", "Jul", "14", "2003" ]
[ "//" ]
[ { "param": "FormBasicController", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "FormBasicController", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe70ff8590f44e63ca6feb2a120fac69cde7ed62
bremersee/fac
bremersee-fac/bremersee-fac-api/src/main/java/org/bremersee/fac/model/AccessResultDto.java
[ "Apache-2.0" ]
Java
AccessResultDto
/** * <p> * Data transfer object of an {@link AccessResult}. * </p> * * @author Christian Bremer */
Data transfer object of an AccessResult. @author Christian Bremer
[ "Data", "transfer", "object", "of", "an", "AccessResult", ".", "@author", "Christian", "Bremer" ]
@SuppressWarnings({"WeakerAccess", "unused"}) @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "accessResult") @XmlType(name = "accessResultType") @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.ALWAYS) @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, creatorVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @JsonPropertyOrder(value = {"accessGranted", "timestamp", "counter", "counterThreshold", "accessDeniedUntil"}) public class AccessResultDto implements AccessResult, Cloneable { private static final long serialVersionUID = 1L; @XmlAttribute(name = "accessGranted", required = true) @JsonProperty(value = "accessGranted", required = true) private boolean accessGranted; @XmlAttribute(name = "timestamp") @JsonProperty(value = "timestamp") private Long timestamp = System.currentTimeMillis(); @XmlAttribute(name = "counter") @JsonProperty(value = "counter") private Integer counter; @XmlAttribute(name = "counterThreshold") @JsonProperty(value = "counterThreshold") private Integer counterThreshold; @XmlAttribute(name = "accessDeniedUntil") @JsonProperty(value = "accessDeniedUntil") private Date accessDeniedUntil; /** * Default constructor. */ public AccessResultDto() { super(); } /** * Constructs an instance with the specified parameter. * * @param accessGranted is access to the resource granted? */ public AccessResultDto(boolean accessGranted) { this.accessGranted = accessGranted; } /** * Constructs an instance with the specified parameters. * * @param accessGranted is access to the resource granted? * @param timestamp the time stamp of the decision */ public AccessResultDto(boolean accessGranted, long timestamp) { this.accessGranted = accessGranted; this.timestamp = timestamp; } /** * Constructs an instance with the specified parameters. * * @param accessGranted is access to the resource granted? * @param timestamp the time stamp of the decision * @param accessDeniedUntil until is the access to the resource is denied */ public AccessResultDto(boolean accessGranted, long timestamp, Date accessDeniedUntil) { this.accessGranted = accessGranted; this.timestamp = timestamp; this.accessDeniedUntil = accessDeniedUntil; } /** * Constructs a clone of another {@link AccessResult}. * * @param accessResult another access result */ public AccessResultDto(AccessResult accessResult) { if (accessResult != null) { this.accessGranted = accessResult.isAccessGranted(); this.timestamp = accessResult.getTimestamp(); this.accessDeniedUntil = accessResult.getAccessDeniedUntil(); this.counter = accessResult.getCounter(); this.counterThreshold = accessResult.getCounterThreshold(); } } @Override public String toString() { return "AccessResultDto [accessGranted=" + accessGranted + ", timestamp=" + timestamp + ", counter=" + counter + ", counterThreshold=" + counterThreshold + ", accessDeniedUntil=" + accessDeniedUntil + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((accessDeniedUntil == null) ? 0 : accessDeniedUntil.hashCode()); result = prime * result + (accessGranted ? 1231 : 1237); result = prime * result + ((counter == null) ? 0 : counter.hashCode()); result = prime * result + ((counterThreshold == null) ? 0 : counterThreshold.hashCode()); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); return result; } @Override public boolean equals(Object obj) { // NOSONAR if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AccessResultDto other = (AccessResultDto) obj; if (accessDeniedUntil == null) { if (other.accessDeniedUntil != null) return false; } else if (!accessDeniedUntil.equals(other.accessDeniedUntil)) return false; if (accessGranted != other.accessGranted) return false; if (counter == null) { if (other.counter != null) return false; } else if (!counter.equals(other.counter)) return false; if (counterThreshold == null) { if (other.counterThreshold != null) return false; } else if (!counterThreshold.equals(other.counterThreshold)) return false; if (timestamp == null) { if (other.timestamp != null) return false; } else if (!timestamp.equals(other.timestamp)) return false; return true; } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public AccessResultDto clone() { // NOSONAR return new AccessResultDto(this); } @Override public boolean isAccessGranted() { return accessGranted; } /** * Sets whether the access to the resource is granted or not. * * @param accessGranted is access to the resource granted? */ public void setAccessGranted(boolean accessGranted) { this.accessGranted = accessGranted; } @Override public Long getTimestamp() { return timestamp; } /** * Sets the time stamp. * * @param timestamp the time stamp */ public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } @Override public Date getAccessDeniedUntil() { return accessDeniedUntil; } /** * Sets until the access to a resource is denied. * * @param accessDeniedUntil a date */ public void setAccessDeniedUntil(Date accessDeniedUntil) { this.accessDeniedUntil = accessDeniedUntil; } @Override public Integer getCounter() { return counter; } public void setCounter(Integer counter) { this.counter = counter; } @Override public Integer getCounterThreshold() { return counterThreshold; } public void setCounterThreshold(Integer counterThreshold) { this.counterThreshold = counterThreshold; } }
[ "@", "SuppressWarnings", "(", "{", "\"", "WeakerAccess", "\"", ",", "\"", "unused", "\"", "}", ")", "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "@", "XmlRootElement", "(", "name", "=", "\"", "accessResult", "\"", ")", "@", "XmlType", "(", "name", "=", "\"", "accessResultType", "\"", ")", "@", "JsonIgnoreProperties", "(", "ignoreUnknown", "=", "true", ")", "@", "JsonInclude", "(", "Include", ".", "ALWAYS", ")", "@", "JsonAutoDetect", "(", "fieldVisibility", "=", "Visibility", ".", "ANY", ",", "getterVisibility", "=", "Visibility", ".", "NONE", ",", "creatorVisibility", "=", "Visibility", ".", "NONE", ",", "isGetterVisibility", "=", "Visibility", ".", "NONE", ",", "setterVisibility", "=", "Visibility", ".", "NONE", ")", "@", "JsonPropertyOrder", "(", "value", "=", "{", "\"", "accessGranted", "\"", ",", "\"", "timestamp", "\"", ",", "\"", "counter", "\"", ",", "\"", "counterThreshold", "\"", ",", "\"", "accessDeniedUntil", "\"", "}", ")", "public", "class", "AccessResultDto", "implements", "AccessResult", ",", "Cloneable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "accessGranted", "\"", ",", "required", "=", "true", ")", "@", "JsonProperty", "(", "value", "=", "\"", "accessGranted", "\"", ",", "required", "=", "true", ")", "private", "boolean", "accessGranted", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "timestamp", "\"", ")", "@", "JsonProperty", "(", "value", "=", "\"", "timestamp", "\"", ")", "private", "Long", "timestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "counter", "\"", ")", "@", "JsonProperty", "(", "value", "=", "\"", "counter", "\"", ")", "private", "Integer", "counter", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "counterThreshold", "\"", ")", "@", "JsonProperty", "(", "value", "=", "\"", "counterThreshold", "\"", ")", "private", "Integer", "counterThreshold", ";", "@", "XmlAttribute", "(", "name", "=", "\"", "accessDeniedUntil", "\"", ")", "@", "JsonProperty", "(", "value", "=", "\"", "accessDeniedUntil", "\"", ")", "private", "Date", "accessDeniedUntil", ";", "/**\n * Default constructor.\n */", "public", "AccessResultDto", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n * Constructs an instance with the specified parameter.\n *\n * @param accessGranted is access to the resource granted?\n */", "public", "AccessResultDto", "(", "boolean", "accessGranted", ")", "{", "this", ".", "accessGranted", "=", "accessGranted", ";", "}", "/**\n * Constructs an instance with the specified parameters.\n *\n * @param accessGranted is access to the resource granted?\n * @param timestamp the time stamp of the decision\n */", "public", "AccessResultDto", "(", "boolean", "accessGranted", ",", "long", "timestamp", ")", "{", "this", ".", "accessGranted", "=", "accessGranted", ";", "this", ".", "timestamp", "=", "timestamp", ";", "}", "/**\n * Constructs an instance with the specified parameters.\n *\n * @param accessGranted is access to the resource granted?\n * @param timestamp the time stamp of the decision\n * @param accessDeniedUntil until is the access to the resource is denied\n */", "public", "AccessResultDto", "(", "boolean", "accessGranted", ",", "long", "timestamp", ",", "Date", "accessDeniedUntil", ")", "{", "this", ".", "accessGranted", "=", "accessGranted", ";", "this", ".", "timestamp", "=", "timestamp", ";", "this", ".", "accessDeniedUntil", "=", "accessDeniedUntil", ";", "}", "/**\n * Constructs a clone of another {@link AccessResult}.\n *\n * @param accessResult another access result\n */", "public", "AccessResultDto", "(", "AccessResult", "accessResult", ")", "{", "if", "(", "accessResult", "!=", "null", ")", "{", "this", ".", "accessGranted", "=", "accessResult", ".", "isAccessGranted", "(", ")", ";", "this", ".", "timestamp", "=", "accessResult", ".", "getTimestamp", "(", ")", ";", "this", ".", "accessDeniedUntil", "=", "accessResult", ".", "getAccessDeniedUntil", "(", ")", ";", "this", ".", "counter", "=", "accessResult", ".", "getCounter", "(", ")", ";", "this", ".", "counterThreshold", "=", "accessResult", ".", "getCounterThreshold", "(", ")", ";", "}", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "AccessResultDto [accessGranted=", "\"", "+", "accessGranted", "+", "\"", ", timestamp=", "\"", "+", "timestamp", "+", "\"", ", counter=", "\"", "+", "counter", "+", "\"", ", counterThreshold=", "\"", "+", "counterThreshold", "+", "\"", ", accessDeniedUntil=", "\"", "+", "accessDeniedUntil", "+", "\"", "]", "\"", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "accessDeniedUntil", "==", "null", ")", "?", "0", ":", "accessDeniedUntil", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "accessGranted", "?", "1231", ":", "1237", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "counter", "==", "null", ")", "?", "0", ":", "counter", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "counterThreshold", "==", "null", ")", "?", "0", ":", "counterThreshold", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "timestamp", "==", "null", ")", "?", "0", ":", "timestamp", ".", "hashCode", "(", ")", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "return", "false", ";", "AccessResultDto", "other", "=", "(", "AccessResultDto", ")", "obj", ";", "if", "(", "accessDeniedUntil", "==", "null", ")", "{", "if", "(", "other", ".", "accessDeniedUntil", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "accessDeniedUntil", ".", "equals", "(", "other", ".", "accessDeniedUntil", ")", ")", "return", "false", ";", "if", "(", "accessGranted", "!=", "other", ".", "accessGranted", ")", "return", "false", ";", "if", "(", "counter", "==", "null", ")", "{", "if", "(", "other", ".", "counter", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "counter", ".", "equals", "(", "other", ".", "counter", ")", ")", "return", "false", ";", "if", "(", "counterThreshold", "==", "null", ")", "{", "if", "(", "other", ".", "counterThreshold", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "counterThreshold", ".", "equals", "(", "other", ".", "counterThreshold", ")", ")", "return", "false", ";", "if", "(", "timestamp", "==", "null", ")", "{", "if", "(", "other", ".", "timestamp", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "timestamp", ".", "equals", "(", "other", ".", "timestamp", ")", ")", "return", "false", ";", "return", "true", ";", "}", "@", "SuppressWarnings", "(", "\"", "MethodDoesntCallSuperMethod", "\"", ")", "@", "Override", "public", "AccessResultDto", "clone", "(", ")", "{", "return", "new", "AccessResultDto", "(", "this", ")", ";", "}", "@", "Override", "public", "boolean", "isAccessGranted", "(", ")", "{", "return", "accessGranted", ";", "}", "/**\n * Sets whether the access to the resource is granted or not.\n *\n * @param accessGranted is access to the resource granted?\n */", "public", "void", "setAccessGranted", "(", "boolean", "accessGranted", ")", "{", "this", ".", "accessGranted", "=", "accessGranted", ";", "}", "@", "Override", "public", "Long", "getTimestamp", "(", ")", "{", "return", "timestamp", ";", "}", "/**\n * Sets the time stamp.\n *\n * @param timestamp the time stamp\n */", "public", "void", "setTimestamp", "(", "Long", "timestamp", ")", "{", "this", ".", "timestamp", "=", "timestamp", ";", "}", "@", "Override", "public", "Date", "getAccessDeniedUntil", "(", ")", "{", "return", "accessDeniedUntil", ";", "}", "/**\n * Sets until the access to a resource is denied.\n *\n * @param accessDeniedUntil a date\n */", "public", "void", "setAccessDeniedUntil", "(", "Date", "accessDeniedUntil", ")", "{", "this", ".", "accessDeniedUntil", "=", "accessDeniedUntil", ";", "}", "@", "Override", "public", "Integer", "getCounter", "(", ")", "{", "return", "counter", ";", "}", "public", "void", "setCounter", "(", "Integer", "counter", ")", "{", "this", ".", "counter", "=", "counter", ";", "}", "@", "Override", "public", "Integer", "getCounterThreshold", "(", ")", "{", "return", "counterThreshold", ";", "}", "public", "void", "setCounterThreshold", "(", "Integer", "counterThreshold", ")", "{", "this", ".", "counterThreshold", "=", "counterThreshold", ";", "}", "}" ]
<p> Data transfer object of an {@link AccessResult}.
[ "<p", ">", "Data", "transfer", "object", "of", "an", "{", "@link", "AccessResult", "}", "." ]
[ "// NOSONAR", "// NOSONAR" ]
[ { "param": "AccessResult, Cloneable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AccessResult, Cloneable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe72bacc195d19083e7bf70d4c2d07dd0be3c721
onap/aai-validation
src/main/java/org/onap/aai/validation/ruledriven/configuration/build/UseRuleBuilder.java
[ "Apache-2.0" ]
Java
UseRuleBuilder
/** * Content Builder for a useRule section * */
Content Builder for a useRule section
[ "Content", "Builder", "for", "a", "useRule", "section" ]
public class UseRuleBuilder extends ContentBuilder { /** * Build a useRule section */ public UseRuleBuilder() { super("useRule"); } /** * @param ruleConfig * @param indent */ public UseRuleBuilder(RuleSection ruleConfig, String indent) { this(); this.indent = indent; appendValue("name", ruleConfig.getName()); appendValue("attributes", ruleConfig.getAttributes()); } }
[ "public", "class", "UseRuleBuilder", "extends", "ContentBuilder", "{", "/**\n\t * Build a useRule section\n\t */", "public", "UseRuleBuilder", "(", ")", "{", "super", "(", "\"", "useRule", "\"", ")", ";", "}", "/**\n\t * @param ruleConfig\n\t * @param indent\n\t */", "public", "UseRuleBuilder", "(", "RuleSection", "ruleConfig", ",", "String", "indent", ")", "{", "this", "(", ")", ";", "this", ".", "indent", "=", "indent", ";", "appendValue", "(", "\"", "name", "\"", ",", "ruleConfig", ".", "getName", "(", ")", ")", ";", "appendValue", "(", "\"", "attributes", "\"", ",", "ruleConfig", ".", "getAttributes", "(", ")", ")", ";", "}", "}" ]
Content Builder for a useRule section
[ "Content", "Builder", "for", "a", "useRule", "section" ]
[]
[ { "param": "ContentBuilder", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ContentBuilder", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe72d49e00ff98eb643c62c06491095e8bc93381
Xooa/xooa-java-sdk
src/main/java/com/xooa/exception/XooaRequestTimeoutException.java
[ "Apache-2.0" ]
Java
XooaRequestTimeoutException
/** * Xooa Request Timeout Exception received when a synchronous call to the API times out and results in a pending response. * * @author kavi * */
Xooa Request Timeout Exception received when a synchronous call to the API times out and results in a pending response. @author kavi
[ "Xooa", "Request", "Timeout", "Exception", "received", "when", "a", "synchronous", "call", "to", "the", "API", "times", "out", "and", "results", "in", "a", "pending", "response", ".", "@author", "kavi" ]
public class XooaRequestTimeoutException extends Exception { private static final long serialVersionUID = -2762335665779877682L; private String resultURL; private String resultId; public String getResultUrl() { return resultURL; } public void setResultUrl(String resultUrl) { this.resultURL = resultUrl; } public String getResultId() { return resultId; } public void setResultId(String resultId) { this.resultId = resultId; } public void display() { System.out.println("Result Id - " + resultId); System.out.println("Result Url - " + resultURL); } }
[ "public", "class", "XooaRequestTimeoutException", "extends", "Exception", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "2762335665779877682L", ";", "private", "String", "resultURL", ";", "private", "String", "resultId", ";", "public", "String", "getResultUrl", "(", ")", "{", "return", "resultURL", ";", "}", "public", "void", "setResultUrl", "(", "String", "resultUrl", ")", "{", "this", ".", "resultURL", "=", "resultUrl", ";", "}", "public", "String", "getResultId", "(", ")", "{", "return", "resultId", ";", "}", "public", "void", "setResultId", "(", "String", "resultId", ")", "{", "this", ".", "resultId", "=", "resultId", ";", "}", "public", "void", "display", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Result Id - ", "\"", "+", "resultId", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Result Url - ", "\"", "+", "resultURL", ")", ";", "}", "}" ]
Xooa Request Timeout Exception received when a synchronous call to the API times out and results in a pending response.
[ "Xooa", "Request", "Timeout", "Exception", "received", "when", "a", "synchronous", "call", "to", "the", "API", "times", "out", "and", "results", "in", "a", "pending", "response", "." ]
[]
[ { "param": "Exception", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Exception", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe7526c0b17021f7c19701aa78e1e45465874888
UKPLab/latech-clfl2017-hittitenlppipeline
src/main/java/pipeline/Cth2CasConverter.java
[ "Apache-2.0" ]
Java
Cth2CasConverter
/** * The purpse of this class is to parse the .odt Translation and Transliteration * Documents. It makes use of the Apache ODF Toolkit, which is availbale on * https://incubator.apache.org/odftoolkit/index.html * * @author Darjush Siahdohoni * */
The purpse of this class is to parse the .odt Translation and Transliteration Documents. @author Darjush Siahdohoni
[ "The", "purpse", "of", "this", "class", "is", "to", "parse", "the", ".", "odt", "Translation", "and", "Transliteration", "Documents", ".", "@author", "Darjush", "Siahdohoni" ]
public class Cth2CasConverter { private TextDocument document; private TextDocument transliteration; private List<Table> translationTableList; private List<Table> transliterationTableList; private int x, y; private StringBuilder bf2; private HashMap<String, String> map; private String documentTitle; private String CTH; private String version = "--"; private String transliterationViewName = "_transliteration"; public Cth2CasConverter() { map = new HashMap<String, String>(280); try { java.util.logging.LogManager.getLogManager().readConfiguration(new java.io.ByteArrayInputStream( "org.odftoolkit.level=WARNING".getBytes(java.nio.charset.StandardCharsets.UTF_8))); readHeadersToMap("src/main/resources/headers.txt"); } catch (IOException e) { e.printStackTrace(); } } public void loadTranslationFile(File translationFile) throws Exception { document = TextDocument.loadDocument(translationFile.getPath()); translationTableList = document.getTableList(); System.out .println("\u001B[32mTranslation File loaded\u001b[0m (" + new File(translationFile.getPath()).getName() + "). Number of Tables: " + translationTableList.size() + ". "); String transliterationPath = getTransliterationFilePathOf(translationFile); if (transliterationPath != null && transliterationPath.length() > 0) { bf2 = new StringBuilder(16384); transliteration = TextDocument.loadDocument(transliterationPath); transliterationTableList = transliteration.getTableList(); System.out.println( "\u001B[32mTransliteration File loaded\u001b[0m (" + new File(transliterationPath).getName() + "). Number of Tables: " + transliterationTableList.size() + ". "); x = y = 0; } int index = translationFile.getName().indexOf('_'); String str = translationFile.getName().substring(0, index); String lang = translationFile.getName().substring(index + 1, index + 3); CTH = str.replaceAll("\\s+", "").trim(); if (map.containsKey(str)) { System.out.println(str + " - " + map.get(str)); documentTitle = map.get(str); } else { documentTitle = getTitle(); System.out.println(str + ":" + documentTitle); saveTitle(str, documentTitle, lang); } } public String parseTranslation(JCas jcas) throws CollectionException, DOMException, Exception { StringBuilder bf = new StringBuilder(16384); String paragraph = ""; boolean newLine = false; for (int i = 0; i < translationTableList.size(); i++) for (int j = 0; j < translationTableList.get(i).getRowCount(); j++) { Row next = translationTableList.get(i).getRowByIndex(j); if(next.getOdfElement().getTextContent().equals("")) continue; Node[] cellNodes = getCells(next.getOdfElement().getChildNodes()); String columnNr = cellNodes[0].getTextContent().trim(); String cleanedColonNr = columnNr.replaceAll("\\s+", ""); // Wenn es eine Zeile mit Paragraphnummer ist (z.B. §3') if (cleanedColonNr.matches("§\\d+(\\.\\d+'*)+|(§\\d+'*)")) { paragraph = cleanedColonNr; newLine = true; continue; // Zum nächsten Row } if (!cleanedColonNr.replaceAll("'", "").matches("\\d+\\w*")) { if(next.getCellCount()<3) continue; if (!(cellNodes[0].getTextContent().trim().equals("") && cellNodes[1].getTextContent().trim().equals(""))) printError("Non-Empty, but unrecognized Row has been found\nCol:" + columnNr + " Col2:" + cellNodes[1].getTextContent() + " Col3:" + cellNodes[2].getTextContent()); continue; } if(!cellNodes[1].getTextContent().trim().matches(version+"|-|–") && !cellNodes[1].getTextContent().trim().equals("")){ printError("Trslat("+columnNr+"): Mittlere Spalte hat abweichende Version: " + cellNodes[1]); continue; } ProcessedColumn ret = processColumn(columnNr, cellNodes[2], true); if (ret == null) { printError("Fatal Running Error."); return null; } if (ret.text.length() > 10 || ret.text.replaceAll("\\s|\\.|\\?|\\!", "").length() > 0) { ProcessedColumn transliteration = getNextTransliterationLine(cleanedColonNr.replaceAll("\\D", ""), columnNr); processTextSnippet(jcas, paragraph, columnNr, ret.text, bf, ret.note, newLine, transliteration.text, transliteration.determiners); if (transliteration != null) processTextSnippet(jcas.getView(transliterationViewName), paragraph, columnNr, transliteration.text, bf2, null, newLine, null, null); else printError("No Transliteration for row " + columnNr + " " + ret.text + " at j: " + j); if (transliteration != null && transliteration.equals("")) printError("Empty Transliteration for row " + columnNr + " " + ret.text); newLine = false; } } return bf.toString(); } private Node[] getCells(NodeList nodeList) { Node childNodeList[] = new Node[3]; int cellCount = 0; for (int m = 0; m < nodeList.getLength(); m++) { Node n = nodeList.item(m); if(n==null) continue; if (n.getNodeName().equals("table:covered-table-cell") && !n.getTextContent().equals("")) printError("table:covered-table-cell Not Empty! text: '" + n.getTextContent() + "'"); else if (n.getNodeName().equals("table:table-cell")) { if (cellCount < 3) { childNodeList[cellCount] = n.getFirstChild(); while (childNodeList[cellCount].hasChildNodes() && (childNodeList[cellCount].getNextSibling() == null)) { childNodeList[cellCount] = childNodeList[cellCount].getFirstChild(); } cellCount++; } else printError("More than 3 table:table-cell"); } else if (!n.getNodeName().equals("table:covered-table-cell")) printError("Unrecognized Cell Name:" + n.getNodeName()); } return childNodeList; } private ProcessedColumn getNextTransliterationLine(String col, String originalCol) { for (; x < transliterationTableList.size();) { for (; y < transliterationTableList.get(x).getRowCount(); y++) { Row next = transliterationTableList.get(x).getRowByIndex(y); if(next.getOdfElement().getTextContent().equals("") || next.getCellCount()<3) continue; Node[] cellNodes = getCells(next.getOdfElement().getChildNodes()); String columnNr = cellNodes[0].getTextContent().replaceAll("\\s+", ""); if (columnNr.matches("§\\d+(\\.\\d+'*)+|(§\\d+'*)")) { continue; // Zum nächsten Row } if(!cellNodes[1].getTextContent().matches(version+"|-|–") && !cellNodes[1].getTextContent().trim().equals("")){ continue; } columnNr = columnNr.replaceAll("'", "").replaceAll("[a-zA-Z]+\\z", ""); try { if (Integer.parseInt(col) < Integer.parseInt(columnNr)) return new ProcessedColumn("", "", new ArrayList<Determiner>()); } catch (Exception e) { printError("Konnte Zahl >" + col + "< oder >" + cellNodes[0].getTextContent() + "< nicht Umwandeln."); } if (!columnNr.equals(col)) continue; ProcessedColumn ret = processColumn(originalCol, cellNodes[2], false); if (ret == null) { printError("Fatal Running Error."); return null; } y++; return ret; } y = 0; x++; } return null; } /** * * processes the column of the read odf-document consistent of a table with 3 columns, containing the paragraph, * a colon number, an identifier if the row contains the "main" translation and the translated text * */ private ProcessedColumn processColumn(String columnNr, Node sib, boolean enableNotes) { String text = ""; String note = ""; ArrayList<Determiner> dets = new ArrayList<Determiner>(); // table is constructed as a tree structure, rows and columns can be accessed via "nodes" // iterates over a level in the tree // case transliteraion: The text is split into several nodes on the same level with annotations in the node-name // that refers to the type of the text (AkkGRAM, SumGRAM, Determiners,...) while (sib != null) { NamedNodeMap attributeMap = sib.getAttributes(); Node style = null; if(attributeMap != null) { style = attributeMap.item(0); } if(style != null) { if(checkStyle(sib) || (sib.getTextContent().matches("(.*[^0-9]+.*)") && !style.getTextContent().contains("--supersc") && (sib.getNodeName().equals("#text") || sib.getNodeName().equals("text:span")))) { if(sib.hasChildNodes()) { String[] result = processChildNodes(sib, text, note, enableNotes, dets); text = result[0]; note = result[1]; } //FIXME: Identify Determiners (no reliable way found yet) // determiners can be identified by style.getTextContent().contains("Determ."), but it may // be the case that a determiner is not annotated as such, when scanned by the odftoolkit // Methods to create a determiner and to merge determiners if they are split int the document structure // see "createDeterminer(Node, String)" and "mergeDeterminers(ArrayList<Determiner>)" in this class else { text += sib.getTextContent(); } } sib = sib.getNextSibling(); } else { if (sib.getNodeName().equals("#text")) text += sib.getTextContent(); else if (sib.getNodeName().equals("text:span")) { if ((!sib.hasChildNodes() && !sib.getTextContent().matches("[0-9]+||^\\?+$")) || (sib.hasChildNodes() && !sib.getFirstChild().hasChildNodes() && !sib.getTextContent().trim().matches("[0-9]+||^\\?+$"))) text += sib.getTextContent(); else { String[] result = processChildNodes(sib, text, note, enableNotes, dets); text = result[0]; note = result[1]; } } else if (sib.getNodeName().equals("text:note")) { if (enableNotes) { note += processNote(removeUnneededChars(text), sib.getChildNodes().item(1).getTextContent()); } } else if (sib.getNodeName().equals("text:list-header")) { printError("A List has been found in row " + columnNr); text += sib.getTextContent(); } sib = sib.getNextSibling(); } } if (note.length() <= 2) note = ""; text = removeUnneededChars(text); dets = mergeDeterminers(dets); return new ProcessedColumn(text, note, dets); } private String[] processChildNodes(Node sib, String text, String note, boolean enableNotes, ArrayList<Determiner> dets) { Node tempSib = sib; int siblings = 0; while (siblings < tempSib.getChildNodes().getLength()) { Node child = tempSib.getChildNodes().item(siblings); //if the translated text contains a footnote if (child.getNodeName().equals("text:note")) { if (enableNotes) { note += processNote(removeUnneededChars(text), child.getChildNodes().item(1).getTextContent()); } } else if ((!child.hasChildNodes() && !child.getTextContent().matches("[0-9]+|^\\?+$")) || (child.hasChildNodes() && !child.getFirstChild().hasChildNodes() && !child.getTextContent().matches("[0-9]+|^\\?+$")) || (child.hasChildNodes() && !child.getFirstChild().hasChildNodes() && checkStyle(child)) || checkStyle(tempSib)) { // FIXME: Extract determiners from the text (not reliable to identify all determiners) // if(!sib.getAttributes().item(0).getTextContent().contains("_Determ.")) { text += child.getTextContent(); } // else { // dets.add(createDeterminer(child, text)); // } else if (tempSib.getChildNodes().getLength() == 1 && tempSib.getFirstChild().getNodeName() == "text:span") { tempSib = tempSib.getFirstChild(); continue; } else if (!tempSib.getTextContent().matches("[0-9]+|^\\?+$")) { if(!tempSib.getNodeName().matches(".*note.*")) { text += child.getTextContent(); } else if(tempSib.getNodeName().matches("text:note")) { note += processNote(removeUnneededChars(text), tempSib.getChildNodes().item(1).getTextContent()); } else { printError("Span has other Format (" + tempSib.getNodeName() + ") at: " + tempSib.getTextContent()); } } siblings++; } return new String[] {text, note}; } private String processNote(String text, String note) { int beginIndex, endIndex; if (text.trim().contains(" ")) { beginIndex = text.lastIndexOf(" ") + 1; endIndex = text.length(); } else { beginIndex = 0; endIndex = text.length(); } return beginIndex + "#begin#" + endIndex + "#end#" + note + "###"; } /** * Checks if the nodes content are relevant for the text * * @param n * @return */ private boolean checkStyle(Node n) { boolean result = false; if(n.hasAttributes()) { NamedNodeMap attributes = n.getAttributes(); Node style = attributes.item(0); if(style.getTextContent().contains("Numeral") || style.getTextContent().contains("Hurrian") || style.getTextContent().contains("Hittite") || style.getTextContent().contains("SumGRAM") || style.getTextContent().contains("Sumerian") || style.getTextContent().contains("AkkGRAM") || style.getTextContent().contains("Akkadian")) { result = true; } } return result; } /** * Process the text found within the given element. If text from the given * element should be included in the document, then it is added and a proper * {@link Field} annotation is created. * * @param jcas * the JCas. * @param localName * the element in which the text was found * @param elementText * the text * @param documentText * the document text buffer */ private void processTextSnippet(JCas jcas, String paragraph, String colonNr, String elementText, StringBuilder documentText, String notes, boolean newLine, String transliteration, ArrayList<Determiner> determiners) { if (newLine) documentText = documentText.append("\n"); int begin = documentText.length(); documentText = documentText.append(elementText); int end = documentText.length(); documentText = documentText.append("\n"); createColonAnnotation(jcas, paragraph, colonNr, notes, begin, end, documentText, transliteration, determiners); } /** * Create a field annotation for the given element name at the given * location. If substitutions are used, the field is created using the * substituted name. * * @param jcas * the JCas. * @param localName * the local name of the current ODT element. * @param begin * the start offset. * @param end * the end offset. * @param determiners * the list of determiners contained in the transliteration */ private void createColonAnnotation(JCas jcas, String paragraph, String colonNr, String notes, int begin, int end, StringBuilder documentText, String transliteration, ArrayList<Determiner> determiners) { Colon Colon = new Colon(jcas, begin, end); Colon.setParagraph(paragraph); Colon.setColon(colonNr); if(transliteration!=null) { Colon.setTransliteration(transliteration); FSArray determinerArray = new FSArray(jcas, determiners.size()); for(int i = 0; i < determiners.size(); i++) { Determiner determiner = determiners.get(i); String word = ""; String previousChar = ""; String nextChar = ""; if(determiner.begin > 0) { previousChar = transliteration.substring(determiner.begin-1, determiner.begin); } if(determiner.begin < documentText.length()) { nextChar = transliteration.substring(determiner.begin, determiner.begin+1); } if(!previousChar.equals(" ")) { String[] words = transliteration.substring(0, determiner.begin).split("\\s"); word = words[words.length-1]; } else if(!nextChar.equals(" ")) { word = transliteration.substring(determiner.begin).split("\\s")[0]; } determinerArray.set(i, convertDeterminer(jcas, determiner, word)); } Colon.setDeterminers(determinerArray); } if (notes != null && notes.length() > 0) { String[] note_arr = notes.split("###"); FSArray footnoteArray = new FSArray(jcas, note_arr.length); for (int indx = 0; indx < note_arr.length; indx++) { int start_index = Integer.parseInt(note_arr[indx].substring(0, note_arr[indx].indexOf("#begin#"))); int end_index = Integer.parseInt( note_arr[indx].substring(note_arr[indx].indexOf("#begin#") + 7, note_arr[indx].indexOf("#end#"))); Footnote footnote = new Footnote(jcas, begin + start_index, begin + end_index); footnote.setFootnote(note_arr[indx].substring(note_arr[indx].indexOf("#end#") + 5)); footnote.setStartIndex(start_index); footnote.setEndIndex(end_index); //Is it really necessary to add footnotes to the indexes? footnote.addToIndexes(); footnoteArray.set(indx, footnote); } Colon.setFootnotes(footnoteArray); } Colon.addToIndexes(); } private types.Determiner convertDeterminer(JCas jcas, Determiner det, String word) { types.Determiner determiner = new types.Determiner(jcas); //convert to uima type determiner determiner.setDeterminedWord(word); determiner.setWordBegin(det.begin); determiner.setWordEnd(det.begin + word.length()); determiner.setDeterminerCode(removeUnneededChars(det.determinerCode)); return determiner; } private void readHeadersToMap(String filePath) throws IOException { File file = new File(filePath); Reader fileReader = new InputStreamReader(new FileInputStream(file), "UTF-8"); @SuppressWarnings("resource") BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { String[] parts = line.split("\t"); map.put(parts[0], parts[1]); } } private String getTitle() { return getTitle("text:h"); } private String getTitle(String tagName) { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); NodeList list = transliteration.getContentDom().getElementsByTagName(tagName); if (list.getLength() == 0) { if (tagName.equals("text:h")) return getTitle("text:p"); printError("There are no Tags with the tag-name: " + tagName); System.out.print("Enter next tag-name: "); String line = bufferedReader.readLine(); return getTitle(line); } for (int i = 0; i < list.getLength(); i++) { String title = list.item(i).getTextContent() .replaceAll("\\(?\\s*CTH\\s*\\d+(\\.(\\d+|\\w+))*\\s*\\)?", "").trim(); title = title.replaceAll("^\\s*–\\s*|^\\s*-\\s*", ""); if (title.length() > 0) { System.out.print("Is this the title?: " + title + "\nInput: "); String line = bufferedReader.readLine(); if (line.matches("j|y|ja|yes|1|t|true")) { return title; } else if (line.matches("n|nein|no|0|f|false")) continue; else if (line.equals("sub")) while (true) { System.out.print("Title length: " + title.length() + "\nStart Index: "); line = bufferedReader.readLine(); int beginIndex = Integer.parseInt(line); System.out.println("End Index: "); line = bufferedReader.readLine(); int endIndex = Integer.parseInt(line); System.out.print( "Is this the title?: " + title.substring(beginIndex, endIndex) + "\nInput: "); line = bufferedReader.readLine(); if (line.matches("j|y|ja|yes|1|t|true")) return title.substring(beginIndex, endIndex); } else return getTitle(line); } } } catch (Exception e) { printError("Exception while trying to read the title"); } return null; } private void saveTitle(String CTH, String title, String lang) { try { title = CTH + "\t" + title + "\tunbekannt\t" + lang + "\n"; Files.write(Paths.get("src/main/resources/headers.txt"), title.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { printError("Exception while trying to save title to headers.txt"); e.printStackTrace(); } } private String getTransliterationFilePathOf(File correspondingTranslationFile) { String filename = correspondingTranslationFile.getName(); int i = filename.indexOf('_'); File transliterationFile = null; try { transliterationFile = new File( correspondingTranslationFile.getParent() + "/" + filename.substring(0, i) + "_tx.odt"); } catch (Exception e) { printError("Es konnte keine Transliterationsdatei gefunden werden."); } if (transliterationFile != null && transliterationFile.isFile() && transliterationFile.canRead()) return transliterationFile.getPath(); return null; } public static String removeUnneededChars(String str) { str = str.replaceAll("\\.\\.\\.|\\(\\?|\\)|\\?", ""); // Entferne "...", "(?)", "?" str = str.replaceAll("\\[|\\]|\\(|\\)|<|>|˺|˹", ""); // Entferne "[", "]", "(", ")", "<", ">" str = str.replaceAll("/", " "); // Ersetze "/" mit " " char c = 0x2026; // Unicode von "…" str = str.replaceAll(String.valueOf(c), ""); str = str.replaceAll("\\s+", " "); // Ersetze Folgen von mehreren Leerzeichen mit einem. str = str.replaceAll("\\s*„\\s*“\\s*", " "); // Ersetze "leere" Zitate mit einem Leerzeichen str = str.replaceAll("„\\s", "„"); // Leerzeichen zw. dem ersten Wort und dem unter Anführungszeichen entfernen str = str.replaceAll("\\s“", "“"); // Leerzeichen zw. dem letzten Wort und dem obere Anführungszeichen entfernen str = str.replaceAll("\\s\\.", "\\."); // Leerzeichen zw. Wort und Punkt entfernen str = str.replaceAll("\\s\\!", "\\!"); // Leerzeichen zw. Wort und Ausrufezeichen entfernen str = str.replaceAll("\\s\\?", "\\?"); // Leerzeichen zw. Wort und Fragezeichen entfernen return str.trim(); } /** * Creates a determiner for a word * * @param node * @param text * @return */ private Determiner createDeterminer(Node node, String text) { String filteredText = removeUnneededChars(text); int start = -1; if(text.endsWith(" ")) { start = filteredText.length()+1; //+1 due to the deletion of the last white space in the string } else { start = filteredText.length(); } Determiner determiner = new Determiner(start, node.getTextContent()); return determiner; } /** * Merge determiners if they belong to the same word * * @param determiners * @return */ private ArrayList<Determiner> mergeDeterminers(ArrayList<Determiner> determiners) { ArrayList<Determiner> temp = new ArrayList<Determiner>(); if(determiners.size() > 1) { for(int i = 0; i < determiners.size()-1; i++) { Determiner det1 = determiners.get(i); Determiner det2 = determiners.get(i+1); if(det1.begin == det2.begin) { temp.add(new Determiner(det1.begin, removeUnneededChars(det1.determinerCode + det2.determinerCode))); i++; } else { temp.add(det1); if(i == determiners.size()-2) { temp.add(det2); break; } } } } else { temp = determiners; } return temp; } public boolean documentloaded() { return document != null || transliteration != null; } public void close() { if (document != null) document.close(); if (transliteration != null) transliteration.close(); document = null; transliteration = null; translationTableList = null; transliterationTableList = null; } private void printError(String str) { System.out.println("\u001B[35mError: " + str + "\u001b[0m"); } public void setTransliterationVersion(String version) { this.version = version; } public String getTransliterationVersion(){ return version; } public void setTransliterationViewName(String transliterationViewName) { this.transliterationViewName = transliterationViewName; } public String getTransliterationViewName(){ return transliterationViewName; } public String getTransliteration() { return bf2.toString(); } public String getCTH() { return CTH; } public String getDocumentTitle() { return documentTitle; } private class ProcessedColumn { String text; String note; ArrayList<Determiner> determiners; public ProcessedColumn(String text, String note, ArrayList<Determiner> determiners) { this.text = text; this.note = note; this.determiners = determiners; } } private class Determiner { int begin; int end; String determinerCode; public Determiner(int begin, String determinerCode) { this.begin = begin; this.end = begin + determinerCode.length(); this.determinerCode = determinerCode; } } }
[ "public", "class", "Cth2CasConverter", "{", "private", "TextDocument", "document", ";", "private", "TextDocument", "transliteration", ";", "private", "List", "<", "Table", ">", "translationTableList", ";", "private", "List", "<", "Table", ">", "transliterationTableList", ";", "private", "int", "x", ",", "y", ";", "private", "StringBuilder", "bf2", ";", "private", "HashMap", "<", "String", ",", "String", ">", "map", ";", "private", "String", "documentTitle", ";", "private", "String", "CTH", ";", "private", "String", "version", "=", "\"", "--", "\"", ";", "private", "String", "transliterationViewName", "=", "\"", "_transliteration", "\"", ";", "public", "Cth2CasConverter", "(", ")", "{", "map", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", "280", ")", ";", "try", "{", "java", ".", "util", ".", "logging", ".", "LogManager", ".", "getLogManager", "(", ")", ".", "readConfiguration", "(", "new", "java", ".", "io", ".", "ByteArrayInputStream", "(", "\"", "org.odftoolkit.level=WARNING", "\"", ".", "getBytes", "(", "java", ".", "nio", ".", "charset", ".", "StandardCharsets", ".", "UTF_8", ")", ")", ")", ";", "readHeadersToMap", "(", "\"", "src/main/resources/headers.txt", "\"", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "public", "void", "loadTranslationFile", "(", "File", "translationFile", ")", "throws", "Exception", "{", "document", "=", "TextDocument", ".", "loadDocument", "(", "translationFile", ".", "getPath", "(", ")", ")", ";", "translationTableList", "=", "document", ".", "getTableList", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\u001B", "[32mTranslation File loaded", "\\u001b", "[0m (", "\"", "+", "new", "File", "(", "translationFile", ".", "getPath", "(", ")", ")", ".", "getName", "(", ")", "+", "\"", "). Number of Tables: ", "\"", "+", "translationTableList", ".", "size", "(", ")", "+", "\"", ". ", "\"", ")", ";", "String", "transliterationPath", "=", "getTransliterationFilePathOf", "(", "translationFile", ")", ";", "if", "(", "transliterationPath", "!=", "null", "&&", "transliterationPath", ".", "length", "(", ")", ">", "0", ")", "{", "bf2", "=", "new", "StringBuilder", "(", "16384", ")", ";", "transliteration", "=", "TextDocument", ".", "loadDocument", "(", "transliterationPath", ")", ";", "transliterationTableList", "=", "transliteration", ".", "getTableList", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\u001B", "[32mTransliteration File loaded", "\\u001b", "[0m (", "\"", "+", "new", "File", "(", "transliterationPath", ")", ".", "getName", "(", ")", "+", "\"", "). Number of Tables: ", "\"", "+", "transliterationTableList", ".", "size", "(", ")", "+", "\"", ". ", "\"", ")", ";", "x", "=", "y", "=", "0", ";", "}", "int", "index", "=", "translationFile", ".", "getName", "(", ")", ".", "indexOf", "(", "'_'", ")", ";", "String", "str", "=", "translationFile", ".", "getName", "(", ")", ".", "substring", "(", "0", ",", "index", ")", ";", "String", "lang", "=", "translationFile", ".", "getName", "(", ")", ".", "substring", "(", "index", "+", "1", ",", "index", "+", "3", ")", ";", "CTH", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s+", "\"", ",", "\"", "\"", ")", ".", "trim", "(", ")", ";", "if", "(", "map", ".", "containsKey", "(", "str", ")", ")", "{", "System", ".", "out", ".", "println", "(", "str", "+", "\"", " - ", "\"", "+", "map", ".", "get", "(", "str", ")", ")", ";", "documentTitle", "=", "map", ".", "get", "(", "str", ")", ";", "}", "else", "{", "documentTitle", "=", "getTitle", "(", ")", ";", "System", ".", "out", ".", "println", "(", "str", "+", "\"", ":", "\"", "+", "documentTitle", ")", ";", "saveTitle", "(", "str", ",", "documentTitle", ",", "lang", ")", ";", "}", "}", "public", "String", "parseTranslation", "(", "JCas", "jcas", ")", "throws", "CollectionException", ",", "DOMException", ",", "Exception", "{", "StringBuilder", "bf", "=", "new", "StringBuilder", "(", "16384", ")", ";", "String", "paragraph", "=", "\"", "\"", ";", "boolean", "newLine", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "translationTableList", ".", "size", "(", ")", ";", "i", "++", ")", "for", "(", "int", "j", "=", "0", ";", "j", "<", "translationTableList", ".", "get", "(", "i", ")", ".", "getRowCount", "(", ")", ";", "j", "++", ")", "{", "Row", "next", "=", "translationTableList", ".", "get", "(", "i", ")", ".", "getRowByIndex", "(", "j", ")", ";", "if", "(", "next", ".", "getOdfElement", "(", ")", ".", "getTextContent", "(", ")", ".", "equals", "(", "\"", "\"", ")", ")", "continue", ";", "Node", "[", "]", "cellNodes", "=", "getCells", "(", "next", ".", "getOdfElement", "(", ")", ".", "getChildNodes", "(", ")", ")", ";", "String", "columnNr", "=", "cellNodes", "[", "0", "]", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ";", "String", "cleanedColonNr", "=", "columnNr", ".", "replaceAll", "(", "\"", "\\\\", "s+", "\"", ",", "\"", "\"", ")", ";", "if", "(", "cleanedColonNr", ".", "matches", "(", "\"", "§\\", "\\d", "+(\\", "\\.", "\\", "\\d", "+'*)+|(§\\\\", "d+", "'*)\")", ")", " ", "{", "", "paragraph", "=", "cleanedColonNr", ";", "newLine", "=", "true", ";", "continue", ";", "}", "if", "(", "!", "cleanedColonNr", ".", "replaceAll", "(", "\"", "'", "\"", ",", "\"", "\"", ")", ".", "matches", "(", "\"", "\\\\", "d+", "\\\\", "w*", "\"", ")", ")", "{", "if", "(", "next", ".", "getCellCount", "(", ")", "<", "3", ")", "continue", ";", "if", "(", "!", "(", "cellNodes", "[", "0", "]", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"", "\"", ")", "&&", "cellNodes", "[", "1", "]", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ".", "equals", "(", "\"", "\"", ")", ")", ")", "printError", "(", "\"", "Non-Empty, but unrecognized Row has been found", "\\n", "Col:", "\"", "+", "columnNr", "+", "\"", " Col2:", "\"", "+", "cellNodes", "[", "1", "]", ".", "getTextContent", "(", ")", "+", "\"", " Col3:", "\"", "+", "cellNodes", "[", "2", "]", ".", "getTextContent", "(", ")", ")", ";", "continue", ";", "}", "if", "(", "!", "cellNodes", "[", "1", "]", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ".", "matches", "(", "version", "+", "\"", "|-|–\")", " ", "&", " !", "e", "llNodes[1", "]", ".", "g", "e", "tTextContent()", ".", "t", "r", "im()", ".", "e", "q", "uals(\"", "\"", ")", ")", "{", "", "", "printError", "(", "\"", "Trslat(", "\"", "+", "columnNr", "+", "\"", "): Mittlere Spalte hat abweichende Version: ", "\"", "+", "cellNodes", "[", "1", "]", ")", ";", "continue", ";", "}", "ProcessedColumn", "ret", "=", "processColumn", "(", "columnNr", ",", "cellNodes", "[", "2", "]", ",", "true", ")", ";", "if", "(", "ret", "==", "null", ")", "{", "printError", "(", "\"", "Fatal Running Error.", "\"", ")", ";", "return", "null", ";", "}", "if", "(", "ret", ".", "text", ".", "length", "(", ")", ">", "10", "||", "ret", ".", "text", ".", "replaceAll", "(", "\"", "\\\\", "s|", "\\\\", ".|", "\\\\", "?|", "\\\\", "!", "\"", ",", "\"", "\"", ")", ".", "length", "(", ")", ">", "0", ")", "{", "ProcessedColumn", "transliteration", "=", "getNextTransliterationLine", "(", "cleanedColonNr", ".", "replaceAll", "(", "\"", "\\\\", "D", "\"", ",", "\"", "\"", ")", ",", "columnNr", ")", ";", "processTextSnippet", "(", "jcas", ",", "paragraph", ",", "columnNr", ",", "ret", ".", "text", ",", "bf", ",", "ret", ".", "note", ",", "newLine", ",", "transliteration", ".", "text", ",", "transliteration", ".", "determiners", ")", ";", "if", "(", "transliteration", "!=", "null", ")", "processTextSnippet", "(", "jcas", ".", "getView", "(", "transliterationViewName", ")", ",", "paragraph", ",", "columnNr", ",", "transliteration", ".", "text", ",", "bf2", ",", "null", ",", "newLine", ",", "null", ",", "null", ")", ";", "else", "printError", "(", "\"", "No Transliteration for row ", "\"", "+", "columnNr", "+", "\"", " ", "\"", "+", "ret", ".", "text", "+", "\"", " at j: ", "\"", "+", "j", ")", ";", "if", "(", "transliteration", "!=", "null", "&&", "transliteration", ".", "equals", "(", "\"", "\"", ")", ")", "printError", "(", "\"", "Empty Transliteration for row ", "\"", "+", "columnNr", "+", "\"", " ", "\"", "+", "ret", ".", "text", ")", ";", "newLine", "=", "false", ";", "}", "}", "return", "bf", ".", "toString", "(", ")", ";", "}", "private", "Node", "[", "]", "getCells", "(", "NodeList", "nodeList", ")", "{", "Node", "childNodeList", "[", "]", "=", "new", "Node", "[", "3", "]", ";", "int", "cellCount", "=", "0", ";", "for", "(", "int", "m", "=", "0", ";", "m", "<", "nodeList", ".", "getLength", "(", ")", ";", "m", "++", ")", "{", "Node", "n", "=", "nodeList", ".", "item", "(", "m", ")", ";", "if", "(", "n", "==", "null", ")", "continue", ";", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "table:covered-table-cell", "\"", ")", "&&", "!", "n", ".", "getTextContent", "(", ")", ".", "equals", "(", "\"", "\"", ")", ")", "printError", "(", "\"", "table:covered-table-cell Not Empty! text: '", "\"", "+", "n", ".", "getTextContent", "(", ")", "+", "\"", "'", "\"", ")", ";", "else", "if", "(", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "table:table-cell", "\"", ")", ")", "{", "if", "(", "cellCount", "<", "3", ")", "{", "childNodeList", "[", "cellCount", "]", "=", "n", ".", "getFirstChild", "(", ")", ";", "while", "(", "childNodeList", "[", "cellCount", "]", ".", "hasChildNodes", "(", ")", "&&", "(", "childNodeList", "[", "cellCount", "]", ".", "getNextSibling", "(", ")", "==", "null", ")", ")", "{", "childNodeList", "[", "cellCount", "]", "=", "childNodeList", "[", "cellCount", "]", ".", "getFirstChild", "(", ")", ";", "}", "cellCount", "++", ";", "}", "else", "printError", "(", "\"", "More than 3 table:table-cell", "\"", ")", ";", "}", "else", "if", "(", "!", "n", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "table:covered-table-cell", "\"", ")", ")", "printError", "(", "\"", "Unrecognized Cell Name:", "\"", "+", "n", ".", "getNodeName", "(", ")", ")", ";", "}", "return", "childNodeList", ";", "}", "private", "ProcessedColumn", "getNextTransliterationLine", "(", "String", "col", ",", "String", "originalCol", ")", "{", "for", "(", ";", "x", "<", "transliterationTableList", ".", "size", "(", ")", ";", ")", "{", "for", "(", ";", "y", "<", "transliterationTableList", ".", "get", "(", "x", ")", ".", "getRowCount", "(", ")", ";", "y", "++", ")", "{", "Row", "next", "=", "transliterationTableList", ".", "get", "(", "x", ")", ".", "getRowByIndex", "(", "y", ")", ";", "if", "(", "next", ".", "getOdfElement", "(", ")", ".", "getTextContent", "(", ")", ".", "equals", "(", "\"", "\"", ")", "||", "next", ".", "getCellCount", "(", ")", "<", "3", ")", "continue", ";", "Node", "[", "]", "cellNodes", "=", "getCells", "(", "next", ".", "getOdfElement", "(", ")", ".", "getChildNodes", "(", ")", ")", ";", "String", "columnNr", "=", "cellNodes", "[", "0", "]", ".", "getTextContent", "(", ")", ".", "replaceAll", "(", "\"", "\\\\", "s+", "\"", ",", "\"", "\"", ")", ";", "if", "(", "columnNr", ".", "matches", "(", "\"", "§\\", "\\d", "+(\\", "\\.", "\\", "\\d", "+'*)+|(§\\\\", "d+", "'*)\")", ")", " ", "{", "", "continue", ";", "}", "if", "(", "!", "cellNodes", "[", "1", "]", ".", "getTextContent", "(", ")", ".", "matches", "(", "version", "+", "\"", "|-|–\")", " ", "&", " !", "e", "llNodes[1", "]", ".", "g", "e", "tTextContent()", ".", "t", "r", "im()", ".", "e", "q", "uals(\"", "\"", ")", ")", "{", "", "", "continue", ";", "}", "columnNr", "=", "columnNr", ".", "replaceAll", "(", "\"", "'", "\"", ",", "\"", "\"", ")", ".", "replaceAll", "(", "\"", "[a-zA-Z]+", "\\\\", "z", "\"", ",", "\"", "\"", ")", ";", "try", "{", "if", "(", "Integer", ".", "parseInt", "(", "col", ")", "<", "Integer", ".", "parseInt", "(", "columnNr", ")", ")", "return", "new", "ProcessedColumn", "(", "\"", "\"", ",", "\"", "\"", ",", "new", "ArrayList", "<", "Determiner", ">", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "printError", "(", "\"", "Konnte Zahl >", "\"", "+", "col", "+", "\"", "< oder >", "\"", "+", "cellNodes", "[", "0", "]", ".", "getTextContent", "(", ")", "+", "\"", "< nicht Umwandeln.", "\"", ")", ";", "}", "if", "(", "!", "columnNr", ".", "equals", "(", "col", ")", ")", "continue", ";", "ProcessedColumn", "ret", "=", "processColumn", "(", "originalCol", ",", "cellNodes", "[", "2", "]", ",", "false", ")", ";", "if", "(", "ret", "==", "null", ")", "{", "printError", "(", "\"", "Fatal Running Error.", "\"", ")", ";", "return", "null", ";", "}", "y", "++", ";", "return", "ret", ";", "}", "y", "=", "0", ";", "x", "++", ";", "}", "return", "null", ";", "}", "/**\n\t * \n\t * processes the column of the read odf-document consistent of a table with 3 columns, containing the paragraph,\n\t * a colon number, an identifier if the row contains the \"main\" translation and the translated text\n\t * \n\t */", "private", "ProcessedColumn", "processColumn", "(", "String", "columnNr", ",", "Node", "sib", ",", "boolean", "enableNotes", ")", "{", "String", "text", "=", "\"", "\"", ";", "String", "note", "=", "\"", "\"", ";", "ArrayList", "<", "Determiner", ">", "dets", "=", "new", "ArrayList", "<", "Determiner", ">", "(", ")", ";", "while", "(", "sib", "!=", "null", ")", "{", "NamedNodeMap", "attributeMap", "=", "sib", ".", "getAttributes", "(", ")", ";", "Node", "style", "=", "null", ";", "if", "(", "attributeMap", "!=", "null", ")", "{", "style", "=", "attributeMap", ".", "item", "(", "0", ")", ";", "}", "if", "(", "style", "!=", "null", ")", "{", "if", "(", "checkStyle", "(", "sib", ")", "||", "(", "sib", ".", "getTextContent", "(", ")", ".", "matches", "(", "\"", "(.*[^0-9]+.*)", "\"", ")", "&&", "!", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "--supersc", "\"", ")", "&&", "(", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "#text", "\"", ")", "||", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "text:span", "\"", ")", ")", ")", ")", "{", "if", "(", "sib", ".", "hasChildNodes", "(", ")", ")", "{", "String", "[", "]", "result", "=", "processChildNodes", "(", "sib", ",", "text", ",", "note", ",", "enableNotes", ",", "dets", ")", ";", "text", "=", "result", "[", "0", "]", ";", "note", "=", "result", "[", "1", "]", ";", "}", "else", "{", "text", "+=", "sib", ".", "getTextContent", "(", ")", ";", "}", "}", "sib", "=", "sib", ".", "getNextSibling", "(", ")", ";", "}", "else", "{", "if", "(", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "#text", "\"", ")", ")", "text", "+=", "sib", ".", "getTextContent", "(", ")", ";", "else", "if", "(", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "text:span", "\"", ")", ")", "{", "if", "(", "(", "!", "sib", ".", "hasChildNodes", "(", ")", "&&", "!", "sib", ".", "getTextContent", "(", ")", ".", "matches", "(", "\"", "[0-9]+||^", "\\\\", "?+$", "\"", ")", ")", "||", "(", "sib", ".", "hasChildNodes", "(", ")", "&&", "!", "sib", ".", "getFirstChild", "(", ")", ".", "hasChildNodes", "(", ")", "&&", "!", "sib", ".", "getTextContent", "(", ")", ".", "trim", "(", ")", ".", "matches", "(", "\"", "[0-9]+||^", "\\\\", "?+$", "\"", ")", ")", ")", "text", "+=", "sib", ".", "getTextContent", "(", ")", ";", "else", "{", "String", "[", "]", "result", "=", "processChildNodes", "(", "sib", ",", "text", ",", "note", ",", "enableNotes", ",", "dets", ")", ";", "text", "=", "result", "[", "0", "]", ";", "note", "=", "result", "[", "1", "]", ";", "}", "}", "else", "if", "(", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "text:note", "\"", ")", ")", "{", "if", "(", "enableNotes", ")", "{", "note", "+=", "processNote", "(", "removeUnneededChars", "(", "text", ")", ",", "sib", ".", "getChildNodes", "(", ")", ".", "item", "(", "1", ")", ".", "getTextContent", "(", ")", ")", ";", "}", "}", "else", "if", "(", "sib", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "text:list-header", "\"", ")", ")", "{", "printError", "(", "\"", "A List has been found in row ", "\"", "+", "columnNr", ")", ";", "text", "+=", "sib", ".", "getTextContent", "(", ")", ";", "}", "sib", "=", "sib", ".", "getNextSibling", "(", ")", ";", "}", "}", "if", "(", "note", ".", "length", "(", ")", "<=", "2", ")", "note", "=", "\"", "\"", ";", "text", "=", "removeUnneededChars", "(", "text", ")", ";", "dets", "=", "mergeDeterminers", "(", "dets", ")", ";", "return", "new", "ProcessedColumn", "(", "text", ",", "note", ",", "dets", ")", ";", "}", "private", "String", "[", "]", "processChildNodes", "(", "Node", "sib", ",", "String", "text", ",", "String", "note", ",", "boolean", "enableNotes", ",", "ArrayList", "<", "Determiner", ">", "dets", ")", "{", "Node", "tempSib", "=", "sib", ";", "int", "siblings", "=", "0", ";", "while", "(", "siblings", "<", "tempSib", ".", "getChildNodes", "(", ")", ".", "getLength", "(", ")", ")", "{", "Node", "child", "=", "tempSib", ".", "getChildNodes", "(", ")", ".", "item", "(", "siblings", ")", ";", "if", "(", "child", ".", "getNodeName", "(", ")", ".", "equals", "(", "\"", "text:note", "\"", ")", ")", "{", "if", "(", "enableNotes", ")", "{", "note", "+=", "processNote", "(", "removeUnneededChars", "(", "text", ")", ",", "child", ".", "getChildNodes", "(", ")", ".", "item", "(", "1", ")", ".", "getTextContent", "(", ")", ")", ";", "}", "}", "else", "if", "(", "(", "!", "child", ".", "hasChildNodes", "(", ")", "&&", "!", "child", ".", "getTextContent", "(", ")", ".", "matches", "(", "\"", "[0-9]+|^", "\\\\", "?+$", "\"", ")", ")", "||", "(", "child", ".", "hasChildNodes", "(", ")", "&&", "!", "child", ".", "getFirstChild", "(", ")", ".", "hasChildNodes", "(", ")", "&&", "!", "child", ".", "getTextContent", "(", ")", ".", "matches", "(", "\"", "[0-9]+|^", "\\\\", "?+$", "\"", ")", ")", "||", "(", "child", ".", "hasChildNodes", "(", ")", "&&", "!", "child", ".", "getFirstChild", "(", ")", ".", "hasChildNodes", "(", ")", "&&", "checkStyle", "(", "child", ")", ")", "||", "checkStyle", "(", "tempSib", ")", ")", "{", "text", "+=", "child", ".", "getTextContent", "(", ")", ";", "}", "else", "if", "(", "tempSib", ".", "getChildNodes", "(", ")", ".", "getLength", "(", ")", "==", "1", "&&", "tempSib", ".", "getFirstChild", "(", ")", ".", "getNodeName", "(", ")", "==", "\"", "text:span", "\"", ")", "{", "tempSib", "=", "tempSib", ".", "getFirstChild", "(", ")", ";", "continue", ";", "}", "else", "if", "(", "!", "tempSib", ".", "getTextContent", "(", ")", ".", "matches", "(", "\"", "[0-9]+|^", "\\\\", "?+$", "\"", ")", ")", "{", "if", "(", "!", "tempSib", ".", "getNodeName", "(", ")", ".", "matches", "(", "\"", ".*note.*", "\"", ")", ")", "{", "text", "+=", "child", ".", "getTextContent", "(", ")", ";", "}", "else", "if", "(", "tempSib", ".", "getNodeName", "(", ")", ".", "matches", "(", "\"", "text:note", "\"", ")", ")", "{", "note", "+=", "processNote", "(", "removeUnneededChars", "(", "text", ")", ",", "tempSib", ".", "getChildNodes", "(", ")", ".", "item", "(", "1", ")", ".", "getTextContent", "(", ")", ")", ";", "}", "else", "{", "printError", "(", "\"", "Span has other Format (", "\"", "+", "tempSib", ".", "getNodeName", "(", ")", "+", "\"", ") at: ", "\"", "+", "tempSib", ".", "getTextContent", "(", ")", ")", ";", "}", "}", "siblings", "++", ";", "}", "return", "new", "String", "[", "]", "{", "text", ",", "note", "}", ";", "}", "private", "String", "processNote", "(", "String", "text", ",", "String", "note", ")", "{", "int", "beginIndex", ",", "endIndex", ";", "if", "(", "text", ".", "trim", "(", ")", ".", "contains", "(", "\"", " ", "\"", ")", ")", "{", "beginIndex", "=", "text", ".", "lastIndexOf", "(", "\"", " ", "\"", ")", "+", "1", ";", "endIndex", "=", "text", ".", "length", "(", ")", ";", "}", "else", "{", "beginIndex", "=", "0", ";", "endIndex", "=", "text", ".", "length", "(", ")", ";", "}", "return", "beginIndex", "+", "\"", "#begin#", "\"", "+", "endIndex", "+", "\"", "#end#", "\"", "+", "note", "+", "\"", "###", "\"", ";", "}", "/**\n\t * Checks if the nodes content are relevant for the text\n\t * \n\t * @param n\n\t * @return\n\t */", "private", "boolean", "checkStyle", "(", "Node", "n", ")", "{", "boolean", "result", "=", "false", ";", "if", "(", "n", ".", "hasAttributes", "(", ")", ")", "{", "NamedNodeMap", "attributes", "=", "n", ".", "getAttributes", "(", ")", ";", "Node", "style", "=", "attributes", ".", "item", "(", "0", ")", ";", "if", "(", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "Numeral", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "Hurrian", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "Hittite", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "SumGRAM", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "Sumerian", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "AkkGRAM", "\"", ")", "||", "style", ".", "getTextContent", "(", ")", ".", "contains", "(", "\"", "Akkadian", "\"", ")", ")", "{", "result", "=", "true", ";", "}", "}", "return", "result", ";", "}", "/**\n\t * Process the text found within the given element. If text from the given\n\t * element should be included in the document, then it is added and a proper\n\t * {@link Field} annotation is created.\n\t *\n\t * @param jcas\n\t * the JCas.\n\t * @param localName\n\t * the element in which the text was found\n\t * @param elementText\n\t * the text\n\t * @param documentText\n\t * the document text buffer\n\t */", "private", "void", "processTextSnippet", "(", "JCas", "jcas", ",", "String", "paragraph", ",", "String", "colonNr", ",", "String", "elementText", ",", "StringBuilder", "documentText", ",", "String", "notes", ",", "boolean", "newLine", ",", "String", "transliteration", ",", "ArrayList", "<", "Determiner", ">", "determiners", ")", "{", "if", "(", "newLine", ")", "documentText", "=", "documentText", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "int", "begin", "=", "documentText", ".", "length", "(", ")", ";", "documentText", "=", "documentText", ".", "append", "(", "elementText", ")", ";", "int", "end", "=", "documentText", ".", "length", "(", ")", ";", "documentText", "=", "documentText", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "createColonAnnotation", "(", "jcas", ",", "paragraph", ",", "colonNr", ",", "notes", ",", "begin", ",", "end", ",", "documentText", ",", "transliteration", ",", "determiners", ")", ";", "}", "/**\n\t * Create a field annotation for the given element name at the given\n\t * location. If substitutions are used, the field is created using the\n\t * substituted name.\n\t *\n\t * @param jcas\n\t * the JCas.\n\t * @param localName\n\t * the local name of the current ODT element.\n\t * @param begin\n\t * the start offset.\n\t * @param end\n\t * the end offset.\n\t * @param determiners\n\t * \t\t\t the list of determiners contained in the transliteration\n\t */", "private", "void", "createColonAnnotation", "(", "JCas", "jcas", ",", "String", "paragraph", ",", "String", "colonNr", ",", "String", "notes", ",", "int", "begin", ",", "int", "end", ",", "StringBuilder", "documentText", ",", "String", "transliteration", ",", "ArrayList", "<", "Determiner", ">", "determiners", ")", "{", "Colon", "Colon", "=", "new", "Colon", "(", "jcas", ",", "begin", ",", "end", ")", ";", "Colon", ".", "setParagraph", "(", "paragraph", ")", ";", "Colon", ".", "setColon", "(", "colonNr", ")", ";", "if", "(", "transliteration", "!=", "null", ")", "{", "Colon", ".", "setTransliteration", "(", "transliteration", ")", ";", "FSArray", "determinerArray", "=", "new", "FSArray", "(", "jcas", ",", "determiners", ".", "size", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "determiners", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Determiner", "determiner", "=", "determiners", ".", "get", "(", "i", ")", ";", "String", "word", "=", "\"", "\"", ";", "String", "previousChar", "=", "\"", "\"", ";", "String", "nextChar", "=", "\"", "\"", ";", "if", "(", "determiner", ".", "begin", ">", "0", ")", "{", "previousChar", "=", "transliteration", ".", "substring", "(", "determiner", ".", "begin", "-", "1", ",", "determiner", ".", "begin", ")", ";", "}", "if", "(", "determiner", ".", "begin", "<", "documentText", ".", "length", "(", ")", ")", "{", "nextChar", "=", "transliteration", ".", "substring", "(", "determiner", ".", "begin", ",", "determiner", ".", "begin", "+", "1", ")", ";", "}", "if", "(", "!", "previousChar", ".", "equals", "(", "\"", " ", "\"", ")", ")", "{", "String", "[", "]", "words", "=", "transliteration", ".", "substring", "(", "0", ",", "determiner", ".", "begin", ")", ".", "split", "(", "\"", "\\\\", "s", "\"", ")", ";", "word", "=", "words", "[", "words", ".", "length", "-", "1", "]", ";", "}", "else", "if", "(", "!", "nextChar", ".", "equals", "(", "\"", " ", "\"", ")", ")", "{", "word", "=", "transliteration", ".", "substring", "(", "determiner", ".", "begin", ")", ".", "split", "(", "\"", "\\\\", "s", "\"", ")", "[", "0", "]", ";", "}", "determinerArray", ".", "set", "(", "i", ",", "convertDeterminer", "(", "jcas", ",", "determiner", ",", "word", ")", ")", ";", "}", "Colon", ".", "setDeterminers", "(", "determinerArray", ")", ";", "}", "if", "(", "notes", "!=", "null", "&&", "notes", ".", "length", "(", ")", ">", "0", ")", "{", "String", "[", "]", "note_arr", "=", "notes", ".", "split", "(", "\"", "###", "\"", ")", ";", "FSArray", "footnoteArray", "=", "new", "FSArray", "(", "jcas", ",", "note_arr", ".", "length", ")", ";", "for", "(", "int", "indx", "=", "0", ";", "indx", "<", "note_arr", ".", "length", ";", "indx", "++", ")", "{", "int", "start_index", "=", "Integer", ".", "parseInt", "(", "note_arr", "[", "indx", "]", ".", "substring", "(", "0", ",", "note_arr", "[", "indx", "]", ".", "indexOf", "(", "\"", "#begin#", "\"", ")", ")", ")", ";", "int", "end_index", "=", "Integer", ".", "parseInt", "(", "note_arr", "[", "indx", "]", ".", "substring", "(", "note_arr", "[", "indx", "]", ".", "indexOf", "(", "\"", "#begin#", "\"", ")", "+", "7", ",", "note_arr", "[", "indx", "]", ".", "indexOf", "(", "\"", "#end#", "\"", ")", ")", ")", ";", "Footnote", "footnote", "=", "new", "Footnote", "(", "jcas", ",", "begin", "+", "start_index", ",", "begin", "+", "end_index", ")", ";", "footnote", ".", "setFootnote", "(", "note_arr", "[", "indx", "]", ".", "substring", "(", "note_arr", "[", "indx", "]", ".", "indexOf", "(", "\"", "#end#", "\"", ")", "+", "5", ")", ")", ";", "footnote", ".", "setStartIndex", "(", "start_index", ")", ";", "footnote", ".", "setEndIndex", "(", "end_index", ")", ";", "footnote", ".", "addToIndexes", "(", ")", ";", "footnoteArray", ".", "set", "(", "indx", ",", "footnote", ")", ";", "}", "Colon", ".", "setFootnotes", "(", "footnoteArray", ")", ";", "}", "Colon", ".", "addToIndexes", "(", ")", ";", "}", "private", "types", ".", "Determiner", "convertDeterminer", "(", "JCas", "jcas", ",", "Determiner", "det", ",", "String", "word", ")", "{", "types", ".", "Determiner", "determiner", "=", "new", "types", ".", "Determiner", "(", "jcas", ")", ";", "determiner", ".", "setDeterminedWord", "(", "word", ")", ";", "determiner", ".", "setWordBegin", "(", "det", ".", "begin", ")", ";", "determiner", ".", "setWordEnd", "(", "det", ".", "begin", "+", "word", ".", "length", "(", ")", ")", ";", "determiner", ".", "setDeterminerCode", "(", "removeUnneededChars", "(", "det", ".", "determinerCode", ")", ")", ";", "return", "determiner", ";", "}", "private", "void", "readHeadersToMap", "(", "String", "filePath", ")", "throws", "IOException", "{", "File", "file", "=", "new", "File", "(", "filePath", ")", ";", "Reader", "fileReader", "=", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "file", ")", ",", "\"", "UTF-8", "\"", ")", ";", "@", "SuppressWarnings", "(", "\"", "resource", "\"", ")", "BufferedReader", "bufferedReader", "=", "new", "BufferedReader", "(", "fileReader", ")", ";", "String", "line", ";", "while", "(", "(", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "[", "]", "parts", "=", "line", ".", "split", "(", "\"", "\\t", "\"", ")", ";", "map", ".", "put", "(", "parts", "[", "0", "]", ",", "parts", "[", "1", "]", ")", ";", "}", "}", "private", "String", "getTitle", "(", ")", "{", "return", "getTitle", "(", "\"", "text:h", "\"", ")", ";", "}", "private", "String", "getTitle", "(", "String", "tagName", ")", "{", "try", "{", "BufferedReader", "bufferedReader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "System", ".", "in", ")", ")", ";", "NodeList", "list", "=", "transliteration", ".", "getContentDom", "(", ")", ".", "getElementsByTagName", "(", "tagName", ")", ";", "if", "(", "list", ".", "getLength", "(", ")", "==", "0", ")", "{", "if", "(", "tagName", ".", "equals", "(", "\"", "text:h", "\"", ")", ")", "return", "getTitle", "(", "\"", "text:p", "\"", ")", ";", "printError", "(", "\"", "There are no Tags with the tag-name: ", "\"", "+", "tagName", ")", ";", "System", ".", "out", ".", "print", "(", "\"", "Enter next tag-name: ", "\"", ")", ";", "String", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ";", "return", "getTitle", "(", "line", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "list", ".", "getLength", "(", ")", ";", "i", "++", ")", "{", "String", "title", "=", "list", ".", "item", "(", "i", ")", ".", "getTextContent", "(", ")", ".", "replaceAll", "(", "\"", "\\\\", "(?", "\\\\", "s*CTH", "\\\\", "s*", "\\\\", "d+(", "\\\\", ".(", "\\\\", "d+|", "\\\\", "w+))*", "\\\\", "s*", "\\\\", ")?", "\"", ",", "\"", "\"", ")", ".", "trim", "(", ")", ";", "title", "=", "title", ".", "replaceAll", "(", "\"", "^", "\\\\", "s*–\\\\", "s*", "|^\\\\", "s*", "-\\\\", "s*", "\",", " ", "\"", ")", ";", "", "", "if", "(", "title", ".", "length", "(", ")", ">", "0", ")", "{", "System", ".", "out", ".", "print", "(", "\"", "Is this the title?: ", "\"", "+", "title", "+", "\"", "\\n", "Input: ", "\"", ")", ";", "String", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ";", "if", "(", "line", ".", "matches", "(", "\"", "j|y|ja|yes|1|t|true", "\"", ")", ")", "{", "return", "title", ";", "}", "else", "if", "(", "line", ".", "matches", "(", "\"", "n|nein|no|0|f|false", "\"", ")", ")", "continue", ";", "else", "if", "(", "line", ".", "equals", "(", "\"", "sub", "\"", ")", ")", "while", "(", "true", ")", "{", "System", ".", "out", ".", "print", "(", "\"", "Title length: ", "\"", "+", "title", ".", "length", "(", ")", "+", "\"", "\\n", "Start Index: ", "\"", ")", ";", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ";", "int", "beginIndex", "=", "Integer", ".", "parseInt", "(", "line", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "End Index: ", "\"", ")", ";", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ";", "int", "endIndex", "=", "Integer", ".", "parseInt", "(", "line", ")", ";", "System", ".", "out", ".", "print", "(", "\"", "Is this the title?: ", "\"", "+", "title", ".", "substring", "(", "beginIndex", ",", "endIndex", ")", "+", "\"", "\\n", "Input: ", "\"", ")", ";", "line", "=", "bufferedReader", ".", "readLine", "(", ")", ";", "if", "(", "line", ".", "matches", "(", "\"", "j|y|ja|yes|1|t|true", "\"", ")", ")", "return", "title", ".", "substring", "(", "beginIndex", ",", "endIndex", ")", ";", "}", "else", "return", "getTitle", "(", "line", ")", ";", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "printError", "(", "\"", "Exception while trying to read the title", "\"", ")", ";", "}", "return", "null", ";", "}", "private", "void", "saveTitle", "(", "String", "CTH", ",", "String", "title", ",", "String", "lang", ")", "{", "try", "{", "title", "=", "CTH", "+", "\"", "\\t", "\"", "+", "title", "+", "\"", "\\t", "unbekannt", "\\t", "\"", "+", "lang", "+", "\"", "\\n", "\"", ";", "Files", ".", "write", "(", "Paths", ".", "get", "(", "\"", "src/main/resources/headers.txt", "\"", ")", ",", "title", ".", "getBytes", "(", ")", ",", "StandardOpenOption", ".", "APPEND", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "printError", "(", "\"", "Exception while trying to save title to headers.txt", "\"", ")", ";", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "private", "String", "getTransliterationFilePathOf", "(", "File", "correspondingTranslationFile", ")", "{", "String", "filename", "=", "correspondingTranslationFile", ".", "getName", "(", ")", ";", "int", "i", "=", "filename", ".", "indexOf", "(", "'_'", ")", ";", "File", "transliterationFile", "=", "null", ";", "try", "{", "transliterationFile", "=", "new", "File", "(", "correspondingTranslationFile", ".", "getParent", "(", ")", "+", "\"", "/", "\"", "+", "filename", ".", "substring", "(", "0", ",", "i", ")", "+", "\"", "_tx.odt", "\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "printError", "(", "\"", "Es konnte keine Transliterationsdatei gefunden werden.", "\"", ")", ";", "}", "if", "(", "transliterationFile", "!=", "null", "&&", "transliterationFile", ".", "isFile", "(", ")", "&&", "transliterationFile", ".", "canRead", "(", ")", ")", "return", "transliterationFile", ".", "getPath", "(", ")", ";", "return", "null", ";", "}", "public", "static", "String", "removeUnneededChars", "(", "String", "str", ")", "{", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", ".", "\\\\", ".", "\\\\", ".|", "\\\\", "(", "\\\\", "?|", "\\\\", ")|", "\\\\", "?", "\"", ",", "\"", "\"", ")", ";", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "[|", "\\\\", "]|", "\\\\", "(|", "\\\\", ")|<|>|˺|˹\",", " ", "\"", ")", ";", " ", "\t", "str", "=", "str", ".", "replaceAll", "(", "\"", "/", "\"", ",", "\"", " ", "\"", ")", ";", "char", "c", "=", "0x2026", ";", "str", "=", "str", ".", "replaceAll", "(", "String", ".", "valueOf", "(", "c", ")", ",", "\"", "\"", ")", ";", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s+", "\"", ",", "\"", " ", "\"", ")", ";", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s*„\\\\", "s*", "“\\\\s*", "\",", " \"", " ", "\"", ";", "\t", "\t", "\t", "/", "str", "=", "str", ".", "replaceAll", "(", "\"", "„\\\\", "s\"", ",", " ", "\"", "\"", ");\t", "\t", "\t", "\t", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s“\",", " ", "\"", "\"", ");\t", "\t", "\t", "\t", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s", "\\\\", ".", "\"", ",", "\"", "\\\\", ".", "\"", ")", ";", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s", "\\\\", "!", "\"", ",", "\"", "\\\\", "!", "\"", ")", ";", "str", "=", "str", ".", "replaceAll", "(", "\"", "\\\\", "s", "\\\\", "?", "\"", ",", "\"", "\\\\", "?", "\"", ")", ";", "return", "str", ".", "trim", "(", ")", ";", "}", "/**\n\t * Creates a determiner for a word\n\t * \n\t * @param node\n\t * @param text\t\n\t * @return\n\t */", "private", "Determiner", "createDeterminer", "(", "Node", "node", ",", "String", "text", ")", "{", "String", "filteredText", "=", "removeUnneededChars", "(", "text", ")", ";", "int", "start", "=", "-", "1", ";", "if", "(", "text", ".", "endsWith", "(", "\"", " ", "\"", ")", ")", "{", "start", "=", "filteredText", ".", "length", "(", ")", "+", "1", ";", "}", "else", "{", "start", "=", "filteredText", ".", "length", "(", ")", ";", "}", "Determiner", "determiner", "=", "new", "Determiner", "(", "start", ",", "node", ".", "getTextContent", "(", ")", ")", ";", "return", "determiner", ";", "}", "/**\n\t * Merge determiners if they belong to the same word\n\t * \n\t * @param determiners\n\t * @return\n\t */", "private", "ArrayList", "<", "Determiner", ">", "mergeDeterminers", "(", "ArrayList", "<", "Determiner", ">", "determiners", ")", "{", "ArrayList", "<", "Determiner", ">", "temp", "=", "new", "ArrayList", "<", "Determiner", ">", "(", ")", ";", "if", "(", "determiners", ".", "size", "(", ")", ">", "1", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "determiners", ".", "size", "(", ")", "-", "1", ";", "i", "++", ")", "{", "Determiner", "det1", "=", "determiners", ".", "get", "(", "i", ")", ";", "Determiner", "det2", "=", "determiners", ".", "get", "(", "i", "+", "1", ")", ";", "if", "(", "det1", ".", "begin", "==", "det2", ".", "begin", ")", "{", "temp", ".", "add", "(", "new", "Determiner", "(", "det1", ".", "begin", ",", "removeUnneededChars", "(", "det1", ".", "determinerCode", "+", "det2", ".", "determinerCode", ")", ")", ")", ";", "i", "++", ";", "}", "else", "{", "temp", ".", "add", "(", "det1", ")", ";", "if", "(", "i", "==", "determiners", ".", "size", "(", ")", "-", "2", ")", "{", "temp", ".", "add", "(", "det2", ")", ";", "break", ";", "}", "}", "}", "}", "else", "{", "temp", "=", "determiners", ";", "}", "return", "temp", ";", "}", "public", "boolean", "documentloaded", "(", ")", "{", "return", "document", "!=", "null", "||", "transliteration", "!=", "null", ";", "}", "public", "void", "close", "(", ")", "{", "if", "(", "document", "!=", "null", ")", "document", ".", "close", "(", ")", ";", "if", "(", "transliteration", "!=", "null", ")", "transliteration", ".", "close", "(", ")", ";", "document", "=", "null", ";", "transliteration", "=", "null", ";", "translationTableList", "=", "null", ";", "transliterationTableList", "=", "null", ";", "}", "private", "void", "printError", "(", "String", "str", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "\\u001B", "[35mError: ", "\"", "+", "str", "+", "\"", "\\u001b", "[0m", "\"", ")", ";", "}", "public", "void", "setTransliterationVersion", "(", "String", "version", ")", "{", "this", ".", "version", "=", "version", ";", "}", "public", "String", "getTransliterationVersion", "(", ")", "{", "return", "version", ";", "}", "public", "void", "setTransliterationViewName", "(", "String", "transliterationViewName", ")", "{", "this", ".", "transliterationViewName", "=", "transliterationViewName", ";", "}", "public", "String", "getTransliterationViewName", "(", ")", "{", "return", "transliterationViewName", ";", "}", "public", "String", "getTransliteration", "(", ")", "{", "return", "bf2", ".", "toString", "(", ")", ";", "}", "public", "String", "getCTH", "(", ")", "{", "return", "CTH", ";", "}", "public", "String", "getDocumentTitle", "(", ")", "{", "return", "documentTitle", ";", "}", "private", "class", "ProcessedColumn", "{", "String", "text", ";", "String", "note", ";", "ArrayList", "<", "Determiner", ">", "determiners", ";", "public", "ProcessedColumn", "(", "String", "text", ",", "String", "note", ",", "ArrayList", "<", "Determiner", ">", "determiners", ")", "{", "this", ".", "text", "=", "text", ";", "this", ".", "note", "=", "note", ";", "this", ".", "determiners", "=", "determiners", ";", "}", "}", "private", "class", "Determiner", "{", "int", "begin", ";", "int", "end", ";", "String", "determinerCode", ";", "public", "Determiner", "(", "int", "begin", ",", "String", "determinerCode", ")", "{", "this", ".", "begin", "=", "begin", ";", "this", ".", "end", "=", "begin", "+", "determinerCode", ".", "length", "(", ")", ";", "this", ".", "determinerCode", "=", "determinerCode", ";", "}", "}", "}" ]
The purpse of this class is to parse the .odt Translation and Transliteration Documents.
[ "The", "purpse", "of", "this", "class", "is", "to", "parse", "the", ".", "odt", "Translation", "and", "Transliteration", "Documents", "." ]
[ "// Wenn es eine Zeile mit Paragraphnummer ist (z.B. §3')", "// Zum nächsten Row", "// Zum nächsten Row", "// table is constructed as a tree structure, rows and columns can be accessed via \"nodes\"", "// iterates over a level in the tree", "// case transliteraion: The text is split into several nodes on the same level with annotations in the node-name", "// that refers to the type of the text (AkkGRAM, SumGRAM, Determiners,...)", "//FIXME: Identify Determiners (no reliable way found yet)", "// determiners can be identified by style.getTextContent().contains(\"Determ.\"), but it may", "// be the case that a determiner is not annotated as such, when scanned by the odftoolkit", "// Methods to create a determiner and to merge determiners if they are split int the document structure", "// see \"createDeterminer(Node, String)\" and \"mergeDeterminers(ArrayList<Determiner>)\" in this class", "//if the translated text contains a footnote", "//\t\t\t\tFIXME: Extract determiners from the text (not reliable to identify all determiners)", "//\t\t\t\tif(!sib.getAttributes().item(0).getTextContent().contains(\"_Determ.\")) {", "//\t\t\t\telse {", "//\t\t\t\t\tdets.add(createDeterminer(child, text));", "//\t\t\t\t}", "//Is it really necessary to add footnotes to the indexes?", "//convert to uima type determiner", "// Entferne \"...\", \"(?)\", \"?\"", " Entferne \"[\", \"]\", \"(\", \")\", \"<\", \">\"", "// Ersetze \"/\" mit \" \"", "// Unicode von \"…\"", "// Ersetze Folgen von mehreren Leerzeichen mit einem.", "rsetze \"leere\" Zitate mit einem Leerzeichen\t\t\t", "eerzeichen zw. dem ersten Wort und dem unter Anführungszeichen entfernen", "eerzeichen zw. dem letzten Wort und dem obere Anführungszeichen entfernen", "// Leerzeichen zw. Wort und Punkt entfernen", "// Leerzeichen zw. Wort und Ausrufezeichen entfernen", "// Leerzeichen zw. Wort und Fragezeichen entfernen", "//+1 due to the deletion of the last white space in the string" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe76f48588e4d70fda66af782b96d249c8e20e9d
yoshioterada/Cognitive-Bot-LUIS-Util
src/main/java/com/yoshio3/services/BotService.java
[ "MIT" ]
Java
BotService
/** * * @author Yoshio Terada */
@author Yoshio Terada
[ "@author", "Yoshio", "Terada" ]
public class BotService{ private final static Logger LOGGER = Logger.getLogger(BotService.class.getName()); private final static String COVERSATIONS = "/v3/conversations/"; private final static String ACTIVITIES = "/activities"; public void sendResponse(MessageFromBotFrameWork requestMessage, String accessToken, String message) { MessageBackToBotFramework creaeteResponseMessage = creaeteResponseMessage(requestMessage, message); LOGGER.log(Level.FINE, "Back Messages:{0}", creaeteResponseMessage.toString()); Jsonb jsonb = JsonbBuilder.create(); String jsonData = jsonb.toJson(creaeteResponseMessage); String serviceUrl = requestMessage.getServiceUrl(); String id = requestMessage.getId(); String convID = requestMessage.getConversation().getId(); try { convID = URLEncoder.encode(convID, "UTF-8"); } catch (UnsupportedEncodingException ex) { LOGGER.log(Level.SEVERE, "UTF-8 is not supported", ex); } String uri = serviceUrl + COVERSATIONS + convID + ACTIVITIES; // + id; Response response = ClientBuilder.newBuilder() .build() .target(uri) .request(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken) .post(Entity.entity(jsonData, MediaType.APPLICATION_JSON)); if (!isRequestSuccess(response)) { LOGGER.log(Level.SEVERE, "{0}:{1}", new Object[]{response.getStatus(), response.readEntity(String.class)}); handleIllegalState(response); } } public MessageBackToBotFramework creaeteResponseMessage(MessageFromBotFrameWork requestMessage, String message) { MessageBackToBotFramework resMsg = new MessageBackToBotFramework(); resMsg.setType("message"); //// 2016-08-18T09:31:31.756Z (UTC Time) Instant instant = Instant.now(); String currentUTC = instant.toString(); resMsg.setTimestamp(currentUTC); From from = new From(); from.setId(requestMessage.getRecipient().getId()); from.setName(requestMessage.getRecipient().getName()); resMsg.setFrom(from); Conversation conversation = new Conversation(); conversation.setId(requestMessage.getConversation().getId()); resMsg.setConversation(conversation); Recipient recipient = new Recipient(); recipient.setId(requestMessage.getRecipient().getId()); recipient.setName(requestMessage.getRecipient().getName()); resMsg.setRecipient(recipient); Members member = new Members(); member.setId(requestMessage.getFrom().getId()); member.setName(requestMessage.getFrom().getName()); Members[] members = new Members[1]; members[0] = member; resMsg.setMembers(members); resMsg.setText(message); resMsg.setReplyToId(requestMessage.getId()); return resMsg; } private boolean isRequestSuccess(Response response) { Response.StatusType statusInfo = response.getStatusInfo(); Response.Status.Family family = statusInfo.getFamily(); return family != null && family == Response.Status.Family.SUCCESSFUL; } /* Operate when the REST invocaiton failed. */ private void handleIllegalState(Response response) throws IllegalStateException { String error = response.readEntity(String.class); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, error); throw new IllegalStateException(error); } }
[ "public", "class", "BotService", "{", "private", "final", "static", "Logger", "LOGGER", "=", "Logger", ".", "getLogger", "(", "BotService", ".", "class", ".", "getName", "(", ")", ")", ";", "private", "final", "static", "String", "COVERSATIONS", "=", "\"", "/v3/conversations/", "\"", ";", "private", "final", "static", "String", "ACTIVITIES", "=", "\"", "/activities", "\"", ";", "public", "void", "sendResponse", "(", "MessageFromBotFrameWork", "requestMessage", ",", "String", "accessToken", ",", "String", "message", ")", "{", "MessageBackToBotFramework", "creaeteResponseMessage", "=", "creaeteResponseMessage", "(", "requestMessage", ",", "message", ")", ";", "LOGGER", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Back Messages:{0}", "\"", ",", "creaeteResponseMessage", ".", "toString", "(", ")", ")", ";", "Jsonb", "jsonb", "=", "JsonbBuilder", ".", "create", "(", ")", ";", "String", "jsonData", "=", "jsonb", ".", "toJson", "(", "creaeteResponseMessage", ")", ";", "String", "serviceUrl", "=", "requestMessage", ".", "getServiceUrl", "(", ")", ";", "String", "id", "=", "requestMessage", ".", "getId", "(", ")", ";", "String", "convID", "=", "requestMessage", ".", "getConversation", "(", ")", ".", "getId", "(", ")", ";", "try", "{", "convID", "=", "URLEncoder", ".", "encode", "(", "convID", ",", "\"", "UTF-8", "\"", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "ex", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "UTF-8 is not supported", "\"", ",", "ex", ")", ";", "}", "String", "uri", "=", "serviceUrl", "+", "COVERSATIONS", "+", "convID", "+", "ACTIVITIES", ";", "Response", "response", "=", "ClientBuilder", ".", "newBuilder", "(", ")", ".", "build", "(", ")", ".", "target", "(", "uri", ")", ".", "request", "(", "MediaType", ".", "APPLICATION_JSON", ")", ".", "header", "(", "\"", "Authorization", "\"", ",", "\"", "Bearer ", "\"", "+", "accessToken", ")", ".", "post", "(", "Entity", ".", "entity", "(", "jsonData", ",", "MediaType", ".", "APPLICATION_JSON", ")", ")", ";", "if", "(", "!", "isRequestSuccess", "(", "response", ")", ")", "{", "LOGGER", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "{0}:{1}", "\"", ",", "new", "Object", "[", "]", "{", "response", ".", "getStatus", "(", ")", ",", "response", ".", "readEntity", "(", "String", ".", "class", ")", "}", ")", ";", "handleIllegalState", "(", "response", ")", ";", "}", "}", "public", "MessageBackToBotFramework", "creaeteResponseMessage", "(", "MessageFromBotFrameWork", "requestMessage", ",", "String", "message", ")", "{", "MessageBackToBotFramework", "resMsg", "=", "new", "MessageBackToBotFramework", "(", ")", ";", "resMsg", ".", "setType", "(", "\"", "message", "\"", ")", ";", "Instant", "instant", "=", "Instant", ".", "now", "(", ")", ";", "String", "currentUTC", "=", "instant", ".", "toString", "(", ")", ";", "resMsg", ".", "setTimestamp", "(", "currentUTC", ")", ";", "From", "from", "=", "new", "From", "(", ")", ";", "from", ".", "setId", "(", "requestMessage", ".", "getRecipient", "(", ")", ".", "getId", "(", ")", ")", ";", "from", ".", "setName", "(", "requestMessage", ".", "getRecipient", "(", ")", ".", "getName", "(", ")", ")", ";", "resMsg", ".", "setFrom", "(", "from", ")", ";", "Conversation", "conversation", "=", "new", "Conversation", "(", ")", ";", "conversation", ".", "setId", "(", "requestMessage", ".", "getConversation", "(", ")", ".", "getId", "(", ")", ")", ";", "resMsg", ".", "setConversation", "(", "conversation", ")", ";", "Recipient", "recipient", "=", "new", "Recipient", "(", ")", ";", "recipient", ".", "setId", "(", "requestMessage", ".", "getRecipient", "(", ")", ".", "getId", "(", ")", ")", ";", "recipient", ".", "setName", "(", "requestMessage", ".", "getRecipient", "(", ")", ".", "getName", "(", ")", ")", ";", "resMsg", ".", "setRecipient", "(", "recipient", ")", ";", "Members", "member", "=", "new", "Members", "(", ")", ";", "member", ".", "setId", "(", "requestMessage", ".", "getFrom", "(", ")", ".", "getId", "(", ")", ")", ";", "member", ".", "setName", "(", "requestMessage", ".", "getFrom", "(", ")", ".", "getName", "(", ")", ")", ";", "Members", "[", "]", "members", "=", "new", "Members", "[", "1", "]", ";", "members", "[", "0", "]", "=", "member", ";", "resMsg", ".", "setMembers", "(", "members", ")", ";", "resMsg", ".", "setText", "(", "message", ")", ";", "resMsg", ".", "setReplyToId", "(", "requestMessage", ".", "getId", "(", ")", ")", ";", "return", "resMsg", ";", "}", "private", "boolean", "isRequestSuccess", "(", "Response", "response", ")", "{", "Response", ".", "StatusType", "statusInfo", "=", "response", ".", "getStatusInfo", "(", ")", ";", "Response", ".", "Status", ".", "Family", "family", "=", "statusInfo", ".", "getFamily", "(", ")", ";", "return", "family", "!=", "null", "&&", "family", "==", "Response", ".", "Status", ".", "Family", ".", "SUCCESSFUL", ";", "}", "/*\n Operate when the REST invocaiton failed.\n */", "private", "void", "handleIllegalState", "(", "Response", "response", ")", "throws", "IllegalStateException", "{", "String", "error", "=", "response", ".", "readEntity", "(", "String", ".", "class", ")", ";", "Logger", ".", "getLogger", "(", "this", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "error", ")", ";", "throw", "new", "IllegalStateException", "(", "error", ")", ";", "}", "}" ]
@author Yoshio Terada
[ "@author", "Yoshio", "Terada" ]
[ "// + id;", "//// 2016-08-18T09:31:31.756Z (UTC Time)" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe793083cf63897c5fe5c2dce3225f1f60717eb6
xiijima/protostuff
protostuff-model/src/main/java/com/dyuproject/protostuff/model/ReadOnlyProperty.java
[ "Apache-2.0" ]
Java
ReadOnlyProperty
/** * ReadOnlyProperty - read-only access on MessageLite and MessageLite.Builder * * @author David Yu * @created Aug 26, 2009 */
@author David Yu @created Aug 26, 2009
[ "@author", "David", "Yu", "@created", "Aug", "26", "2009" ]
public class ReadOnlyProperty extends Property { public static final Property.Factory<ReadOnlyProperty> FACTORY = new Property.Factory<ReadOnlyProperty>() { public ReadOnlyProperty create(PropertyMeta propertyMeta) { return new ReadOnlyProperty(propertyMeta); } public Class<ReadOnlyProperty> getType() { return ReadOnlyProperty.class; } }; private final GetMethod _messageGet, _builderGet; private final HasMethod _messageHas, _builderHas; public ReadOnlyProperty(PropertyMeta propertyMeta) { super(propertyMeta); _messageGet = new GetMethod(); _builderGet = new GetMethod(); if(propertyMeta.isRepeated()) { _messageHas = new RepeatedHasMethod(); _builderHas = new RepeatedHasMethod(); } else { _messageHas = new HasMethod(); _builderHas = new HasMethod(); } _messageHas.init(propertyMeta, propertyMeta.getMessageClass()); _messageGet.init(propertyMeta, propertyMeta.getMessageClass()); _builderHas.init(propertyMeta, propertyMeta.getBuilderClass()); _builderGet.init(propertyMeta, propertyMeta.getBuilderClass()); } public Object getValue(Object target) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if(_propertyMeta.getMessageClass()==target.getClass()) return _messageHas.hasValue(target) ? _messageGet.getValue(target) : null; else if(_propertyMeta.getBuilderClass()==target.getClass()) return _builderHas.hasValue(target) ? _builderGet.getValue(target) : null; return null; } public Object removeValue(Object target) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { throw new UnsupportedOperationException(); } public boolean setValue(Object target, Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { throw new UnsupportedOperationException(); } public boolean replaceValueIfNone(Object target, Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { throw new UnsupportedOperationException(); } public Object replaceValueIfAny(Object target, Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { throw new UnsupportedOperationException(); } }
[ "public", "class", "ReadOnlyProperty", "extends", "Property", "{", "public", "static", "final", "Property", ".", "Factory", "<", "ReadOnlyProperty", ">", "FACTORY", "=", "new", "Property", ".", "Factory", "<", "ReadOnlyProperty", ">", "(", ")", "{", "public", "ReadOnlyProperty", "create", "(", "PropertyMeta", "propertyMeta", ")", "{", "return", "new", "ReadOnlyProperty", "(", "propertyMeta", ")", ";", "}", "public", "Class", "<", "ReadOnlyProperty", ">", "getType", "(", ")", "{", "return", "ReadOnlyProperty", ".", "class", ";", "}", "}", ";", "private", "final", "GetMethod", "_messageGet", ",", "_builderGet", ";", "private", "final", "HasMethod", "_messageHas", ",", "_builderHas", ";", "public", "ReadOnlyProperty", "(", "PropertyMeta", "propertyMeta", ")", "{", "super", "(", "propertyMeta", ")", ";", "_messageGet", "=", "new", "GetMethod", "(", ")", ";", "_builderGet", "=", "new", "GetMethod", "(", ")", ";", "if", "(", "propertyMeta", ".", "isRepeated", "(", ")", ")", "{", "_messageHas", "=", "new", "RepeatedHasMethod", "(", ")", ";", "_builderHas", "=", "new", "RepeatedHasMethod", "(", ")", ";", "}", "else", "{", "_messageHas", "=", "new", "HasMethod", "(", ")", ";", "_builderHas", "=", "new", "HasMethod", "(", ")", ";", "}", "_messageHas", ".", "init", "(", "propertyMeta", ",", "propertyMeta", ".", "getMessageClass", "(", ")", ")", ";", "_messageGet", ".", "init", "(", "propertyMeta", ",", "propertyMeta", ".", "getMessageClass", "(", ")", ")", ";", "_builderHas", ".", "init", "(", "propertyMeta", ",", "propertyMeta", ".", "getBuilderClass", "(", ")", ")", ";", "_builderGet", ".", "init", "(", "propertyMeta", ",", "propertyMeta", ".", "getBuilderClass", "(", ")", ")", ";", "}", "public", "Object", "getValue", "(", "Object", "target", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "if", "(", "_propertyMeta", ".", "getMessageClass", "(", ")", "==", "target", ".", "getClass", "(", ")", ")", "return", "_messageHas", ".", "hasValue", "(", "target", ")", "?", "_messageGet", ".", "getValue", "(", "target", ")", ":", "null", ";", "else", "if", "(", "_propertyMeta", ".", "getBuilderClass", "(", ")", "==", "target", ".", "getClass", "(", ")", ")", "return", "_builderHas", ".", "hasValue", "(", "target", ")", "?", "_builderGet", ".", "getValue", "(", "target", ")", ":", "null", ";", "return", "null", ";", "}", "public", "Object", "removeValue", "(", "Object", "target", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "public", "boolean", "setValue", "(", "Object", "target", ",", "Object", "value", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "public", "boolean", "replaceValueIfNone", "(", "Object", "target", ",", "Object", "value", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "public", "Object", "replaceValueIfAny", "(", "Object", "target", ",", "Object", "value", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "InvocationTargetException", "{", "throw", "new", "UnsupportedOperationException", "(", ")", ";", "}", "}" ]
ReadOnlyProperty - read-only access on MessageLite and MessageLite.Builder
[ "ReadOnlyProperty", "-", "read", "-", "only", "access", "on", "MessageLite", "and", "MessageLite", ".", "Builder" ]
[]
[ { "param": "Property", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Property", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe79babf37ae3d72b8b9e9be1e52242c994b99bd
SecureBankingAccessToolkit/securebanking-openbanking-uk-rs
securebanking-openbanking-uk-rs-simulator-server/src/main/java/com/forgerock/securebanking/openbanking/uk/rs/service/AnalyticsLogService.java
[ "ECL-2.0", "Apache-2.0" ]
Java
AnalyticsLogService
/** * Outputs the occurrence of an event/activity to the configured default logger. Each output has a recognised prefix * so that is it easy to identify the analytics events in the logs. */
Outputs the occurrence of an event/activity to the configured default logger. Each output has a recognised prefix so that is it easy to identify the analytics events in the logs.
[ "Outputs", "the", "occurrence", "of", "an", "event", "/", "activity", "to", "the", "configured", "default", "logger", ".", "Each", "output", "has", "a", "recognised", "prefix", "so", "that", "is", "it", "easy", "to", "identify", "the", "analytics", "events", "in", "the", "logs", "." ]
@Component @Slf4j public class AnalyticsLogService implements AnalyticsService { // TODO #25 - we may not need this prefix private static final String PREFIX = "ANALYTICS: "; /** * {@inheritDoc} */ @Override public void recordActivity(String text, Object... arguments) { log.info(PREFIX + text, arguments); } }
[ "@", "Component", "@", "Slf4j", "public", "class", "AnalyticsLogService", "implements", "AnalyticsService", "{", "private", "static", "final", "String", "PREFIX", "=", "\"", "ANALYTICS: ", "\"", ";", "/**\n * {@inheritDoc}\n */", "@", "Override", "public", "void", "recordActivity", "(", "String", "text", ",", "Object", "...", "arguments", ")", "{", "log", ".", "info", "(", "PREFIX", "+", "text", ",", "arguments", ")", ";", "}", "}" ]
Outputs the occurrence of an event/activity to the configured default logger.
[ "Outputs", "the", "occurrence", "of", "an", "event", "/", "activity", "to", "the", "configured", "default", "logger", "." ]
[ "// TODO #25 - we may not need this prefix" ]
[ { "param": "AnalyticsService", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AnalyticsService", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe79e15c8049da2b496dbeb83b405a90cc3649ce
BenjaminLiCN/quickstart-java
config/src/main/java/com/google/firebase/samples/config/Configure.java
[ "CC-BY-4.0" ]
Java
Configure
/** * Retrieve and publish templates for Firebase Remote Config using the REST API. */
Retrieve and publish templates for Firebase Remote Config using the REST API.
[ "Retrieve", "and", "publish", "templates", "for", "Firebase", "Remote", "Config", "using", "the", "REST", "API", "." ]
public class Configure { private final static String PROJECT_ID = "PROJECT_ID"; private final static String BASE_URL = "https://firebaseremoteconfig.googleapis.com"; private final static String REMOTE_CONFIG_ENDPOINT = "/v1/projects/" + PROJECT_ID + "/remoteConfig"; private final static String[] SCOPES = { "https://www.googleapis.com/auth/firebase.remoteconfig" }; /** * Retrieve a valid access token that can be use to authorize requests to the Remote Config REST * API. * * @return Access token. * @throws IOException */ // [START retrieve_access_token] private static String getAccessToken() throws IOException { GoogleCredential googleCredential = GoogleCredential .fromStream(new FileInputStream("service-account.json")) .createScoped(Arrays.asList(SCOPES)); googleCredential.refreshToken(); return googleCredential.getAccessToken(); } // [END retrieve_access_token] /** * Get current Firebase Remote Config template from server and store it locally. * * @throws IOException */ private static void getTemplate() throws IOException { HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("Accept-Encoding", "gzip"); int code = httpURLConnection.getResponseCode(); if (code == 200) { InputStream inputStream = new GZIPInputStream(httpURLConnection.getInputStream()); String response = inputstreamToString(inputStream); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(response); Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); String jsonStr = gson.toJson(jsonElement); File file = new File("config.json"); PrintWriter printWriter = new PrintWriter(new FileWriter(file)); printWriter.print(jsonStr); printWriter.flush(); printWriter.close(); System.out.println("Template retrieved and has been written to config.json"); // Print ETag String etag = httpURLConnection.getHeaderField("ETag"); System.out.println("ETag from server: " + etag); } else { System.out.println(inputstreamToString(httpURLConnection.getErrorStream())); } } /** * Print the last 5 available Firebase Remote Config template metadata from the server. * * @throws IOException */ private static void getVersions() throws IOException { HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT + ":listVersions?pageSize=5"); httpURLConnection.setRequestMethod("GET"); int code = httpURLConnection.getResponseCode(); if (code == 200) { String versions = inputstreamToPrettyString(httpURLConnection.getInputStream()); System.out.println("Versions:"); System.out.println(versions); } else { System.out.println(inputstreamToString(httpURLConnection.getErrorStream())); } } /** * Roll back to an available version of Firebase Remote Config template. * * @param version The version to roll back to. * * @throws IOException */ private static void rollback(int version) throws IOException { HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT + ":rollback"); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Accept-Encoding", "gzip"); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("version_number", version); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); outputStreamWriter.write(jsonObject.toString()); outputStreamWriter.flush(); outputStreamWriter.close(); int code = httpURLConnection.getResponseCode(); if (code == 200) { System.out.println("Rolled back to: " + version); InputStream inputStream = new GZIPInputStream(httpURLConnection.getInputStream()); System.out.println(inputstreamToPrettyString(inputStream)); // Print ETag String etag = httpURLConnection.getHeaderField("ETag"); System.out.println("ETag from server: " + etag); } else { System.out.println("Error:"); InputStream inputStream = new GZIPInputStream(httpURLConnection.getErrorStream()); System.out.println(inputstreamToString(inputStream)); } } /** * Publish local template to Firebase server. * * @throws IOException */ private static void publishTemplate(String etag) throws IOException { if (etag.equals("*")) { Scanner scanner = new Scanner(System.in); System.out.println("Are you sure you would like to force replace the template? Yes (y), No (n)"); String answer = scanner.nextLine(); if (!answer.equalsIgnoreCase("y")) { System.out.println("Publish canceled."); return; } } System.out.println("Publishing template..."); HttpURLConnection httpURLConnection = getCommonConnection(BASE_URL + REMOTE_CONFIG_ENDPOINT); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); httpURLConnection.setRequestProperty("If-Match", etag); httpURLConnection.setRequestProperty("Content-Encoding", "gzip"); String configStr = readConfig(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(httpURLConnection.getOutputStream()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gzipOutputStream); outputStreamWriter.write(configStr); outputStreamWriter.flush(); outputStreamWriter.close(); int code = httpURLConnection.getResponseCode(); if (code == 200) { System.out.println("Template has been published."); } else { System.out.println(inputstreamToString(httpURLConnection.getErrorStream())); } } /** * Read the Firebase Remote Config template from config.json file. * * @return String with contents of config.json file. * @throws FileNotFoundException */ private static String readConfig() throws FileNotFoundException { File file = new File("config.json"); Scanner scanner = new Scanner(file); StringBuilder stringBuilder = new StringBuilder(); while (scanner.hasNext()) { stringBuilder.append(scanner.nextLine()); } return stringBuilder.toString(); } /** * Format content from an InputStream as pretty JSON. * * @param inputStream Content to be formatted. * @return Pretty JSON formatted string. * * @throws IOException */ private static String inputstreamToPrettyString(InputStream inputStream) throws IOException { String response = inputstreamToString(inputStream); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(response); Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); String jsonStr = gson.toJson(jsonElement); return jsonStr; } /** * Read contents of InputStream into String. * * @param inputStream InputStream to read. * @return String containing contents of InputStream. * @throws IOException */ private static String inputstreamToString(InputStream inputStream) throws IOException { StringBuilder stringBuilder = new StringBuilder(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { stringBuilder.append(scanner.nextLine()); } return stringBuilder.toString(); } /** * Create HttpURLConnection that can be used for both retrieving and publishing. * * @return Base HttpURLConnection. * @throws IOException */ private static HttpURLConnection getCommonConnection(String endpoint) throws IOException { URL url = new URL(endpoint); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken()); httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8"); return httpURLConnection; } public static void main(String[] args) throws IOException { if (args.length > 1 && args[0].equals("publish")) { publishTemplate(args[1]); } else if (args.length == 1 && args[0].equals("get")) { getTemplate(); } else if (args.length == 1 && args[0].equals("versions")) { getVersions(); } else if (args.length > 1 && args[0].equals("rollback")) { rollback(Integer.parseInt(args[1])); } else { System.err.println("Invalid request. Please use one of the following commands:"); // To get the current template from the server. System.err.println("./gradlew run -Paction=get"); // To publish the template in config.json to the server. System.err.println("./gradlew run -Paction=publish -Petag='<LATEST_ETAG>'"); // To get the available template versions from the server. System.err.println("./gradlew run -Paction=versions"); // To roll back to a particular version. System.err.println("./gradlew run -Paction=rollback -Pversion=<TEMPLATE_VERSION_NUMBER>"); } } }
[ "public", "class", "Configure", "{", "private", "final", "static", "String", "PROJECT_ID", "=", "\"", "PROJECT_ID", "\"", ";", "private", "final", "static", "String", "BASE_URL", "=", "\"", "https://firebaseremoteconfig.googleapis.com", "\"", ";", "private", "final", "static", "String", "REMOTE_CONFIG_ENDPOINT", "=", "\"", "/v1/projects/", "\"", "+", "PROJECT_ID", "+", "\"", "/remoteConfig", "\"", ";", "private", "final", "static", "String", "[", "]", "SCOPES", "=", "{", "\"", "https://www.googleapis.com/auth/firebase.remoteconfig", "\"", "}", ";", "/**\n * Retrieve a valid access token that can be use to authorize requests to the Remote Config REST\n * API.\n *\n * @return Access token.\n * @throws IOException\n */", "private", "static", "String", "getAccessToken", "(", ")", "throws", "IOException", "{", "GoogleCredential", "googleCredential", "=", "GoogleCredential", ".", "fromStream", "(", "new", "FileInputStream", "(", "\"", "service-account.json", "\"", ")", ")", ".", "createScoped", "(", "Arrays", ".", "asList", "(", "SCOPES", ")", ")", ";", "googleCredential", ".", "refreshToken", "(", ")", ";", "return", "googleCredential", ".", "getAccessToken", "(", ")", ";", "}", "/**\n * Get current Firebase Remote Config template from server and store it locally.\n *\n * @throws IOException\n */", "private", "static", "void", "getTemplate", "(", ")", "throws", "IOException", "{", "HttpURLConnection", "httpURLConnection", "=", "getCommonConnection", "(", "BASE_URL", "+", "REMOTE_CONFIG_ENDPOINT", ")", ";", "httpURLConnection", ".", "setRequestMethod", "(", "\"", "GET", "\"", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "Accept-Encoding", "\"", ",", "\"", "gzip", "\"", ")", ";", "int", "code", "=", "httpURLConnection", ".", "getResponseCode", "(", ")", ";", "if", "(", "code", "==", "200", ")", "{", "InputStream", "inputStream", "=", "new", "GZIPInputStream", "(", "httpURLConnection", ".", "getInputStream", "(", ")", ")", ";", "String", "response", "=", "inputstreamToString", "(", "inputStream", ")", ";", "JsonParser", "jsonParser", "=", "new", "JsonParser", "(", ")", ";", "JsonElement", "jsonElement", "=", "jsonParser", ".", "parse", "(", "response", ")", ";", "Gson", "gson", "=", "new", "GsonBuilder", "(", ")", ".", "setPrettyPrinting", "(", ")", ".", "disableHtmlEscaping", "(", ")", ".", "create", "(", ")", ";", "String", "jsonStr", "=", "gson", ".", "toJson", "(", "jsonElement", ")", ";", "File", "file", "=", "new", "File", "(", "\"", "config.json", "\"", ")", ";", "PrintWriter", "printWriter", "=", "new", "PrintWriter", "(", "new", "FileWriter", "(", "file", ")", ")", ";", "printWriter", ".", "print", "(", "jsonStr", ")", ";", "printWriter", ".", "flush", "(", ")", ";", "printWriter", ".", "close", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Template retrieved and has been written to config.json", "\"", ")", ";", "String", "etag", "=", "httpURLConnection", ".", "getHeaderField", "(", "\"", "ETag", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "ETag from server: ", "\"", "+", "etag", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "inputstreamToString", "(", "httpURLConnection", ".", "getErrorStream", "(", ")", ")", ")", ";", "}", "}", "/**\n * Print the last 5 available Firebase Remote Config template metadata from the server.\n *\n * @throws IOException\n */", "private", "static", "void", "getVersions", "(", ")", "throws", "IOException", "{", "HttpURLConnection", "httpURLConnection", "=", "getCommonConnection", "(", "BASE_URL", "+", "REMOTE_CONFIG_ENDPOINT", "+", "\"", ":listVersions?pageSize=5", "\"", ")", ";", "httpURLConnection", ".", "setRequestMethod", "(", "\"", "GET", "\"", ")", ";", "int", "code", "=", "httpURLConnection", ".", "getResponseCode", "(", ")", ";", "if", "(", "code", "==", "200", ")", "{", "String", "versions", "=", "inputstreamToPrettyString", "(", "httpURLConnection", ".", "getInputStream", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Versions:", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "versions", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "inputstreamToString", "(", "httpURLConnection", ".", "getErrorStream", "(", ")", ")", ")", ";", "}", "}", "/**\n * Roll back to an available version of Firebase Remote Config template.\n *\n * @param version The version to roll back to.\n *\n * @throws IOException\n */", "private", "static", "void", "rollback", "(", "int", "version", ")", "throws", "IOException", "{", "HttpURLConnection", "httpURLConnection", "=", "getCommonConnection", "(", "BASE_URL", "+", "REMOTE_CONFIG_ENDPOINT", "+", "\"", ":rollback", "\"", ")", ";", "httpURLConnection", ".", "setDoOutput", "(", "true", ")", ";", "httpURLConnection", ".", "setRequestMethod", "(", "\"", "POST", "\"", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "Accept-Encoding", "\"", ",", "\"", "gzip", "\"", ")", ";", "JsonObject", "jsonObject", "=", "new", "JsonObject", "(", ")", ";", "jsonObject", ".", "addProperty", "(", "\"", "version_number", "\"", ",", "version", ")", ";", "OutputStreamWriter", "outputStreamWriter", "=", "new", "OutputStreamWriter", "(", "httpURLConnection", ".", "getOutputStream", "(", ")", ")", ";", "outputStreamWriter", ".", "write", "(", "jsonObject", ".", "toString", "(", ")", ")", ";", "outputStreamWriter", ".", "flush", "(", ")", ";", "outputStreamWriter", ".", "close", "(", ")", ";", "int", "code", "=", "httpURLConnection", ".", "getResponseCode", "(", ")", ";", "if", "(", "code", "==", "200", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Rolled back to: ", "\"", "+", "version", ")", ";", "InputStream", "inputStream", "=", "new", "GZIPInputStream", "(", "httpURLConnection", ".", "getInputStream", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "inputstreamToPrettyString", "(", "inputStream", ")", ")", ";", "String", "etag", "=", "httpURLConnection", ".", "getHeaderField", "(", "\"", "ETag", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "ETag from server: ", "\"", "+", "etag", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "Error:", "\"", ")", ";", "InputStream", "inputStream", "=", "new", "GZIPInputStream", "(", "httpURLConnection", ".", "getErrorStream", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "inputstreamToString", "(", "inputStream", ")", ")", ";", "}", "}", "/**\n * Publish local template to Firebase server.\n *\n * @throws IOException\n */", "private", "static", "void", "publishTemplate", "(", "String", "etag", ")", "throws", "IOException", "{", "if", "(", "etag", ".", "equals", "(", "\"", "*", "\"", ")", ")", "{", "Scanner", "scanner", "=", "new", "Scanner", "(", "System", ".", "in", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Are you sure you would like to force replace the template? Yes (y), No (n)", "\"", ")", ";", "String", "answer", "=", "scanner", ".", "nextLine", "(", ")", ";", "if", "(", "!", "answer", ".", "equalsIgnoreCase", "(", "\"", "y", "\"", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Publish canceled.", "\"", ")", ";", "return", ";", "}", "}", "System", ".", "out", ".", "println", "(", "\"", "Publishing template...", "\"", ")", ";", "HttpURLConnection", "httpURLConnection", "=", "getCommonConnection", "(", "BASE_URL", "+", "REMOTE_CONFIG_ENDPOINT", ")", ";", "httpURLConnection", ".", "setDoOutput", "(", "true", ")", ";", "httpURLConnection", ".", "setRequestMethod", "(", "\"", "PUT", "\"", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "If-Match", "\"", ",", "etag", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "Content-Encoding", "\"", ",", "\"", "gzip", "\"", ")", ";", "String", "configStr", "=", "readConfig", "(", ")", ";", "GZIPOutputStream", "gzipOutputStream", "=", "new", "GZIPOutputStream", "(", "httpURLConnection", ".", "getOutputStream", "(", ")", ")", ";", "OutputStreamWriter", "outputStreamWriter", "=", "new", "OutputStreamWriter", "(", "gzipOutputStream", ")", ";", "outputStreamWriter", ".", "write", "(", "configStr", ")", ";", "outputStreamWriter", ".", "flush", "(", ")", ";", "outputStreamWriter", ".", "close", "(", ")", ";", "int", "code", "=", "httpURLConnection", ".", "getResponseCode", "(", ")", ";", "if", "(", "code", "==", "200", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Template has been published.", "\"", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "inputstreamToString", "(", "httpURLConnection", ".", "getErrorStream", "(", ")", ")", ")", ";", "}", "}", "/**\n * Read the Firebase Remote Config template from config.json file.\n *\n * @return String with contents of config.json file.\n * @throws FileNotFoundException\n */", "private", "static", "String", "readConfig", "(", ")", "throws", "FileNotFoundException", "{", "File", "file", "=", "new", "File", "(", "\"", "config.json", "\"", ")", ";", "Scanner", "scanner", "=", "new", "Scanner", "(", "file", ")", ";", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "while", "(", "scanner", ".", "hasNext", "(", ")", ")", "{", "stringBuilder", ".", "append", "(", "scanner", ".", "nextLine", "(", ")", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}", "/**\n * Format content from an InputStream as pretty JSON.\n *\n * @param inputStream Content to be formatted.\n * @return Pretty JSON formatted string.\n *\n * @throws IOException\n */", "private", "static", "String", "inputstreamToPrettyString", "(", "InputStream", "inputStream", ")", "throws", "IOException", "{", "String", "response", "=", "inputstreamToString", "(", "inputStream", ")", ";", "JsonParser", "jsonParser", "=", "new", "JsonParser", "(", ")", ";", "JsonElement", "jsonElement", "=", "jsonParser", ".", "parse", "(", "response", ")", ";", "Gson", "gson", "=", "new", "GsonBuilder", "(", ")", ".", "setPrettyPrinting", "(", ")", ".", "disableHtmlEscaping", "(", ")", ".", "create", "(", ")", ";", "String", "jsonStr", "=", "gson", ".", "toJson", "(", "jsonElement", ")", ";", "return", "jsonStr", ";", "}", "/**\n * Read contents of InputStream into String.\n *\n * @param inputStream InputStream to read.\n * @return String containing contents of InputStream.\n * @throws IOException\n */", "private", "static", "String", "inputstreamToString", "(", "InputStream", "inputStream", ")", "throws", "IOException", "{", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "Scanner", "scanner", "=", "new", "Scanner", "(", "inputStream", ")", ";", "while", "(", "scanner", ".", "hasNext", "(", ")", ")", "{", "stringBuilder", ".", "append", "(", "scanner", ".", "nextLine", "(", ")", ")", ";", "}", "return", "stringBuilder", ".", "toString", "(", ")", ";", "}", "/**\n * Create HttpURLConnection that can be used for both retrieving and publishing.\n *\n * @return Base HttpURLConnection.\n * @throws IOException\n */", "private", "static", "HttpURLConnection", "getCommonConnection", "(", "String", "endpoint", ")", "throws", "IOException", "{", "URL", "url", "=", "new", "URL", "(", "endpoint", ")", ";", "HttpURLConnection", "httpURLConnection", "=", "(", "HttpURLConnection", ")", "url", ".", "openConnection", "(", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "Authorization", "\"", ",", "\"", "Bearer ", "\"", "+", "getAccessToken", "(", ")", ")", ";", "httpURLConnection", ".", "setRequestProperty", "(", "\"", "Content-Type", "\"", ",", "\"", "application/json; UTF-8", "\"", ")", ";", "return", "httpURLConnection", ";", "}", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", "{", "if", "(", "args", ".", "length", ">", "1", "&&", "args", "[", "0", "]", ".", "equals", "(", "\"", "publish", "\"", ")", ")", "{", "publishTemplate", "(", "args", "[", "1", "]", ")", ";", "}", "else", "if", "(", "args", ".", "length", "==", "1", "&&", "args", "[", "0", "]", ".", "equals", "(", "\"", "get", "\"", ")", ")", "{", "getTemplate", "(", ")", ";", "}", "else", "if", "(", "args", ".", "length", "==", "1", "&&", "args", "[", "0", "]", ".", "equals", "(", "\"", "versions", "\"", ")", ")", "{", "getVersions", "(", ")", ";", "}", "else", "if", "(", "args", ".", "length", ">", "1", "&&", "args", "[", "0", "]", ".", "equals", "(", "\"", "rollback", "\"", ")", ")", "{", "rollback", "(", "Integer", ".", "parseInt", "(", "args", "[", "1", "]", ")", ")", ";", "}", "else", "{", "System", ".", "err", ".", "println", "(", "\"", "Invalid request. Please use one of the following commands:", "\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"", "./gradlew run -Paction=get", "\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"", "./gradlew run -Paction=publish -Petag='<LATEST_ETAG>'", "\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"", "./gradlew run -Paction=versions", "\"", ")", ";", "System", ".", "err", ".", "println", "(", "\"", "./gradlew run -Paction=rollback -Pversion=<TEMPLATE_VERSION_NUMBER>", "\"", ")", ";", "}", "}", "}" ]
Retrieve and publish templates for Firebase Remote Config using the REST API.
[ "Retrieve", "and", "publish", "templates", "for", "Firebase", "Remote", "Config", "using", "the", "REST", "API", "." ]
[ "// [START retrieve_access_token]", "// [END retrieve_access_token]", "// Print ETag", "// Print ETag", "// To get the current template from the server.", "// To publish the template in config.json to the server.", "// To get the available template versions from the server.", "// To roll back to a particular version." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe79ef4b6047c370a224f97783e9015dc00a0b41
moonlight83340/PearEmu-2.0
Pearemu/src/org/pearemu/commons/database/CreatableDAO.java
[ "MIT" ]
Java
CreatableDAO
/** * * @author Vincent Quatrevieux <[email protected]> */
@author Vincent Quatrevieux
[ "@author", "Vincent", "Quatrevieux" ]
abstract public class CreatableDAO<T extends Model> extends FindableDAO<T> { final protected PreparedStatement deleteStatement = Database.prepare("SELECT * FROM " + tableName() + " WHERE " + primaryKey() + " = ?"); abstract public boolean create(T obj); public boolean delete(int pk) { try { if (primaryKey().isEmpty()) { return false; } synchronized (deleteStatement) { deleteStatement.setInt(1, pk); return deleteStatement.execute(); } } catch (SQLException e) { return false; } } public boolean delete(T obj) { if (delete(obj.getPk())) { obj.clear(); return true; } else { return false; } } }
[ "abstract", "public", "class", "CreatableDAO", "<", "T", "extends", "Model", ">", "extends", "FindableDAO", "<", "T", ">", "{", "final", "protected", "PreparedStatement", "deleteStatement", "=", "Database", ".", "prepare", "(", "\"", "SELECT * FROM ", "\"", "+", "tableName", "(", ")", "+", "\"", " WHERE ", "\"", "+", "primaryKey", "(", ")", "+", "\"", " = ?", "\"", ")", ";", "abstract", "public", "boolean", "create", "(", "T", "obj", ")", ";", "public", "boolean", "delete", "(", "int", "pk", ")", "{", "try", "{", "if", "(", "primaryKey", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "synchronized", "(", "deleteStatement", ")", "{", "deleteStatement", ".", "setInt", "(", "1", ",", "pk", ")", ";", "return", "deleteStatement", ".", "execute", "(", ")", ";", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "return", "false", ";", "}", "}", "public", "boolean", "delete", "(", "T", "obj", ")", "{", "if", "(", "delete", "(", "obj", ".", "getPk", "(", ")", ")", ")", "{", "obj", ".", "clear", "(", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}" ]
@author Vincent Quatrevieux <[email protected]>
[ "@author", "Vincent", "Quatrevieux", "<quatrevieux", ".", "vincent@gmail", ".", "com", ">" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe7a4dc6b879064e1f84c59fac48721e4042b8cd
karensmolermiller/incubator-geode
gemfire-core/src/test/java/com/examples/TestObject.java
[ "Apache-2.0" ]
Java
TestObject
/** * A simple test object used by the {@link * com.gemstone.gemfire.internal.enhancer.serializer.SerializingStreamPerfTest} * that must be in a non-<code>com.gemstone</code> package. * * @author David Whitlock * * @since 3.5 */
A simple test object used by the {@link com.gemstone.gemfire.internal.enhancer.serializer.SerializingStreamPerfTest} * that must be in a non-com.gemstone package. @author David Whitlock
[ "A", "simple", "test", "object", "used", "by", "the", "{", "@link", "com", ".", "gemstone", ".", "gemfire", ".", "internal", ".", "enhancer", ".", "serializer", ".", "SerializingStreamPerfTest", "}", "*", "that", "must", "be", "in", "a", "non", "-", "com", ".", "gemstone", "package", ".", "@author", "David", "Whitlock" ]
public class TestObject { private int intField; private String stringField; private Object objectField; /** * Creates a new <code>TestObject</code> */ public TestObject() { this.intField = 42; this.stringField = "123456789012345678901234567890"; this.objectField = new Integer(67); } ////////////////////// Inner Classes ////////////////////// /** * A <code>Serializable</code> object that is serialized */ public static class SerializableTestObject extends TestObject implements java.io.Serializable { } }
[ "public", "class", "TestObject", "{", "private", "int", "intField", ";", "private", "String", "stringField", ";", "private", "Object", "objectField", ";", "/**\n * Creates a new <code>TestObject</code>\n */", "public", "TestObject", "(", ")", "{", "this", ".", "intField", "=", "42", ";", "this", ".", "stringField", "=", "\"", "123456789012345678901234567890", "\"", ";", "this", ".", "objectField", "=", "new", "Integer", "(", "67", ")", ";", "}", "/**\n * A <code>Serializable</code> object that is serialized\n */", "public", "static", "class", "SerializableTestObject", "extends", "TestObject", "implements", "java", ".", "io", ".", "Serializable", "{", "}", "}" ]
A simple test object used by the {@link com.gemstone.gemfire.internal.enhancer.serializer.SerializingStreamPerfTest} * that must be in a non-<code>com.gemstone</code> package.
[ "A", "simple", "test", "object", "used", "by", "the", "{", "@link", "com", ".", "gemstone", ".", "gemfire", ".", "internal", ".", "enhancer", ".", "serializer", ".", "SerializingStreamPerfTest", "}", "*", "that", "must", "be", "in", "a", "non", "-", "<code", ">", "com", ".", "gemstone<", "/", "code", ">", "package", "." ]
[ "////////////////////// Inner Classes //////////////////////" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe7a96d2e95851798193faa98f138c1022352d25
fujion/fujion-framework
fujion-core/src/main/java/org/fujion/dialog/ReportDialog.java
[ "Apache-2.0" ]
Java
ReportDialog
/** * A simple dialog for displaying text information modally or amodally. */
A simple dialog for displaying text information modally or amodally.
[ "A", "simple", "dialog", "for", "displaying", "text", "information", "modally", "or", "amodally", "." ]
public class ReportDialog implements IAutoWired { private Window window; @WiredComponent private Cell cmpText; @WiredComponent private Html cmpHtml; @WiredComponent private Button btnPrint; @WiredComponent private BaseUIComponent printRoot; /** * Displays the dialog. * * @param text The text or HTML content. HTML content is indicated by prefixing with the html * tag. * @param title Dialog title. * @param allowPrint If true, a print button is provided. * @param asModal If true, open as modal; otherwise, as popup. * @param callback Callback when dialog is closed. * @return The created dialog. */ public static Window show( String text, String title, boolean allowPrint, boolean asModal, IEventListener callback) { Map<String, Object> args = new HashMap<>(); args.put("text", text); args.put("title", title); args.put("allowPrint", allowPrint); Window dialog = org.fujion.dialog.PopupDialog.show(RESOURCE_PREFIX + "reportDialog.fsp", args, true, true, false, null); if (asModal) { dialog.modal(callback); } else { dialog.popup(callback); } return dialog; } @Override public void afterInitialized(BaseComponent root) { window = (Window) root; window.setTitle(root.getAttribute("title", "")); btnPrint.setVisible(root.getAttribute("allowPrint", false)); String text = root.getAttribute("text", ""); if (text.startsWith("<html>")) { cmpHtml.setContent(text); } else { cmpText.setLabel(text); } } @EventHandler(value = "click", target = "btnClose") private void btnClose$click() { window.close(); } @EventHandler(value = "click", target = "@btnPrint") private void btnPrint$click() { PrintOptions options = new PrintOptions(); options.title = window.getTitle(); printRoot.print(options); } }
[ "public", "class", "ReportDialog", "implements", "IAutoWired", "{", "private", "Window", "window", ";", "@", "WiredComponent", "private", "Cell", "cmpText", ";", "@", "WiredComponent", "private", "Html", "cmpHtml", ";", "@", "WiredComponent", "private", "Button", "btnPrint", ";", "@", "WiredComponent", "private", "BaseUIComponent", "printRoot", ";", "/**\n * Displays the dialog.\n *\n * @param text The text or HTML content. HTML content is indicated by prefixing with the html\n * tag.\n * @param title Dialog title.\n * @param allowPrint If true, a print button is provided.\n * @param asModal If true, open as modal; otherwise, as popup.\n * @param callback Callback when dialog is closed.\n * @return The created dialog.\n */", "public", "static", "Window", "show", "(", "String", "text", ",", "String", "title", ",", "boolean", "allowPrint", ",", "boolean", "asModal", ",", "IEventListener", "callback", ")", "{", "Map", "<", "String", ",", "Object", ">", "args", "=", "new", "HashMap", "<", ">", "(", ")", ";", "args", ".", "put", "(", "\"", "text", "\"", ",", "text", ")", ";", "args", ".", "put", "(", "\"", "title", "\"", ",", "title", ")", ";", "args", ".", "put", "(", "\"", "allowPrint", "\"", ",", "allowPrint", ")", ";", "Window", "dialog", "=", "org", ".", "fujion", ".", "dialog", ".", "PopupDialog", ".", "show", "(", "RESOURCE_PREFIX", "+", "\"", "reportDialog.fsp", "\"", ",", "args", ",", "true", ",", "true", ",", "false", ",", "null", ")", ";", "if", "(", "asModal", ")", "{", "dialog", ".", "modal", "(", "callback", ")", ";", "}", "else", "{", "dialog", ".", "popup", "(", "callback", ")", ";", "}", "return", "dialog", ";", "}", "@", "Override", "public", "void", "afterInitialized", "(", "BaseComponent", "root", ")", "{", "window", "=", "(", "Window", ")", "root", ";", "window", ".", "setTitle", "(", "root", ".", "getAttribute", "(", "\"", "title", "\"", ",", "\"", "\"", ")", ")", ";", "btnPrint", ".", "setVisible", "(", "root", ".", "getAttribute", "(", "\"", "allowPrint", "\"", ",", "false", ")", ")", ";", "String", "text", "=", "root", ".", "getAttribute", "(", "\"", "text", "\"", ",", "\"", "\"", ")", ";", "if", "(", "text", ".", "startsWith", "(", "\"", "<html>", "\"", ")", ")", "{", "cmpHtml", ".", "setContent", "(", "text", ")", ";", "}", "else", "{", "cmpText", ".", "setLabel", "(", "text", ")", ";", "}", "}", "@", "EventHandler", "(", "value", "=", "\"", "click", "\"", ",", "target", "=", "\"", "btnClose", "\"", ")", "private", "void", "btnClose$click", "(", ")", "{", "window", ".", "close", "(", ")", ";", "}", "@", "EventHandler", "(", "value", "=", "\"", "click", "\"", ",", "target", "=", "\"", "@btnPrint", "\"", ")", "private", "void", "btnPrint$click", "(", ")", "{", "PrintOptions", "options", "=", "new", "PrintOptions", "(", ")", ";", "options", ".", "title", "=", "window", ".", "getTitle", "(", ")", ";", "printRoot", ".", "print", "(", "options", ")", ";", "}", "}" ]
A simple dialog for displaying text information modally or amodally.
[ "A", "simple", "dialog", "for", "displaying", "text", "information", "modally", "or", "amodally", "." ]
[]
[ { "param": "IAutoWired", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IAutoWired", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe7b7880ec8fcef0d3b53be26b4f16238b86dae7
kamaci/manifoldcf
connectors/jcifs/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/sharedrive/SharedDriveParameters.java
[ "Apache-2.0" ]
Java
SharedDriveParameters
/** This class describes shared drive connection parameters. */
This class describes shared drive connection parameters.
[ "This", "class", "describes", "shared", "drive", "connection", "parameters", "." ]
public class SharedDriveParameters { public static final String _rcsid = "@(#)$Id: SharedDriveParameters.java 988245 2010-08-23 18:39:35Z kwright $"; /* SMB/CIFS share server */ public final static String server = "Server"; /* Optional domain/realm */ public final static String domain = "Domain/Realm"; /* username for the above server */ public final static String username = "User Name"; /* password for the above server */ public final static String password = "Password"; /* SIDs handling */ public final static String useSIDs = "Use SIDs"; /* User-settable bin name */ public final static String binName = "Bin Name"; }
[ "public", "class", "SharedDriveParameters", "{", "public", "static", "final", "String", "_rcsid", "=", "\"", "@(#)$Id: SharedDriveParameters.java 988245 2010-08-23 18:39:35Z kwright $", "\"", ";", "/* SMB/CIFS share server */", "public", "final", "static", "String", "server", "=", "\"", "Server", "\"", ";", "/* Optional domain/realm */", "public", "final", "static", "String", "domain", "=", "\"", "Domain/Realm", "\"", ";", "/* username for the above server */", "public", "final", "static", "String", "username", "=", "\"", "User Name", "\"", ";", "/* password for the above server */", "public", "final", "static", "String", "password", "=", "\"", "Password", "\"", ";", "/* SIDs handling */", "public", "final", "static", "String", "useSIDs", "=", "\"", "Use SIDs", "\"", ";", "/* User-settable bin name */", "public", "final", "static", "String", "binName", "=", "\"", "Bin Name", "\"", ";", "}" ]
This class describes shared drive connection parameters.
[ "This", "class", "describes", "shared", "drive", "connection", "parameters", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
fe7cbdfa37d89249e73b0d65934a677ab78e040d
arusinha/incubator-netbeans
platform/core.ui/src/org/netbeans/core/ui/warmup/MenuWarmUpTask.java
[ "Apache-2.0" ]
Java
MenuWarmUpTask
/** * A menu preheating task. It is referenced from the layer and may be performed * by the core after the startup. * * Plus hooked WindowListener on main window (see {@link NbWindowsAdapter}) */
A menu preheating task. It is referenced from the layer and may be performed by the core after the startup. Plus hooked WindowListener on main window
[ "A", "menu", "preheating", "task", ".", "It", "is", "referenced", "from", "the", "layer", "and", "may", "be", "performed", "by", "the", "core", "after", "the", "startup", ".", "Plus", "hooked", "WindowListener", "on", "main", "window" ]
@ServiceProvider(service=Runnable.class, path="WarmUp") public final class MenuWarmUpTask implements Runnable { private Component[] comps; /** Actually performs pre-heat. */ @Override public void run() { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { Frame main = WindowManager.getDefault().getMainWindow(); assert main != null; main.addWindowListener(new NbWindowsAdapter()); if (main instanceof JFrame) { comps = ((JFrame) main).getJMenuBar().getComponents(); } } }); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return; } catch (Exception e) { // bail out! return; } if (comps != null) { walkMenu(comps); comps = null; } // tackle the Tools menu now? How? } private void walkMenu(Component[] items) { for (int i=0; i<items.length; i++) { if (! (items[i] instanceof JMenu)) continue; try { Class<?> cls = items[i].getClass(); Method m = cls.getDeclaredMethod("doInitialize"); m.setAccessible(true); m.invoke(items[i]); walkMenu(((JMenu)items[i]).getMenuComponents()); // recursive? } catch (Exception e) {// do nothing, it may happen for user-provided menus } } } /** * After activation of window is refreshed filesystem but only if switching * from an external application. */ private static class NbWindowsAdapter extends WindowAdapter implements Runnable, Cancellable { private static final RequestProcessor rp = new RequestProcessor ("Refresh-After-WindowActivated", 1, true);//NOI18N private RequestProcessor.Task task; private AtomicBoolean goOn; private static final Logger UILOG = Logger.getLogger("org.netbeans.ui.focus"); // NOI18N private static final Logger LOG = Logger.getLogger("org.netbeans.core.ui.focus"); // NOI18N private boolean warnedNoRefresh; @Override public void windowActivated(WindowEvent e) { // proceed only if switching from external application if (e.getOppositeWindow() == null) { synchronized (rp) { if (task != null) { LOG.fine("Scheduling task after activation"); task.schedule(1500); task = null; } else { LOG.fine("Activation without prepared refresh task"); } } } } @Override public void windowDeactivated(WindowEvent e) { // proceed only if switching to external application if (e.getOppositeWindow() == null) { synchronized (rp) { if (task != null) { task.cancel(); } else { task = rp.create(this); } LOG.fine("Window deactivated, preparing refresh task"); } if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_DEACTIVATED"); // NOI18N r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } } } private static boolean isNoRefresh() { if (Boolean.getBoolean("netbeans.indexing.noFileRefresh")) { return true; } return NbPreferences.root().node("org/openide/actions/FileSystemRefreshAction").getBoolean("manual", false); // NOI18N } @Messages({ "MSG_Refresh=Checking for external changes", "# default delay is 10s. Increase to Integer.MAX_VALUE to effectively disable", "#NOI18N", "MSG_RefreshDelay=10000", "MSG_Refresh_Suspend=Suspended" }) @Override public void run() { if (isNoRefresh()) { if (!warnedNoRefresh) { LOG.info("External Changes Refresh on focus gain disabled"); // NOI18N warnedNoRefresh = true; } LOG.fine("Refresh disabled, aborting"); return; // no file refresh } final ProgressHandle h = ProgressHandleFactory.createHandle(MSG_Refresh(), this, null); if (!LOG.isLoggable(Level.FINE)) { int delay = Integer.parseInt(MSG_RefreshDelay()); h.setInitialDelay(delay); } h.start(); Runnable run = null; class HandleBridge extends ActionEvent implements Runnable { private FileObject previous; private long next; public HandleBridge(Object source) { super (source, 0, ""); } @Override public void setSource(Object newSource) { if (newSource instanceof Object[]) { long now = System.currentTimeMillis(); boolean again = now > next; Object[] arr = (Object[])newSource; if (arr.length >= 3 && arr[0] instanceof Integer && arr[1] instanceof Integer && arr[2] instanceof FileObject ) { if (! (getSource() instanceof Object[])) { h.switchToDeterminate((Integer)arr[1]); LOG.log(Level.FINE, "First refresh progress event delivered: {0}/{1} where {2}, goOn: {3}", arr); } if ((Integer)arr[0] < (Integer)arr[1]) { h.progress((Integer)arr[0]); } FileObject fo = (FileObject)arr[2]; if (previous != fo.getParent() && again) { previous = fo.getParent(); if (previous != null) { h.progress(previous.getPath()); } next = now + 500; } super.setSource(newSource); } if (arr.length >= 4 && arr[3] instanceof AtomicBoolean) { goOn = (AtomicBoolean)arr[3]; } if (arr.length >= 5 && arr[4] == null && again) { arr[4] = Utilities.actionsGlobalContext().lookup(FileObject.class); LOG.log(Level.FINE, "Preferring {0}", arr[4]); } } } @Override public void run() { if (EventQueue.isDispatchThread()) { try { h.suspend(MSG_Refresh_Suspend()); } catch (Throwable t) { // ignore any errors } } else { EventQueue.invokeLater(this); } } } HandleBridge handleBridge = new HandleBridge(this); // preinitialize handleBridge.run(); try { FileObject udFo = FileUtil.toFileObject(Places.getUserDirectory()); if (udFo != null) { udFo = udFo.getFileSystem().getRoot(); } if (udFo != null) { run = (Runnable)udFo.getAttribute("refreshSlow"); // NOI18N } } catch (Exception ex) { LOG.log(Level.FINE, "Error getting refreshSlow", ex); // NOI18N } long now = System.currentTimeMillis(); try { if (run == null) { LOG.fine("Starting classical refresh"); FileUtil.refreshAll(); } else { // connect the bridge with the masterfs's RefreshSlow if (run instanceof AtomicBoolean) { goOn = (AtomicBoolean) run; LOG.fine("goOn controller registered"); } LOG.fine("Starting slow refresh"); run.equals(handleBridge); run.run(); } long took = System.currentTimeMillis() - now; if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_ACTIVATED"); // NOI18N r.setParameters(new Object[] { took }); r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } LOG.log(Level.FINE, "Refresh done in {0} ms", took); AtomicBoolean ab = goOn; if (ab == null || ab.get()) { long sfs = System.currentTimeMillis(); FileUtil.getConfigRoot().getFileSystem().refresh(true); LOG.log(Level.FINE, "SystemFileSystem refresh done {0} ms", (System.currentTimeMillis() - sfs)); } else { LOG.fine("Skipping SystemFileSystem refresh"); } } catch (FileStateInvalidException ex) { Exceptions.printStackTrace(ex); } finally { h.finish(); } } private int counter; @Override public boolean cancel() { synchronized(rp) { if (task != null) { task.cancel(); } if (goOn != null) { goOn.set(false); LOG.log(Level.FINE, "Signaling cancel to {0}", System.identityHashCode(goOn)); } else { LOG.log(Level.FINE, "Cannot signal cancel, goOn is null"); } } ++counter; if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_REFRESH_CANCEL"); // NOI18N r.setParameters(new Object[]{counter}); r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } return true; } } // end of NbWindowsAdapter }
[ "@", "ServiceProvider", "(", "service", "=", "Runnable", ".", "class", ",", "path", "=", "\"", "WarmUp", "\"", ")", "public", "final", "class", "MenuWarmUpTask", "implements", "Runnable", "{", "private", "Component", "[", "]", "comps", ";", "/** Actually performs pre-heat.\n */", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "SwingUtilities", ".", "invokeAndWait", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "Frame", "main", "=", "WindowManager", ".", "getDefault", "(", ")", ".", "getMainWindow", "(", ")", ";", "assert", "main", "!=", "null", ";", "main", ".", "addWindowListener", "(", "new", "NbWindowsAdapter", "(", ")", ")", ";", "if", "(", "main", "instanceof", "JFrame", ")", "{", "comps", "=", "(", "(", "JFrame", ")", "main", ")", ".", "getJMenuBar", "(", ")", ".", "getComponents", "(", ")", ";", "}", "}", "}", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "return", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", ";", "}", "if", "(", "comps", "!=", "null", ")", "{", "walkMenu", "(", "comps", ")", ";", "comps", "=", "null", ";", "}", "}", "private", "void", "walkMenu", "(", "Component", "[", "]", "items", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "(", "items", "[", "i", "]", "instanceof", "JMenu", ")", ")", "continue", ";", "try", "{", "Class", "<", "?", ">", "cls", "=", "items", "[", "i", "]", ".", "getClass", "(", ")", ";", "Method", "m", "=", "cls", ".", "getDeclaredMethod", "(", "\"", "doInitialize", "\"", ")", ";", "m", ".", "setAccessible", "(", "true", ")", ";", "m", ".", "invoke", "(", "items", "[", "i", "]", ")", ";", "walkMenu", "(", "(", "(", "JMenu", ")", "items", "[", "i", "]", ")", ".", "getMenuComponents", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}", "/**\n * After activation of window is refreshed filesystem but only if switching\n * from an external application.\n */", "private", "static", "class", "NbWindowsAdapter", "extends", "WindowAdapter", "implements", "Runnable", ",", "Cancellable", "{", "private", "static", "final", "RequestProcessor", "rp", "=", "new", "RequestProcessor", "(", "\"", "Refresh-After-WindowActivated", "\"", ",", "1", ",", "true", ")", ";", "private", "RequestProcessor", ".", "Task", "task", ";", "private", "AtomicBoolean", "goOn", ";", "private", "static", "final", "Logger", "UILOG", "=", "Logger", ".", "getLogger", "(", "\"", "org.netbeans.ui.focus", "\"", ")", ";", "private", "static", "final", "Logger", "LOG", "=", "Logger", ".", "getLogger", "(", "\"", "org.netbeans.core.ui.focus", "\"", ")", ";", "private", "boolean", "warnedNoRefresh", ";", "@", "Override", "public", "void", "windowActivated", "(", "WindowEvent", "e", ")", "{", "if", "(", "e", ".", "getOppositeWindow", "(", ")", "==", "null", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "LOG", ".", "fine", "(", "\"", "Scheduling task after activation", "\"", ")", ";", "task", ".", "schedule", "(", "1500", ")", ";", "task", "=", "null", ";", "}", "else", "{", "LOG", ".", "fine", "(", "\"", "Activation without prepared refresh task", "\"", ")", ";", "}", "}", "}", "}", "@", "Override", "public", "void", "windowDeactivated", "(", "WindowEvent", "e", ")", "{", "if", "(", "e", ".", "getOppositeWindow", "(", ")", "==", "null", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "task", ".", "cancel", "(", ")", ";", "}", "else", "{", "task", "=", "rp", ".", "create", "(", "this", ")", ";", "}", "LOG", ".", "fine", "(", "\"", "Window deactivated, preparing refresh task", "\"", ")", ";", "}", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_DEACTIVATED", "\"", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "}", "}", "private", "static", "boolean", "isNoRefresh", "(", ")", "{", "if", "(", "Boolean", ".", "getBoolean", "(", "\"", "netbeans.indexing.noFileRefresh", "\"", ")", ")", "{", "return", "true", ";", "}", "return", "NbPreferences", ".", "root", "(", ")", ".", "node", "(", "\"", "org/openide/actions/FileSystemRefreshAction", "\"", ")", ".", "getBoolean", "(", "\"", "manual", "\"", ",", "false", ")", ";", "}", "@", "Messages", "(", "{", "\"", "MSG_Refresh=Checking for external changes", "\"", ",", "\"", "# default delay is 10s. Increase to Integer.MAX_VALUE to effectively disable", "\"", ",", "\"", "#NOI18N", "\"", ",", "\"", "MSG_RefreshDelay=10000", "\"", ",", "\"", "MSG_Refresh_Suspend=Suspended", "\"", "}", ")", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "isNoRefresh", "(", ")", ")", "{", "if", "(", "!", "warnedNoRefresh", ")", "{", "LOG", ".", "info", "(", "\"", "External Changes Refresh on focus gain disabled", "\"", ")", ";", "warnedNoRefresh", "=", "true", ";", "}", "LOG", ".", "fine", "(", "\"", "Refresh disabled, aborting", "\"", ")", ";", "return", ";", "}", "final", "ProgressHandle", "h", "=", "ProgressHandleFactory", ".", "createHandle", "(", "MSG_Refresh", "(", ")", ",", "this", ",", "null", ")", ";", "if", "(", "!", "LOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "int", "delay", "=", "Integer", ".", "parseInt", "(", "MSG_RefreshDelay", "(", ")", ")", ";", "h", ".", "setInitialDelay", "(", "delay", ")", ";", "}", "h", ".", "start", "(", ")", ";", "Runnable", "run", "=", "null", ";", "class", "HandleBridge", "extends", "ActionEvent", "implements", "Runnable", "{", "private", "FileObject", "previous", ";", "private", "long", "next", ";", "public", "HandleBridge", "(", "Object", "source", ")", "{", "super", "(", "source", ",", "0", ",", "\"", "\"", ")", ";", "}", "@", "Override", "public", "void", "setSource", "(", "Object", "newSource", ")", "{", "if", "(", "newSource", "instanceof", "Object", "[", "]", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "again", "=", "now", ">", "next", ";", "Object", "[", "]", "arr", "=", "(", "Object", "[", "]", ")", "newSource", ";", "if", "(", "arr", ".", "length", ">=", "3", "&&", "arr", "[", "0", "]", "instanceof", "Integer", "&&", "arr", "[", "1", "]", "instanceof", "Integer", "&&", "arr", "[", "2", "]", "instanceof", "FileObject", ")", "{", "if", "(", "!", "(", "getSource", "(", ")", "instanceof", "Object", "[", "]", ")", ")", "{", "h", ".", "switchToDeterminate", "(", "(", "Integer", ")", "arr", "[", "1", "]", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "First refresh progress event delivered: {0}/{1} where {2}, goOn: {3}", "\"", ",", "arr", ")", ";", "}", "if", "(", "(", "Integer", ")", "arr", "[", "0", "]", "<", "(", "Integer", ")", "arr", "[", "1", "]", ")", "{", "h", ".", "progress", "(", "(", "Integer", ")", "arr", "[", "0", "]", ")", ";", "}", "FileObject", "fo", "=", "(", "FileObject", ")", "arr", "[", "2", "]", ";", "if", "(", "previous", "!=", "fo", ".", "getParent", "(", ")", "&&", "again", ")", "{", "previous", "=", "fo", ".", "getParent", "(", ")", ";", "if", "(", "previous", "!=", "null", ")", "{", "h", ".", "progress", "(", "previous", ".", "getPath", "(", ")", ")", ";", "}", "next", "=", "now", "+", "500", ";", "}", "super", ".", "setSource", "(", "newSource", ")", ";", "}", "if", "(", "arr", ".", "length", ">=", "4", "&&", "arr", "[", "3", "]", "instanceof", "AtomicBoolean", ")", "{", "goOn", "=", "(", "AtomicBoolean", ")", "arr", "[", "3", "]", ";", "}", "if", "(", "arr", ".", "length", ">=", "5", "&&", "arr", "[", "4", "]", "==", "null", "&&", "again", ")", "{", "arr", "[", "4", "]", "=", "Utilities", ".", "actionsGlobalContext", "(", ")", ".", "lookup", "(", "FileObject", ".", "class", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Preferring {0}", "\"", ",", "arr", "[", "4", "]", ")", ";", "}", "}", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "EventQueue", ".", "isDispatchThread", "(", ")", ")", "{", "try", "{", "h", ".", "suspend", "(", "MSG_Refresh_Suspend", "(", ")", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "}", "}", "else", "{", "EventQueue", ".", "invokeLater", "(", "this", ")", ";", "}", "}", "}", "HandleBridge", "handleBridge", "=", "new", "HandleBridge", "(", "this", ")", ";", "handleBridge", ".", "run", "(", ")", ";", "try", "{", "FileObject", "udFo", "=", "FileUtil", ".", "toFileObject", "(", "Places", ".", "getUserDirectory", "(", ")", ")", ";", "if", "(", "udFo", "!=", "null", ")", "{", "udFo", "=", "udFo", ".", "getFileSystem", "(", ")", ".", "getRoot", "(", ")", ";", "}", "if", "(", "udFo", "!=", "null", ")", "{", "run", "=", "(", "Runnable", ")", "udFo", ".", "getAttribute", "(", "\"", "refreshSlow", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Error getting refreshSlow", "\"", ",", "ex", ")", ";", "}", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "try", "{", "if", "(", "run", "==", "null", ")", "{", "LOG", ".", "fine", "(", "\"", "Starting classical refresh", "\"", ")", ";", "FileUtil", ".", "refreshAll", "(", ")", ";", "}", "else", "{", "if", "(", "run", "instanceof", "AtomicBoolean", ")", "{", "goOn", "=", "(", "AtomicBoolean", ")", "run", ";", "LOG", ".", "fine", "(", "\"", "goOn controller registered", "\"", ")", ";", "}", "LOG", ".", "fine", "(", "\"", "Starting slow refresh", "\"", ")", ";", "run", ".", "equals", "(", "handleBridge", ")", ";", "run", ".", "run", "(", ")", ";", "}", "long", "took", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "now", ";", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_ACTIVATED", "\"", ")", ";", "r", ".", "setParameters", "(", "new", "Object", "[", "]", "{", "took", "}", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Refresh done in {0} ms", "\"", ",", "took", ")", ";", "AtomicBoolean", "ab", "=", "goOn", ";", "if", "(", "ab", "==", "null", "||", "ab", ".", "get", "(", ")", ")", "{", "long", "sfs", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "FileUtil", ".", "getConfigRoot", "(", ")", ".", "getFileSystem", "(", ")", ".", "refresh", "(", "true", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "SystemFileSystem refresh done {0} ms", "\"", ",", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "sfs", ")", ")", ";", "}", "else", "{", "LOG", ".", "fine", "(", "\"", "Skipping SystemFileSystem refresh", "\"", ")", ";", "}", "}", "catch", "(", "FileStateInvalidException", "ex", ")", "{", "Exceptions", ".", "printStackTrace", "(", "ex", ")", ";", "}", "finally", "{", "h", ".", "finish", "(", ")", ";", "}", "}", "private", "int", "counter", ";", "@", "Override", "public", "boolean", "cancel", "(", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "task", ".", "cancel", "(", ")", ";", "}", "if", "(", "goOn", "!=", "null", ")", "{", "goOn", ".", "set", "(", "false", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Signaling cancel to {0}", "\"", ",", "System", ".", "identityHashCode", "(", "goOn", ")", ")", ";", "}", "else", "{", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Cannot signal cancel, goOn is null", "\"", ")", ";", "}", "}", "++", "counter", ";", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_REFRESH_CANCEL", "\"", ")", ";", "r", ".", "setParameters", "(", "new", "Object", "[", "]", "{", "counter", "}", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "return", "true", ";", "}", "}", "}" ]
A menu preheating task.
[ "A", "menu", "preheating", "task", "." ]
[ "// bail out!", "// tackle the Tools menu now? How?", "// recursive?", "// do nothing, it may happen for user-provided menus", "//NOI18N", "// NOI18N", "// NOI18N", "// proceed only if switching from external application", "// proceed only if switching to external application", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// no file refresh", "// ignore any errors", "// preinitialize", "// NOI18N", "// NOI18N", "// connect the bridge with the masterfs's RefreshSlow", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// end of NbWindowsAdapter" ]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fe7cbdfa37d89249e73b0d65934a677ab78e040d
arusinha/incubator-netbeans
platform/core.ui/src/org/netbeans/core/ui/warmup/MenuWarmUpTask.java
[ "Apache-2.0" ]
Java
NbWindowsAdapter
/** * After activation of window is refreshed filesystem but only if switching * from an external application. */
After activation of window is refreshed filesystem but only if switching from an external application.
[ "After", "activation", "of", "window", "is", "refreshed", "filesystem", "but", "only", "if", "switching", "from", "an", "external", "application", "." ]
private static class NbWindowsAdapter extends WindowAdapter implements Runnable, Cancellable { private static final RequestProcessor rp = new RequestProcessor ("Refresh-After-WindowActivated", 1, true);//NOI18N private RequestProcessor.Task task; private AtomicBoolean goOn; private static final Logger UILOG = Logger.getLogger("org.netbeans.ui.focus"); // NOI18N private static final Logger LOG = Logger.getLogger("org.netbeans.core.ui.focus"); // NOI18N private boolean warnedNoRefresh; @Override public void windowActivated(WindowEvent e) { // proceed only if switching from external application if (e.getOppositeWindow() == null) { synchronized (rp) { if (task != null) { LOG.fine("Scheduling task after activation"); task.schedule(1500); task = null; } else { LOG.fine("Activation without prepared refresh task"); } } } } @Override public void windowDeactivated(WindowEvent e) { // proceed only if switching to external application if (e.getOppositeWindow() == null) { synchronized (rp) { if (task != null) { task.cancel(); } else { task = rp.create(this); } LOG.fine("Window deactivated, preparing refresh task"); } if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_DEACTIVATED"); // NOI18N r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } } } private static boolean isNoRefresh() { if (Boolean.getBoolean("netbeans.indexing.noFileRefresh")) { return true; } return NbPreferences.root().node("org/openide/actions/FileSystemRefreshAction").getBoolean("manual", false); // NOI18N } @Messages({ "MSG_Refresh=Checking for external changes", "# default delay is 10s. Increase to Integer.MAX_VALUE to effectively disable", "#NOI18N", "MSG_RefreshDelay=10000", "MSG_Refresh_Suspend=Suspended" }) @Override public void run() { if (isNoRefresh()) { if (!warnedNoRefresh) { LOG.info("External Changes Refresh on focus gain disabled"); // NOI18N warnedNoRefresh = true; } LOG.fine("Refresh disabled, aborting"); return; // no file refresh } final ProgressHandle h = ProgressHandleFactory.createHandle(MSG_Refresh(), this, null); if (!LOG.isLoggable(Level.FINE)) { int delay = Integer.parseInt(MSG_RefreshDelay()); h.setInitialDelay(delay); } h.start(); Runnable run = null; class HandleBridge extends ActionEvent implements Runnable { private FileObject previous; private long next; public HandleBridge(Object source) { super (source, 0, ""); } @Override public void setSource(Object newSource) { if (newSource instanceof Object[]) { long now = System.currentTimeMillis(); boolean again = now > next; Object[] arr = (Object[])newSource; if (arr.length >= 3 && arr[0] instanceof Integer && arr[1] instanceof Integer && arr[2] instanceof FileObject ) { if (! (getSource() instanceof Object[])) { h.switchToDeterminate((Integer)arr[1]); LOG.log(Level.FINE, "First refresh progress event delivered: {0}/{1} where {2}, goOn: {3}", arr); } if ((Integer)arr[0] < (Integer)arr[1]) { h.progress((Integer)arr[0]); } FileObject fo = (FileObject)arr[2]; if (previous != fo.getParent() && again) { previous = fo.getParent(); if (previous != null) { h.progress(previous.getPath()); } next = now + 500; } super.setSource(newSource); } if (arr.length >= 4 && arr[3] instanceof AtomicBoolean) { goOn = (AtomicBoolean)arr[3]; } if (arr.length >= 5 && arr[4] == null && again) { arr[4] = Utilities.actionsGlobalContext().lookup(FileObject.class); LOG.log(Level.FINE, "Preferring {0}", arr[4]); } } } @Override public void run() { if (EventQueue.isDispatchThread()) { try { h.suspend(MSG_Refresh_Suspend()); } catch (Throwable t) { // ignore any errors } } else { EventQueue.invokeLater(this); } } } HandleBridge handleBridge = new HandleBridge(this); // preinitialize handleBridge.run(); try { FileObject udFo = FileUtil.toFileObject(Places.getUserDirectory()); if (udFo != null) { udFo = udFo.getFileSystem().getRoot(); } if (udFo != null) { run = (Runnable)udFo.getAttribute("refreshSlow"); // NOI18N } } catch (Exception ex) { LOG.log(Level.FINE, "Error getting refreshSlow", ex); // NOI18N } long now = System.currentTimeMillis(); try { if (run == null) { LOG.fine("Starting classical refresh"); FileUtil.refreshAll(); } else { // connect the bridge with the masterfs's RefreshSlow if (run instanceof AtomicBoolean) { goOn = (AtomicBoolean) run; LOG.fine("goOn controller registered"); } LOG.fine("Starting slow refresh"); run.equals(handleBridge); run.run(); } long took = System.currentTimeMillis() - now; if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_ACTIVATED"); // NOI18N r.setParameters(new Object[] { took }); r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } LOG.log(Level.FINE, "Refresh done in {0} ms", took); AtomicBoolean ab = goOn; if (ab == null || ab.get()) { long sfs = System.currentTimeMillis(); FileUtil.getConfigRoot().getFileSystem().refresh(true); LOG.log(Level.FINE, "SystemFileSystem refresh done {0} ms", (System.currentTimeMillis() - sfs)); } else { LOG.fine("Skipping SystemFileSystem refresh"); } } catch (FileStateInvalidException ex) { Exceptions.printStackTrace(ex); } finally { h.finish(); } } private int counter; @Override public boolean cancel() { synchronized(rp) { if (task != null) { task.cancel(); } if (goOn != null) { goOn.set(false); LOG.log(Level.FINE, "Signaling cancel to {0}", System.identityHashCode(goOn)); } else { LOG.log(Level.FINE, "Cannot signal cancel, goOn is null"); } } ++counter; if (UILOG.isLoggable(Level.FINE)) { LogRecord r = new LogRecord(Level.FINE, "LOG_WINDOW_REFRESH_CANCEL"); // NOI18N r.setParameters(new Object[]{counter}); r.setResourceBundleName("org.netbeans.core.ui.warmup.Bundle"); // NOI18N r.setResourceBundle(NbBundle.getBundle(MenuWarmUpTask.class)); // NOI18N r.setLoggerName(UILOG.getName()); UILOG.log(r); } return true; } }
[ "private", "static", "class", "NbWindowsAdapter", "extends", "WindowAdapter", "implements", "Runnable", ",", "Cancellable", "{", "private", "static", "final", "RequestProcessor", "rp", "=", "new", "RequestProcessor", "(", "\"", "Refresh-After-WindowActivated", "\"", ",", "1", ",", "true", ")", ";", "private", "RequestProcessor", ".", "Task", "task", ";", "private", "AtomicBoolean", "goOn", ";", "private", "static", "final", "Logger", "UILOG", "=", "Logger", ".", "getLogger", "(", "\"", "org.netbeans.ui.focus", "\"", ")", ";", "private", "static", "final", "Logger", "LOG", "=", "Logger", ".", "getLogger", "(", "\"", "org.netbeans.core.ui.focus", "\"", ")", ";", "private", "boolean", "warnedNoRefresh", ";", "@", "Override", "public", "void", "windowActivated", "(", "WindowEvent", "e", ")", "{", "if", "(", "e", ".", "getOppositeWindow", "(", ")", "==", "null", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "LOG", ".", "fine", "(", "\"", "Scheduling task after activation", "\"", ")", ";", "task", ".", "schedule", "(", "1500", ")", ";", "task", "=", "null", ";", "}", "else", "{", "LOG", ".", "fine", "(", "\"", "Activation without prepared refresh task", "\"", ")", ";", "}", "}", "}", "}", "@", "Override", "public", "void", "windowDeactivated", "(", "WindowEvent", "e", ")", "{", "if", "(", "e", ".", "getOppositeWindow", "(", ")", "==", "null", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "task", ".", "cancel", "(", ")", ";", "}", "else", "{", "task", "=", "rp", ".", "create", "(", "this", ")", ";", "}", "LOG", ".", "fine", "(", "\"", "Window deactivated, preparing refresh task", "\"", ")", ";", "}", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_DEACTIVATED", "\"", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "}", "}", "private", "static", "boolean", "isNoRefresh", "(", ")", "{", "if", "(", "Boolean", ".", "getBoolean", "(", "\"", "netbeans.indexing.noFileRefresh", "\"", ")", ")", "{", "return", "true", ";", "}", "return", "NbPreferences", ".", "root", "(", ")", ".", "node", "(", "\"", "org/openide/actions/FileSystemRefreshAction", "\"", ")", ".", "getBoolean", "(", "\"", "manual", "\"", ",", "false", ")", ";", "}", "@", "Messages", "(", "{", "\"", "MSG_Refresh=Checking for external changes", "\"", ",", "\"", "# default delay is 10s. Increase to Integer.MAX_VALUE to effectively disable", "\"", ",", "\"", "#NOI18N", "\"", ",", "\"", "MSG_RefreshDelay=10000", "\"", ",", "\"", "MSG_Refresh_Suspend=Suspended", "\"", "}", ")", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "isNoRefresh", "(", ")", ")", "{", "if", "(", "!", "warnedNoRefresh", ")", "{", "LOG", ".", "info", "(", "\"", "External Changes Refresh on focus gain disabled", "\"", ")", ";", "warnedNoRefresh", "=", "true", ";", "}", "LOG", ".", "fine", "(", "\"", "Refresh disabled, aborting", "\"", ")", ";", "return", ";", "}", "final", "ProgressHandle", "h", "=", "ProgressHandleFactory", ".", "createHandle", "(", "MSG_Refresh", "(", ")", ",", "this", ",", "null", ")", ";", "if", "(", "!", "LOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "int", "delay", "=", "Integer", ".", "parseInt", "(", "MSG_RefreshDelay", "(", ")", ")", ";", "h", ".", "setInitialDelay", "(", "delay", ")", ";", "}", "h", ".", "start", "(", ")", ";", "Runnable", "run", "=", "null", ";", "class", "HandleBridge", "extends", "ActionEvent", "implements", "Runnable", "{", "private", "FileObject", "previous", ";", "private", "long", "next", ";", "public", "HandleBridge", "(", "Object", "source", ")", "{", "super", "(", "source", ",", "0", ",", "\"", "\"", ")", ";", "}", "@", "Override", "public", "void", "setSource", "(", "Object", "newSource", ")", "{", "if", "(", "newSource", "instanceof", "Object", "[", "]", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "again", "=", "now", ">", "next", ";", "Object", "[", "]", "arr", "=", "(", "Object", "[", "]", ")", "newSource", ";", "if", "(", "arr", ".", "length", ">=", "3", "&&", "arr", "[", "0", "]", "instanceof", "Integer", "&&", "arr", "[", "1", "]", "instanceof", "Integer", "&&", "arr", "[", "2", "]", "instanceof", "FileObject", ")", "{", "if", "(", "!", "(", "getSource", "(", ")", "instanceof", "Object", "[", "]", ")", ")", "{", "h", ".", "switchToDeterminate", "(", "(", "Integer", ")", "arr", "[", "1", "]", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "First refresh progress event delivered: {0}/{1} where {2}, goOn: {3}", "\"", ",", "arr", ")", ";", "}", "if", "(", "(", "Integer", ")", "arr", "[", "0", "]", "<", "(", "Integer", ")", "arr", "[", "1", "]", ")", "{", "h", ".", "progress", "(", "(", "Integer", ")", "arr", "[", "0", "]", ")", ";", "}", "FileObject", "fo", "=", "(", "FileObject", ")", "arr", "[", "2", "]", ";", "if", "(", "previous", "!=", "fo", ".", "getParent", "(", ")", "&&", "again", ")", "{", "previous", "=", "fo", ".", "getParent", "(", ")", ";", "if", "(", "previous", "!=", "null", ")", "{", "h", ".", "progress", "(", "previous", ".", "getPath", "(", ")", ")", ";", "}", "next", "=", "now", "+", "500", ";", "}", "super", ".", "setSource", "(", "newSource", ")", ";", "}", "if", "(", "arr", ".", "length", ">=", "4", "&&", "arr", "[", "3", "]", "instanceof", "AtomicBoolean", ")", "{", "goOn", "=", "(", "AtomicBoolean", ")", "arr", "[", "3", "]", ";", "}", "if", "(", "arr", ".", "length", ">=", "5", "&&", "arr", "[", "4", "]", "==", "null", "&&", "again", ")", "{", "arr", "[", "4", "]", "=", "Utilities", ".", "actionsGlobalContext", "(", ")", ".", "lookup", "(", "FileObject", ".", "class", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Preferring {0}", "\"", ",", "arr", "[", "4", "]", ")", ";", "}", "}", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "EventQueue", ".", "isDispatchThread", "(", ")", ")", "{", "try", "{", "h", ".", "suspend", "(", "MSG_Refresh_Suspend", "(", ")", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "}", "}", "else", "{", "EventQueue", ".", "invokeLater", "(", "this", ")", ";", "}", "}", "}", "HandleBridge", "handleBridge", "=", "new", "HandleBridge", "(", "this", ")", ";", "handleBridge", ".", "run", "(", ")", ";", "try", "{", "FileObject", "udFo", "=", "FileUtil", ".", "toFileObject", "(", "Places", ".", "getUserDirectory", "(", ")", ")", ";", "if", "(", "udFo", "!=", "null", ")", "{", "udFo", "=", "udFo", ".", "getFileSystem", "(", ")", ".", "getRoot", "(", ")", ";", "}", "if", "(", "udFo", "!=", "null", ")", "{", "run", "=", "(", "Runnable", ")", "udFo", ".", "getAttribute", "(", "\"", "refreshSlow", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Error getting refreshSlow", "\"", ",", "ex", ")", ";", "}", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "try", "{", "if", "(", "run", "==", "null", ")", "{", "LOG", ".", "fine", "(", "\"", "Starting classical refresh", "\"", ")", ";", "FileUtil", ".", "refreshAll", "(", ")", ";", "}", "else", "{", "if", "(", "run", "instanceof", "AtomicBoolean", ")", "{", "goOn", "=", "(", "AtomicBoolean", ")", "run", ";", "LOG", ".", "fine", "(", "\"", "goOn controller registered", "\"", ")", ";", "}", "LOG", ".", "fine", "(", "\"", "Starting slow refresh", "\"", ")", ";", "run", ".", "equals", "(", "handleBridge", ")", ";", "run", ".", "run", "(", ")", ";", "}", "long", "took", "=", "System", ".", "currentTimeMillis", "(", ")", "-", "now", ";", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_ACTIVATED", "\"", ")", ";", "r", ".", "setParameters", "(", "new", "Object", "[", "]", "{", "took", "}", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Refresh done in {0} ms", "\"", ",", "took", ")", ";", "AtomicBoolean", "ab", "=", "goOn", ";", "if", "(", "ab", "==", "null", "||", "ab", ".", "get", "(", ")", ")", "{", "long", "sfs", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "FileUtil", ".", "getConfigRoot", "(", ")", ".", "getFileSystem", "(", ")", ".", "refresh", "(", "true", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "SystemFileSystem refresh done {0} ms", "\"", ",", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "sfs", ")", ")", ";", "}", "else", "{", "LOG", ".", "fine", "(", "\"", "Skipping SystemFileSystem refresh", "\"", ")", ";", "}", "}", "catch", "(", "FileStateInvalidException", "ex", ")", "{", "Exceptions", ".", "printStackTrace", "(", "ex", ")", ";", "}", "finally", "{", "h", ".", "finish", "(", ")", ";", "}", "}", "private", "int", "counter", ";", "@", "Override", "public", "boolean", "cancel", "(", ")", "{", "synchronized", "(", "rp", ")", "{", "if", "(", "task", "!=", "null", ")", "{", "task", ".", "cancel", "(", ")", ";", "}", "if", "(", "goOn", "!=", "null", ")", "{", "goOn", ".", "set", "(", "false", ")", ";", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Signaling cancel to {0}", "\"", ",", "System", ".", "identityHashCode", "(", "goOn", ")", ")", ";", "}", "else", "{", "LOG", ".", "log", "(", "Level", ".", "FINE", ",", "\"", "Cannot signal cancel, goOn is null", "\"", ")", ";", "}", "}", "++", "counter", ";", "if", "(", "UILOG", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "LogRecord", "r", "=", "new", "LogRecord", "(", "Level", ".", "FINE", ",", "\"", "LOG_WINDOW_REFRESH_CANCEL", "\"", ")", ";", "r", ".", "setParameters", "(", "new", "Object", "[", "]", "{", "counter", "}", ")", ";", "r", ".", "setResourceBundleName", "(", "\"", "org.netbeans.core.ui.warmup.Bundle", "\"", ")", ";", "r", ".", "setResourceBundle", "(", "NbBundle", ".", "getBundle", "(", "MenuWarmUpTask", ".", "class", ")", ")", ";", "r", ".", "setLoggerName", "(", "UILOG", ".", "getName", "(", ")", ")", ";", "UILOG", ".", "log", "(", "r", ")", ";", "}", "return", "true", ";", "}", "}" ]
After activation of window is refreshed filesystem but only if switching from an external application.
[ "After", "activation", "of", "window", "is", "refreshed", "filesystem", "but", "only", "if", "switching", "from", "an", "external", "application", "." ]
[ "//NOI18N", "// NOI18N", "// NOI18N", "// proceed only if switching from external application", "// proceed only if switching to external application", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// no file refresh", "// ignore any errors", "// preinitialize", "// NOI18N", "// NOI18N", "// connect the bridge with the masterfs's RefreshSlow", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N", "// NOI18N" ]
[ { "param": "WindowAdapter", "type": null }, { "param": "Runnable, Cancellable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "WindowAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "Runnable, Cancellable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }