repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcUtil.java | JdbcUtil.executeSql | public static boolean executeSql(final String sql, final Connection connection, final boolean isDebug) throws SQLException {
if (isDebug || LOGGER.isTraceEnabled()) {
LOGGER.log(Level.INFO, "Executing SQL [" + sql + "]");
}
final Statement statement = connection.createStatement();
final boolean isSuccess = !statement.execute(sql);
statement.close();
return isSuccess;
} | java | public static boolean executeSql(final String sql, final Connection connection, final boolean isDebug) throws SQLException {
if (isDebug || LOGGER.isTraceEnabled()) {
LOGGER.log(Level.INFO, "Executing SQL [" + sql + "]");
}
final Statement statement = connection.createStatement();
final boolean isSuccess = !statement.execute(sql);
statement.close();
return isSuccess;
} | [
"public",
"static",
"boolean",
"executeSql",
"(",
"final",
"String",
"sql",
",",
"final",
"Connection",
"connection",
",",
"final",
"boolean",
"isDebug",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"isDebug",
"||",
"LOGGER",
".",
"isTraceEnabled",
"(",
")",... | Executes the specified SQL with the specified connection.
@param sql the specified SQL
@param connection connection the specified connection
@param isDebug the specified debug flag
@return {@code true} if success, returns {@false} otherwise
@throws SQLException SQLException | [
"Executes",
"the",
"specified",
"SQL",
"with",
"the",
"specified",
"connection",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcUtil.java#L60-L70 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcUtil.java | JdbcUtil.executeSql | public static boolean executeSql(final String sql, final List<Object> paramList, final Connection connection, final boolean isDebug) throws SQLException {
if (isDebug || LOGGER.isTraceEnabled()) {
LOGGER.log(Level.INFO, "Executing SQL [" + sql + "]");
}
final PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= paramList.size(); i++) {
preparedStatement.setObject(i, paramList.get(i - 1));
}
final boolean isSuccess = preparedStatement.execute();
preparedStatement.close();
return isSuccess;
} | java | public static boolean executeSql(final String sql, final List<Object> paramList, final Connection connection, final boolean isDebug) throws SQLException {
if (isDebug || LOGGER.isTraceEnabled()) {
LOGGER.log(Level.INFO, "Executing SQL [" + sql + "]");
}
final PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 1; i <= paramList.size(); i++) {
preparedStatement.setObject(i, paramList.get(i - 1));
}
final boolean isSuccess = preparedStatement.execute();
preparedStatement.close();
return isSuccess;
} | [
"public",
"static",
"boolean",
"executeSql",
"(",
"final",
"String",
"sql",
",",
"final",
"List",
"<",
"Object",
">",
"paramList",
",",
"final",
"Connection",
"connection",
",",
"final",
"boolean",
"isDebug",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"i... | Executes the specified SQL with the specified params and connection...
@param sql the specified SQL
@param paramList the specified params
@param connection the specified connection
@param isDebug the specified debug flag
@return {@code true} if success, returns {@false} otherwise
@throws SQLException SQLException | [
"Executes",
"the",
"specified",
"SQL",
"with",
"the",
"specified",
"params",
"and",
"connection",
"..."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcUtil.java#L82-L95 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/servlet/renderer/AbstractFreeMarkerRenderer.java | AbstractFreeMarkerRenderer.genHTML | protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel, final Template template)
throws Exception {
final StringWriter stringWriter = new StringWriter();
template.setOutputEncoding("UTF-8");
template.process(dataModel, stringWriter);
final StringBuilder pageContentBuilder = new StringBuilder(stringWriter.toString());
final long endimeMillis = System.currentTimeMillis();
final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS);
final String msg = String.format("\n<!-- Generated by Latke (https://github.com/b3log/latke) in %1$dms, %2$s -->",
endimeMillis - startTimeMillis, dateString);
pageContentBuilder.append(msg);
return pageContentBuilder.toString();
} | java | protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel, final Template template)
throws Exception {
final StringWriter stringWriter = new StringWriter();
template.setOutputEncoding("UTF-8");
template.process(dataModel, stringWriter);
final StringBuilder pageContentBuilder = new StringBuilder(stringWriter.toString());
final long endimeMillis = System.currentTimeMillis();
final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS);
final String msg = String.format("\n<!-- Generated by Latke (https://github.com/b3log/latke) in %1$dms, %2$s -->",
endimeMillis - startTimeMillis, dateString);
pageContentBuilder.append(msg);
return pageContentBuilder.toString();
} | [
"protected",
"String",
"genHTML",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"dataModel",
",",
"final",
"Template",
"template",
")",
"throws",
"Exception",
"{",
"final",
"StringWriter",
"stringWriter",
... | Processes the specified FreeMarker template with the specified request, data model.
@param request the specified request
@param dataModel the specified data model
@param template the specified FreeMarker template
@return generated HTML
@throws Exception exception | [
"Processes",
"the",
"specified",
"FreeMarker",
"template",
"with",
"the",
"specified",
"request",
"data",
"model",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/servlet/renderer/AbstractFreeMarkerRenderer.java#L150-L165 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Discoverer.java | Discoverer.discover | public static Collection<Class<?>> discover(final String scanPath) throws Exception {
if (StringUtils.isBlank(scanPath)) {
throw new IllegalStateException("Please specify the [scanPath]");
}
LOGGER.debug("scanPath[" + scanPath + "]");
final Collection<Class<?>> ret = new HashSet<>();
final String[] splitPaths = scanPath.split(",");
// Adds some built-in components
final String[] paths = ArrayUtils.concatenate(splitPaths, BUILT_IN_COMPONENT_PKGS);
final Set<URL> urls = new LinkedHashSet<>();
for (String path : paths) {
/*
* the being two types of the scanPath.
* 1 package: org.b3log.xxx
* 2 ant-style classpath: org/b3log/** /*process.class
*/
if (!AntPathMatcher.isPattern(path)) {
path = path.replaceAll("\\.", "/") + "/**/*.class";
}
urls.addAll(ClassPathResolver.getResources(path));
}
for (final URL url : urls) {
final DataInputStream classInputStream = new DataInputStream(url.openStream());
final ClassFile classFile = new ClassFile(classInputStream);
final String className = classFile.getName();
final AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag);
if (null == annotationsAttribute) {
LOGGER.log(Level.TRACE, "The class [name={0}] is not a bean", className);
continue;
}
final ConstPool constPool = classFile.getConstPool();
final Annotation[] annotations = annotationsAttribute.getAnnotations();
boolean maybeBeanClass = false;
for (final Annotation annotation : annotations) {
final String typeName = annotation.getTypeName();
if (typeName.equals(Singleton.class.getName())) {
maybeBeanClass = true;
break;
}
if (typeName.equals(RequestProcessor.class.getName()) || typeName.equals(Service.class.getName()) ||
typeName.equals(Repository.class.getName())) {
final Annotation singletonAnnotation = new Annotation(Singleton.class.getName(), constPool);
annotationsAttribute.addAnnotation(singletonAnnotation);
classFile.addAttribute(annotationsAttribute);
classFile.setVersionToJava5();
maybeBeanClass = true;
break;
}
}
if (maybeBeanClass) {
Class<?> clz = null;
try {
clz = Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (final ClassNotFoundException e) {
LOGGER.log(Level.ERROR, "Loads class [" + className + "] failed", e);
}
ret.add(clz);
}
}
return ret;
} | java | public static Collection<Class<?>> discover(final String scanPath) throws Exception {
if (StringUtils.isBlank(scanPath)) {
throw new IllegalStateException("Please specify the [scanPath]");
}
LOGGER.debug("scanPath[" + scanPath + "]");
final Collection<Class<?>> ret = new HashSet<>();
final String[] splitPaths = scanPath.split(",");
// Adds some built-in components
final String[] paths = ArrayUtils.concatenate(splitPaths, BUILT_IN_COMPONENT_PKGS);
final Set<URL> urls = new LinkedHashSet<>();
for (String path : paths) {
/*
* the being two types of the scanPath.
* 1 package: org.b3log.xxx
* 2 ant-style classpath: org/b3log/** /*process.class
*/
if (!AntPathMatcher.isPattern(path)) {
path = path.replaceAll("\\.", "/") + "/**/*.class";
}
urls.addAll(ClassPathResolver.getResources(path));
}
for (final URL url : urls) {
final DataInputStream classInputStream = new DataInputStream(url.openStream());
final ClassFile classFile = new ClassFile(classInputStream);
final String className = classFile.getName();
final AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag);
if (null == annotationsAttribute) {
LOGGER.log(Level.TRACE, "The class [name={0}] is not a bean", className);
continue;
}
final ConstPool constPool = classFile.getConstPool();
final Annotation[] annotations = annotationsAttribute.getAnnotations();
boolean maybeBeanClass = false;
for (final Annotation annotation : annotations) {
final String typeName = annotation.getTypeName();
if (typeName.equals(Singleton.class.getName())) {
maybeBeanClass = true;
break;
}
if (typeName.equals(RequestProcessor.class.getName()) || typeName.equals(Service.class.getName()) ||
typeName.equals(Repository.class.getName())) {
final Annotation singletonAnnotation = new Annotation(Singleton.class.getName(), constPool);
annotationsAttribute.addAnnotation(singletonAnnotation);
classFile.addAttribute(annotationsAttribute);
classFile.setVersionToJava5();
maybeBeanClass = true;
break;
}
}
if (maybeBeanClass) {
Class<?> clz = null;
try {
clz = Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (final ClassNotFoundException e) {
LOGGER.log(Level.ERROR, "Loads class [" + className + "] failed", e);
}
ret.add(clz);
}
}
return ret;
} | [
"public",
"static",
"Collection",
"<",
"Class",
"<",
"?",
">",
">",
"discover",
"(",
"final",
"String",
"scanPath",
")",
"throws",
"Exception",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"scanPath",
")",
")",
"{",
"throw",
"new",
"IllegalStateExce... | Scans classpath to discover bean classes.
@param scanPath the paths to scan, using ',' as the separator. There are two types of the scanPath:
<ul>
<li>package: org.b3log.process</li>
<li>ant-style classpath: org/b3log/** /*process.class</li>
</ul>
@return discovered classes
@throws Exception exception | [
"Scans",
"classpath",
"to",
"discover",
"bean",
"classes",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Discoverer.java#L74-L148 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Crypts.java | Crypts.signHmacSHA1 | public static String signHmacSHA1(final String source, final String secret) {
try {
final Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1"));
final byte[] signData = mac.doFinal(source.getBytes("UTF-8"));
return new String(Base64.encodeBase64(signData), "UTF-8");
} catch (final Exception e) {
throw new RuntimeException("HMAC-SHA1 sign failed", e);
}
} | java | public static String signHmacSHA1(final String source, final String secret) {
try {
final Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1"));
final byte[] signData = mac.doFinal(source.getBytes("UTF-8"));
return new String(Base64.encodeBase64(signData), "UTF-8");
} catch (final Exception e) {
throw new RuntimeException("HMAC-SHA1 sign failed", e);
}
} | [
"public",
"static",
"String",
"signHmacSHA1",
"(",
"final",
"String",
"source",
",",
"final",
"String",
"secret",
")",
"{",
"try",
"{",
"final",
"Mac",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"\"HmacSHA1\"",
")",
";",
"mac",
".",
"init",
"(",
"new",
... | Signs the specified source string using the specified secret.
@param source the specified source string
@param secret the specified secret
@return signed string | [
"Signs",
"the",
"specified",
"source",
"string",
"using",
"the",
"specified",
"secret",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Crypts.java#L46-L56 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Crypts.java | Crypts.encryptByAES | public static String encryptByAES(final String content, final String key) {
try {
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
final byte[] byteContent = content.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(byteContent);
return Hex.encodeHexString(result);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Encrypt failed", e);
return null;
}
} | java | public static String encryptByAES(final String content, final String key) {
try {
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
final byte[] byteContent = content.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(byteContent);
return Hex.encodeHexString(result);
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Encrypt failed", e);
return null;
}
} | [
"public",
"static",
"String",
"encryptByAES",
"(",
"final",
"String",
"content",
",",
"final",
"String",
"key",
")",
"{",
"try",
"{",
"final",
"KeyGenerator",
"kgen",
"=",
"KeyGenerator",
".",
"getInstance",
"(",
"\"AES\"",
")",
";",
"final",
"SecureRandom",
... | Encrypts by AES.
@param content the specified content to encrypt
@param key the specified key
@return encrypted content
@see #decryptByAES(java.lang.String, java.lang.String) | [
"Encrypts",
"by",
"AES",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Crypts.java#L71-L91 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Crypts.java | Crypts.decryptByAES | public static String decryptByAES(final String content, final String key) {
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
}
} | java | public static String decryptByAES(final String content, final String key) {
try {
final byte[] data = Hex.decodeHex(content.toCharArray());
final KeyGenerator kgen = KeyGenerator.getInstance("AES");
final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
final SecretKey secretKey = kgen.generateKey();
final byte[] enCodeFormat = secretKey.getEncoded();
final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
final byte[] result = cipher.doFinal(data);
return new String(result, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decrypt failed");
return null;
}
} | [
"public",
"static",
"String",
"decryptByAES",
"(",
"final",
"String",
"content",
",",
"final",
"String",
"key",
")",
"{",
"try",
"{",
"final",
"byte",
"[",
"]",
"data",
"=",
"Hex",
".",
"decodeHex",
"(",
"content",
".",
"toCharArray",
"(",
")",
")",
";... | Decrypts by AES.
@param content the specified content to decrypt
@param key the specified key
@return original content
@see #encryptByAES(java.lang.String, java.lang.String) | [
"Decrypts",
"by",
"AES",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Crypts.java#L101-L121 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Ids.java | Ids.genTimeMillisId | public static synchronized String genTimeMillisId() {
String ret;
ID_GEN_LOCK.lock();
try {
ret = String.valueOf(System.currentTimeMillis());
try {
Thread.sleep(ID_GEN_SLEEP_MILLIS);
} catch (final InterruptedException e) {
throw new RuntimeException("Generates time millis id fail");
}
} finally {
ID_GEN_LOCK.unlock();
}
return ret;
} | java | public static synchronized String genTimeMillisId() {
String ret;
ID_GEN_LOCK.lock();
try {
ret = String.valueOf(System.currentTimeMillis());
try {
Thread.sleep(ID_GEN_SLEEP_MILLIS);
} catch (final InterruptedException e) {
throw new RuntimeException("Generates time millis id fail");
}
} finally {
ID_GEN_LOCK.unlock();
}
return ret;
} | [
"public",
"static",
"synchronized",
"String",
"genTimeMillisId",
"(",
")",
"{",
"String",
"ret",
";",
"ID_GEN_LOCK",
".",
"lock",
"(",
")",
";",
"try",
"{",
"ret",
"=",
"String",
".",
"valueOf",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";"... | Gets current date time string.
<p>
<b>Note</b>: This method is not safe in cluster environment.
</p>
@return a time millis string | [
"Gets",
"current",
"date",
"time",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Ids.java#L54-L71 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.hasLocale | public static boolean hasLocale(final Locale locale) {
try {
ResourceBundle.getBundle(Keys.LANGUAGE, locale);
return true;
} catch (final MissingResourceException e) {
return false;
}
} | java | public static boolean hasLocale(final Locale locale) {
try {
ResourceBundle.getBundle(Keys.LANGUAGE, locale);
return true;
} catch (final MissingResourceException e) {
return false;
}
} | [
"public",
"static",
"boolean",
"hasLocale",
"(",
"final",
"Locale",
"locale",
")",
"{",
"try",
"{",
"ResourceBundle",
".",
"getBundle",
"(",
"Keys",
".",
"LANGUAGE",
",",
"locale",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"final",
"MissingResour... | Determines whether the server has the specified locale configuration or not.
@param locale the specified locale
@return {@code true} if the server has the specified locale, {@code false} otherwise | [
"Determines",
"whether",
"the",
"server",
"has",
"the",
"specified",
"locale",
"configuration",
"or",
"not",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L133-L141 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.setLocale | public static void setLocale(final HttpServletRequest request, final Locale locale) {
final HttpSession session = request.getSession(false);
if (null == session) {
LOGGER.warn("Ignores set locale caused by no session");
return;
}
session.setAttribute(Keys.LOCALE, locale);
LOGGER.log(Level.DEBUG, "Client[sessionId={0}] sets locale to [{1}]", new Object[]{session.getId(), locale.toString()});
} | java | public static void setLocale(final HttpServletRequest request, final Locale locale) {
final HttpSession session = request.getSession(false);
if (null == session) {
LOGGER.warn("Ignores set locale caused by no session");
return;
}
session.setAttribute(Keys.LOCALE, locale);
LOGGER.log(Level.DEBUG, "Client[sessionId={0}] sets locale to [{1}]", new Object[]{session.getId(), locale.toString()});
} | [
"public",
"static",
"void",
"setLocale",
"(",
"final",
"HttpServletRequest",
"request",
",",
"final",
"Locale",
"locale",
")",
"{",
"final",
"HttpSession",
"session",
"=",
"request",
".",
"getSession",
"(",
"false",
")",
";",
"if",
"(",
"null",
"==",
"sessio... | Sets the specified locale into session of the specified request.
<p>
If no session of the specified request, do nothing.
</p>
@param request the specified request
@param locale a new locale | [
"Sets",
"the",
"specified",
"locale",
"into",
"session",
"of",
"the",
"specified",
"request",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L153-L164 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.getLocale | public static Locale getLocale() {
final Locale ret = LOCALE.get();
if (null == ret) {
return Latkes.getLocale();
}
return ret;
} | java | public static Locale getLocale() {
final Locale ret = LOCALE.get();
if (null == ret) {
return Latkes.getLocale();
}
return ret;
} | [
"public",
"static",
"Locale",
"getLocale",
"(",
")",
"{",
"final",
"Locale",
"ret",
"=",
"LOCALE",
".",
"get",
"(",
")",
";",
"if",
"(",
"null",
"==",
"ret",
")",
"{",
"return",
"Latkes",
".",
"getLocale",
"(",
")",
";",
"}",
"return",
"ret",
";",
... | Gets locale.
@return locale | [
"Gets",
"locale",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L180-L187 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.getCountry | public static String getCountry(final String localeString) {
if (localeString.length() >= COUNTRY_END) {
return localeString.substring(COUNTRY_START, COUNTRY_END);
}
return "";
} | java | public static String getCountry(final String localeString) {
if (localeString.length() >= COUNTRY_END) {
return localeString.substring(COUNTRY_START, COUNTRY_END);
}
return "";
} | [
"public",
"static",
"String",
"getCountry",
"(",
"final",
"String",
"localeString",
")",
"{",
"if",
"(",
"localeString",
".",
"length",
"(",
")",
">=",
"COUNTRY_END",
")",
"{",
"return",
"localeString",
".",
"substring",
"(",
"COUNTRY_START",
",",
"COUNTRY_END... | Gets country from the specified locale string.
@param localeString the specified locale string
@return country, if the length of specified locale string less than 5, returns "" | [
"Gets",
"country",
"from",
"the",
"specified",
"locale",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L195-L201 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Locales.java | Locales.getLanguage | public static String getLanguage(final String localeString) {
if (localeString.length() >= LANG_END) {
return localeString.substring(LANG_START, LANG_END);
}
return "";
} | java | public static String getLanguage(final String localeString) {
if (localeString.length() >= LANG_END) {
return localeString.substring(LANG_START, LANG_END);
}
return "";
} | [
"public",
"static",
"String",
"getLanguage",
"(",
"final",
"String",
"localeString",
")",
"{",
"if",
"(",
"localeString",
".",
"length",
"(",
")",
">=",
"LANG_END",
")",
"{",
"return",
"localeString",
".",
"substring",
"(",
"LANG_START",
",",
"LANG_END",
")"... | Gets language from the specified locale string.
@param localeString the specified locale string
@return language, if the length of specified locale string less than 2, returns "" | [
"Gets",
"language",
"from",
"the",
"specified",
"locale",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Locales.java#L209-L215 | train |
b3log/latke | latke-repository-sqlserver/src/main/java/org/b3log/latke/repository/sqlserver/SQLServerJdbcDatabaseSolution.java | SQLServerJdbcDatabaseSolution.createKeyDefinition | private String createKeyDefinition(final List<FieldDefinition> keyDefinitionList) {
final StringBuilder sql = new StringBuilder();
sql.append(" PRIMARY KEY");
boolean isFirst = true;
for (FieldDefinition fieldDefinition : keyDefinitionList) {
if (isFirst) {
sql.append("(");
isFirst = false;
} else {
sql.append(",");
}
sql.append(fieldDefinition.getName());
}
sql.append(")");
return sql.toString();
} | java | private String createKeyDefinition(final List<FieldDefinition> keyDefinitionList) {
final StringBuilder sql = new StringBuilder();
sql.append(" PRIMARY KEY");
boolean isFirst = true;
for (FieldDefinition fieldDefinition : keyDefinitionList) {
if (isFirst) {
sql.append("(");
isFirst = false;
} else {
sql.append(",");
}
sql.append(fieldDefinition.getName());
}
sql.append(")");
return sql.toString();
} | [
"private",
"String",
"createKeyDefinition",
"(",
"final",
"List",
"<",
"FieldDefinition",
">",
"keyDefinitionList",
")",
"{",
"final",
"StringBuilder",
"sql",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sql",
".",
"append",
"(",
"\" PRIMARY KEY\"",
")",
";",
... | the keyDefinitionList tableSql.
@param keyDefinitionList keyDefinitionList
@return createKeyDefinitionsql | [
"the",
"keyDefinitionList",
"tableSql",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-repository-sqlserver/src/main/java/org/b3log/latke/repository/sqlserver/SQLServerJdbcDatabaseSolution.java#L170-L189 | train |
b3log/latke | latke-core/src/main/java/org/json/Cookie.java | Cookie.escape | public static String escape(String string) {
char c;
String s = string.trim();
int length = s.length();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} | java | public static String escape(String string) {
char c;
String s = string.trim();
int length = s.length();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} | [
"public",
"static",
"String",
"escape",
"(",
"String",
"string",
")",
"{",
"char",
"c",
";",
"String",
"s",
"=",
"string",
".",
"trim",
"(",
")",
";",
"int",
"length",
"=",
"s",
".",
"length",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"Stri... | Produce a copy of a string in which the characters '+', '%', '=', ';'
and control characters are replaced with "%hh". This is a gentle form
of URL encoding, attempting to cause as little distortion to the
string as possible. The characters '=' and ';' are meta characters in
cookies. By convention, they are escaped using the URL-encoding. This is
only a convention, not a standard. Often, cookies are expected to have
encoded values. We encode '=' and ';' because we must. We encode '%' and
'+' because they are meta characters in URL encoding.
@param string The source string.
@return The escaped result. | [
"Produce",
"a",
"copy",
"of",
"a",
"string",
"in",
"which",
"the",
"characters",
"+",
"%",
"=",
";",
"and",
"control",
"characters",
"are",
"replaced",
"with",
"%hh",
".",
"This",
"is",
"a",
"gentle",
"form",
"of",
"URL",
"encoding",
"attempting",
"to",
... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/Cookie.java#L47-L63 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java | SingletonContext.getReference | private <T> T getReference(final Bean<T> bean) {
T ret = (T) beanReferences.get(bean);
if (null != ret) {
return ret;
}
ret = bean.create();
if (null != ret) {
beanReferences.put(bean, ret);
return ret;
}
throw new RuntimeException("Can't create reference for bean [" + bean + "]");
} | java | private <T> T getReference(final Bean<T> bean) {
T ret = (T) beanReferences.get(bean);
if (null != ret) {
return ret;
}
ret = bean.create();
if (null != ret) {
beanReferences.put(bean, ret);
return ret;
}
throw new RuntimeException("Can't create reference for bean [" + bean + "]");
} | [
"private",
"<",
"T",
">",
"T",
"getReference",
"(",
"final",
"Bean",
"<",
"T",
">",
"bean",
")",
"{",
"T",
"ret",
"=",
"(",
"T",
")",
"beanReferences",
".",
"get",
"(",
"bean",
")",
";",
"if",
"(",
"null",
"!=",
"ret",
")",
"{",
"return",
"ret"... | Gets reference of the specified bean and creational context.
@param <T> the type of contextual
@param bean the specified bean
@return reference | [
"Gets",
"reference",
"of",
"the",
"specified",
"bean",
"and",
"creational",
"context",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java#L60-L76 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java | SingletonContext.destroyReference | private <T> void destroyReference(final Bean<T> bean, final T beanInstance) {
bean.destroy(beanInstance);
} | java | private <T> void destroyReference(final Bean<T> bean, final T beanInstance) {
bean.destroy(beanInstance);
} | [
"private",
"<",
"T",
">",
"void",
"destroyReference",
"(",
"final",
"Bean",
"<",
"T",
">",
"bean",
",",
"final",
"T",
"beanInstance",
")",
"{",
"bean",
".",
"destroy",
"(",
"beanInstance",
")",
";",
"}"
] | Destroys the specified bean's instance.
@param <T> the type of contextual
@param bean the specified bean
@param beanInstance the specified bean's instance | [
"Destroys",
"the",
"specified",
"bean",
"s",
"instance",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/SingletonContext.java#L104-L106 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.dispose | public static void dispose() {
final JdbcTransaction jdbcTransaction = TX.get();
if (null != jdbcTransaction && jdbcTransaction.getConnection() != null) {
jdbcTransaction.dispose();
}
final Connection connection = CONN.get();
if (null != connection) {
try {
connection.close();
} catch (final SQLException e) {
throw new RuntimeException("Close connection failed", e);
} finally {
CONN.set(null);
}
}
} | java | public static void dispose() {
final JdbcTransaction jdbcTransaction = TX.get();
if (null != jdbcTransaction && jdbcTransaction.getConnection() != null) {
jdbcTransaction.dispose();
}
final Connection connection = CONN.get();
if (null != connection) {
try {
connection.close();
} catch (final SQLException e) {
throw new RuntimeException("Close connection failed", e);
} finally {
CONN.set(null);
}
}
} | [
"public",
"static",
"void",
"dispose",
"(",
")",
"{",
"final",
"JdbcTransaction",
"jdbcTransaction",
"=",
"TX",
".",
"get",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"jdbcTransaction",
"&&",
"jdbcTransaction",
".",
"getConnection",
"(",
")",
"!=",
"null",
")... | Disposes the resources. | [
"Disposes",
"the",
"resources",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L114-L131 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.update | private void update(final String id, final JSONObject oldJsonObject, final JSONObject jsonObject,
final List<Object> paramList, final StringBuilder sql) throws JSONException {
final JSONObject needUpdateJsonObject = getNeedUpdateJsonObject(oldJsonObject, jsonObject);
if (0 == needUpdateJsonObject.length()) {
LOGGER.log(Level.TRACE, "Nothing to update [{0}] for repository [{1}]", id, getName());
return;
}
setUpdateProperties(id, needUpdateJsonObject, paramList, sql);
} | java | private void update(final String id, final JSONObject oldJsonObject, final JSONObject jsonObject,
final List<Object> paramList, final StringBuilder sql) throws JSONException {
final JSONObject needUpdateJsonObject = getNeedUpdateJsonObject(oldJsonObject, jsonObject);
if (0 == needUpdateJsonObject.length()) {
LOGGER.log(Level.TRACE, "Nothing to update [{0}] for repository [{1}]", id, getName());
return;
}
setUpdateProperties(id, needUpdateJsonObject, paramList, sql);
} | [
"private",
"void",
"update",
"(",
"final",
"String",
"id",
",",
"final",
"JSONObject",
"oldJsonObject",
",",
"final",
"JSONObject",
"jsonObject",
",",
"final",
"List",
"<",
"Object",
">",
"paramList",
",",
"final",
"StringBuilder",
"sql",
")",
"throws",
"JSONE... | Compares the specified old json object and new json object, updates it if need.
@param id id
@param oldJsonObject the specified old json object
@param jsonObject the specified new json object
@param paramList paramList
@param sql sql
@throws JSONException JSONException | [
"Compares",
"the",
"specified",
"old",
"json",
"object",
"and",
"new",
"json",
"object",
"updates",
"it",
"if",
"need",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L275-L285 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.getNeedUpdateJsonObject | private JSONObject getNeedUpdateJsonObject(final JSONObject oldJsonObject, final JSONObject jsonObject) throws JSONException {
if (null == oldJsonObject) {
return jsonObject;
}
final JSONObject ret = new JSONObject();
final Iterator<String> keys = jsonObject.keys();
String key;
while (keys.hasNext()) {
key = keys.next();
if (null == jsonObject.get(key) && null == oldJsonObject.get(key)) {
ret.put(key, jsonObject.get(key));
} else if (!jsonObject.optString(key).equals(oldJsonObject.optString(key))) {
ret.put(key, jsonObject.get(key));
}
}
return ret;
} | java | private JSONObject getNeedUpdateJsonObject(final JSONObject oldJsonObject, final JSONObject jsonObject) throws JSONException {
if (null == oldJsonObject) {
return jsonObject;
}
final JSONObject ret = new JSONObject();
final Iterator<String> keys = jsonObject.keys();
String key;
while (keys.hasNext()) {
key = keys.next();
if (null == jsonObject.get(key) && null == oldJsonObject.get(key)) {
ret.put(key, jsonObject.get(key));
} else if (!jsonObject.optString(key).equals(oldJsonObject.optString(key))) {
ret.put(key, jsonObject.get(key));
}
}
return ret;
} | [
"private",
"JSONObject",
"getNeedUpdateJsonObject",
"(",
"final",
"JSONObject",
"oldJsonObject",
",",
"final",
"JSONObject",
"jsonObject",
")",
"throws",
"JSONException",
"{",
"if",
"(",
"null",
"==",
"oldJsonObject",
")",
"{",
"return",
"jsonObject",
";",
"}",
"f... | Compares the specified old json object and the new json object, returns diff object for updating.
@param oldJsonObject the specified old json object
@param jsonObject the specified new json object
@return diff object for updating
@throws JSONException jsonObject | [
"Compares",
"the",
"specified",
"old",
"json",
"object",
"and",
"the",
"new",
"json",
"object",
"returns",
"diff",
"object",
"for",
"updating",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L329-L347 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.remove | private void remove(final String id, final StringBuilder sql) {
sql.append("DELETE FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = '").
append(id).append("'");
} | java | private void remove(final String id, final StringBuilder sql) {
sql.append("DELETE FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = '").
append(id).append("'");
} | [
"private",
"void",
"remove",
"(",
"final",
"String",
"id",
",",
"final",
"StringBuilder",
"sql",
")",
"{",
"sql",
".",
"append",
"(",
"\"DELETE FROM \"",
")",
".",
"append",
"(",
"getName",
"(",
")",
")",
".",
"append",
"(",
"\" WHERE \"",
")",
".",
"a... | Removes an record.
@param id id
@param sql sql | [
"Removes",
"an",
"record",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L400-L403 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.buildSQLCount | private Map<String, Object> buildSQLCount(final int currentPageNum, final int pageSize, final int pageCount,
final Query query, final StringBuilder sqlBuilder, final List<Object> paramList) throws RepositoryException {
final Map<String, Object> ret = new HashMap<>();
int pageCnt = pageCount;
int recordCnt = 0;
final StringBuilder selectBuilder = new StringBuilder();
final StringBuilder whereBuilder = new StringBuilder();
final StringBuilder orderByBuilder = new StringBuilder();
buildSelect(selectBuilder, query.getProjections());
buildWhere(whereBuilder, paramList, query.getFilter());
buildOrderBy(orderByBuilder, query.getSorts());
if (-1 == pageCount) {
final StringBuilder countBuilder = new StringBuilder("SELECT COUNT(" + JdbcRepositories.getDefaultKeyName() + ") FROM ").append(getName());
if (StringUtils.isNotBlank(whereBuilder.toString())) {
countBuilder.append(" WHERE ").append(whereBuilder);
}
recordCnt = (int) count(countBuilder, paramList);
if (0 == recordCnt) {
ret.put(Pagination.PAGINATION_PAGE_COUNT, 0);
ret.put(Pagination.PAGINATION_RECORD_COUNT, 0);
return ret;
}
pageCnt = (int) Math.ceil((double) recordCnt / (double) pageSize);
}
ret.put(Pagination.PAGINATION_PAGE_COUNT, pageCnt);
ret.put(Pagination.PAGINATION_RECORD_COUNT, recordCnt);
final int start = (currentPageNum - 1) * pageSize;
final int end = start + pageSize;
sqlBuilder.append(JdbcFactory.getInstance().
queryPage(start, end, selectBuilder.toString(), whereBuilder.toString(), orderByBuilder.toString(), getName()));
return ret;
} | java | private Map<String, Object> buildSQLCount(final int currentPageNum, final int pageSize, final int pageCount,
final Query query, final StringBuilder sqlBuilder, final List<Object> paramList) throws RepositoryException {
final Map<String, Object> ret = new HashMap<>();
int pageCnt = pageCount;
int recordCnt = 0;
final StringBuilder selectBuilder = new StringBuilder();
final StringBuilder whereBuilder = new StringBuilder();
final StringBuilder orderByBuilder = new StringBuilder();
buildSelect(selectBuilder, query.getProjections());
buildWhere(whereBuilder, paramList, query.getFilter());
buildOrderBy(orderByBuilder, query.getSorts());
if (-1 == pageCount) {
final StringBuilder countBuilder = new StringBuilder("SELECT COUNT(" + JdbcRepositories.getDefaultKeyName() + ") FROM ").append(getName());
if (StringUtils.isNotBlank(whereBuilder.toString())) {
countBuilder.append(" WHERE ").append(whereBuilder);
}
recordCnt = (int) count(countBuilder, paramList);
if (0 == recordCnt) {
ret.put(Pagination.PAGINATION_PAGE_COUNT, 0);
ret.put(Pagination.PAGINATION_RECORD_COUNT, 0);
return ret;
}
pageCnt = (int) Math.ceil((double) recordCnt / (double) pageSize);
}
ret.put(Pagination.PAGINATION_PAGE_COUNT, pageCnt);
ret.put(Pagination.PAGINATION_RECORD_COUNT, recordCnt);
final int start = (currentPageNum - 1) * pageSize;
final int end = start + pageSize;
sqlBuilder.append(JdbcFactory.getInstance().
queryPage(start, end, selectBuilder.toString(), whereBuilder.toString(), orderByBuilder.toString(), getName()));
return ret;
} | [
"private",
"Map",
"<",
"String",
",",
"Object",
">",
"buildSQLCount",
"(",
"final",
"int",
"currentPageNum",
",",
"final",
"int",
"pageSize",
",",
"final",
"int",
"pageCount",
",",
"final",
"Query",
"query",
",",
"final",
"StringBuilder",
"sqlBuilder",
",",
... | Builds query SQL and count result.
@param currentPageNum currentPageNum
@param pageSize pageSize
@param pageCount if the pageCount specified with {@code -1}, the returned (pageCnt, recordCnt) value will be
calculated, otherwise, the returned pageCnt will be this pageCount, and recordCnt will be {@code 0}, means these
values will not be calculated
@param query query
@param sqlBuilder the specified SQL builder
@param paramList paramList
@return <pageCnt, Integer>,<br/>
<recordCnt, Integer><br/>
@throws RepositoryException RepositoryException | [
"Builds",
"query",
"SQL",
"and",
"count",
"result",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L533-L573 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.buildSelect | private void buildSelect(final StringBuilder selectBuilder, final List<Projection> projections) {
selectBuilder.append("SELECT ");
if (null == projections || projections.isEmpty()) {
selectBuilder.append(" * ");
return;
}
selectBuilder.append(projections.stream().map(Projection::getKey).collect(Collectors.joining(", ")));
} | java | private void buildSelect(final StringBuilder selectBuilder, final List<Projection> projections) {
selectBuilder.append("SELECT ");
if (null == projections || projections.isEmpty()) {
selectBuilder.append(" * ");
return;
}
selectBuilder.append(projections.stream().map(Projection::getKey).collect(Collectors.joining(", ")));
} | [
"private",
"void",
"buildSelect",
"(",
"final",
"StringBuilder",
"selectBuilder",
",",
"final",
"List",
"<",
"Projection",
">",
"projections",
")",
"{",
"selectBuilder",
".",
"append",
"(",
"\"SELECT \"",
")",
";",
"if",
"(",
"null",
"==",
"projections",
"||",... | Builds 'SELECT' part with the specified select build and projections.
@param selectBuilder the specified select builder
@param projections the specified projections | [
"Builds",
"SELECT",
"part",
"with",
"the",
"specified",
"select",
"build",
"and",
"projections",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L581-L590 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.buildWhere | private void buildWhere(final StringBuilder whereBuilder, final List<Object> paramList, final Filter filter) throws RepositoryException {
if (null == filter) {
return;
}
if (filter instanceof PropertyFilter) {
processPropertyFilter(whereBuilder, paramList, (PropertyFilter) filter);
} else { // CompositeFiler
processCompositeFilter(whereBuilder, paramList, (CompositeFilter) filter);
}
} | java | private void buildWhere(final StringBuilder whereBuilder, final List<Object> paramList, final Filter filter) throws RepositoryException {
if (null == filter) {
return;
}
if (filter instanceof PropertyFilter) {
processPropertyFilter(whereBuilder, paramList, (PropertyFilter) filter);
} else { // CompositeFiler
processCompositeFilter(whereBuilder, paramList, (CompositeFilter) filter);
}
} | [
"private",
"void",
"buildWhere",
"(",
"final",
"StringBuilder",
"whereBuilder",
",",
"final",
"List",
"<",
"Object",
">",
"paramList",
",",
"final",
"Filter",
"filter",
")",
"throws",
"RepositoryException",
"{",
"if",
"(",
"null",
"==",
"filter",
")",
"{",
"... | Builds 'WHERE' part with the specified where build, param list and filter.
@param whereBuilder the specified where builder
@param paramList the specified param list
@param filter the specified filter
@throws RepositoryException RepositoryException | [
"Builds",
"WHERE",
"part",
"with",
"the",
"specified",
"where",
"build",
"param",
"list",
"and",
"filter",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L601-L611 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.buildOrderBy | private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) {
boolean isFirst = true;
String querySortDirection;
for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) {
if (isFirst) {
orderByBuilder.append(" ORDER BY ");
isFirst = false;
} else {
orderByBuilder.append(", ");
}
if (sort.getValue().equals(SortDirection.ASCENDING)) {
querySortDirection = "ASC";
} else {
querySortDirection = "DESC";
}
orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection);
}
} | java | private void buildOrderBy(final StringBuilder orderByBuilder, final Map<String, SortDirection> sorts) {
boolean isFirst = true;
String querySortDirection;
for (final Map.Entry<String, SortDirection> sort : sorts.entrySet()) {
if (isFirst) {
orderByBuilder.append(" ORDER BY ");
isFirst = false;
} else {
orderByBuilder.append(", ");
}
if (sort.getValue().equals(SortDirection.ASCENDING)) {
querySortDirection = "ASC";
} else {
querySortDirection = "DESC";
}
orderByBuilder.append(sort.getKey()).append(" ").append(querySortDirection);
}
} | [
"private",
"void",
"buildOrderBy",
"(",
"final",
"StringBuilder",
"orderByBuilder",
",",
"final",
"Map",
"<",
"String",
",",
"SortDirection",
">",
"sorts",
")",
"{",
"boolean",
"isFirst",
"=",
"true",
";",
"String",
"querySortDirection",
";",
"for",
"(",
"fina... | Builds 'ORDER BY' part with the specified order by build and sorts.
@param orderByBuilder the specified order by builder
@param sorts the specified sorts | [
"Builds",
"ORDER",
"BY",
"part",
"with",
"the",
"specified",
"order",
"by",
"build",
"and",
"sorts",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L619-L638 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.getConnection | private Connection getConnection() {
final JdbcTransaction jdbcTransaction = TX.get();
if (null != jdbcTransaction && jdbcTransaction.isActive()) {
return jdbcTransaction.getConnection();
}
Connection ret = CONN.get();
try {
if (null != ret && !ret.isClosed()) {
return ret;
}
ret = Connections.getConnection();
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Gets a connection failed", e);
}
CONN.set(ret);
return ret;
} | java | private Connection getConnection() {
final JdbcTransaction jdbcTransaction = TX.get();
if (null != jdbcTransaction && jdbcTransaction.isActive()) {
return jdbcTransaction.getConnection();
}
Connection ret = CONN.get();
try {
if (null != ret && !ret.isClosed()) {
return ret;
}
ret = Connections.getConnection();
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Gets a connection failed", e);
}
CONN.set(ret);
return ret;
} | [
"private",
"Connection",
"getConnection",
"(",
")",
"{",
"final",
"JdbcTransaction",
"jdbcTransaction",
"=",
"TX",
".",
"get",
"(",
")",
";",
"if",
"(",
"null",
"!=",
"jdbcTransaction",
"&&",
"jdbcTransaction",
".",
"isActive",
"(",
")",
")",
"{",
"return",
... | getConnection. default using current JdbcTransaction's connection, if null get a new one.
@return {@link Connection} | [
"getConnection",
".",
"default",
"using",
"current",
"JdbcTransaction",
"s",
"connection",
"if",
"null",
"get",
"a",
"new",
"one",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L787-L807 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.processPropertyFilter | private void processPropertyFilter(final StringBuilder whereBuilder,
final List<Object> paramList, final PropertyFilter propertyFilter) throws RepositoryException {
String filterOperator;
switch (propertyFilter.getOperator()) {
case EQUAL:
filterOperator = "=";
break;
case GREATER_THAN:
filterOperator = ">";
break;
case GREATER_THAN_OR_EQUAL:
filterOperator = ">=";
break;
case LESS_THAN:
filterOperator = "<";
break;
case LESS_THAN_OR_EQUAL:
filterOperator = "<=";
break;
case NOT_EQUAL:
filterOperator = "!=";
break;
case IN:
filterOperator = "IN";
break;
case LIKE:
filterOperator = "LIKE";
break;
case NOT_LIKE:
filterOperator = "NOT LIKE";
break;
default:
throw new RepositoryException("Unsupported filter operator [" + propertyFilter.getOperator() + "]");
}
if (FilterOperator.IN != propertyFilter.getOperator()) {
whereBuilder.append(propertyFilter.getKey()).append(" ").append(filterOperator).append(" ?");
paramList.add(propertyFilter.getValue());
} else {
final Collection<Object> objects = (Collection<Object>) propertyFilter.getValue();
boolean isSubFist = true;
if (objects != null && !objects.isEmpty()) {
whereBuilder.append(propertyFilter.getKey()).append(" IN ");
final Iterator<Object> obs = objects.iterator();
while (obs.hasNext()) {
if (isSubFist) {
whereBuilder.append("(");
isSubFist = false;
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
paramList.add(obs.next());
if (!obs.hasNext()) {
whereBuilder.append(") ");
}
}
} else { // in () => 1!=1
whereBuilder.append("1 != 1");
}
}
} | java | private void processPropertyFilter(final StringBuilder whereBuilder,
final List<Object> paramList, final PropertyFilter propertyFilter) throws RepositoryException {
String filterOperator;
switch (propertyFilter.getOperator()) {
case EQUAL:
filterOperator = "=";
break;
case GREATER_THAN:
filterOperator = ">";
break;
case GREATER_THAN_OR_EQUAL:
filterOperator = ">=";
break;
case LESS_THAN:
filterOperator = "<";
break;
case LESS_THAN_OR_EQUAL:
filterOperator = "<=";
break;
case NOT_EQUAL:
filterOperator = "!=";
break;
case IN:
filterOperator = "IN";
break;
case LIKE:
filterOperator = "LIKE";
break;
case NOT_LIKE:
filterOperator = "NOT LIKE";
break;
default:
throw new RepositoryException("Unsupported filter operator [" + propertyFilter.getOperator() + "]");
}
if (FilterOperator.IN != propertyFilter.getOperator()) {
whereBuilder.append(propertyFilter.getKey()).append(" ").append(filterOperator).append(" ?");
paramList.add(propertyFilter.getValue());
} else {
final Collection<Object> objects = (Collection<Object>) propertyFilter.getValue();
boolean isSubFist = true;
if (objects != null && !objects.isEmpty()) {
whereBuilder.append(propertyFilter.getKey()).append(" IN ");
final Iterator<Object> obs = objects.iterator();
while (obs.hasNext()) {
if (isSubFist) {
whereBuilder.append("(");
isSubFist = false;
} else {
whereBuilder.append(",");
}
whereBuilder.append("?");
paramList.add(obs.next());
if (!obs.hasNext()) {
whereBuilder.append(") ");
}
}
} else { // in () => 1!=1
whereBuilder.append("1 != 1");
}
}
} | [
"private",
"void",
"processPropertyFilter",
"(",
"final",
"StringBuilder",
"whereBuilder",
",",
"final",
"List",
"<",
"Object",
">",
"paramList",
",",
"final",
"PropertyFilter",
"propertyFilter",
")",
"throws",
"RepositoryException",
"{",
"String",
"filterOperator",
"... | Processes property filter.
@param whereBuilder the specified where builder
@param paramList the specified parameter list
@param propertyFilter the specified property filter
@throws RepositoryException repository exception | [
"Processes",
"property",
"filter",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L817-L893 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.processCompositeFilter | private void processCompositeFilter(final StringBuilder whereBuilder,
final List<Object> paramList, final CompositeFilter compositeFilter) throws RepositoryException {
final List<Filter> subFilters = compositeFilter.getSubFilters();
if (2 > subFilters.size()) {
throw new RepositoryException("At least two sub filters in a composite filter");
}
whereBuilder.append("(");
final Iterator<Filter> iterator = subFilters.iterator();
while (iterator.hasNext()) {
final Filter filter = iterator.next();
if (filter instanceof PropertyFilter) {
processPropertyFilter(whereBuilder, paramList, (PropertyFilter) filter);
} else { // CompositeFilter
processCompositeFilter(whereBuilder, paramList, (CompositeFilter) filter);
}
if (iterator.hasNext()) {
switch (compositeFilter.getOperator()) {
case AND:
whereBuilder.append(" AND ");
break;
case OR:
whereBuilder.append(" OR ");
break;
default:
throw new RepositoryException("Unsupported composite filter [operator=" + compositeFilter.getOperator() + "]");
}
}
}
whereBuilder.append(")");
} | java | private void processCompositeFilter(final StringBuilder whereBuilder,
final List<Object> paramList, final CompositeFilter compositeFilter) throws RepositoryException {
final List<Filter> subFilters = compositeFilter.getSubFilters();
if (2 > subFilters.size()) {
throw new RepositoryException("At least two sub filters in a composite filter");
}
whereBuilder.append("(");
final Iterator<Filter> iterator = subFilters.iterator();
while (iterator.hasNext()) {
final Filter filter = iterator.next();
if (filter instanceof PropertyFilter) {
processPropertyFilter(whereBuilder, paramList, (PropertyFilter) filter);
} else { // CompositeFilter
processCompositeFilter(whereBuilder, paramList, (CompositeFilter) filter);
}
if (iterator.hasNext()) {
switch (compositeFilter.getOperator()) {
case AND:
whereBuilder.append(" AND ");
break;
case OR:
whereBuilder.append(" OR ");
break;
default:
throw new RepositoryException("Unsupported composite filter [operator=" + compositeFilter.getOperator() + "]");
}
}
}
whereBuilder.append(")");
} | [
"private",
"void",
"processCompositeFilter",
"(",
"final",
"StringBuilder",
"whereBuilder",
",",
"final",
"List",
"<",
"Object",
">",
"paramList",
",",
"final",
"CompositeFilter",
"compositeFilter",
")",
"throws",
"RepositoryException",
"{",
"final",
"List",
"<",
"F... | Processes composite filter.
@param whereBuilder the specified where builder
@param paramList the specified parameter list
@param compositeFilter the specified composite filter
@throws RepositoryException repository exception | [
"Processes",
"composite",
"filter",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L903-L939 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java | JdbcRepository.toOracleClobEmpty | private static void toOracleClobEmpty(final JSONObject jsonObject) {
final Iterator<String> keys = jsonObject.keys();
try {
while (keys.hasNext()) {
final String name = keys.next();
final Object val = jsonObject.get(name);
if (val instanceof String) {
final String valStr = (String) val;
if (StringUtils.isBlank(valStr)) {
jsonObject.put(name, ORA_EMPTY_STR);
}
}
}
} catch (final JSONException e) {
LOGGER.log(Level.ERROR, "Process oracle clob empty failed", e);
}
} | java | private static void toOracleClobEmpty(final JSONObject jsonObject) {
final Iterator<String> keys = jsonObject.keys();
try {
while (keys.hasNext()) {
final String name = keys.next();
final Object val = jsonObject.get(name);
if (val instanceof String) {
final String valStr = (String) val;
if (StringUtils.isBlank(valStr)) {
jsonObject.put(name, ORA_EMPTY_STR);
}
}
}
} catch (final JSONException e) {
LOGGER.log(Level.ERROR, "Process oracle clob empty failed", e);
}
} | [
"private",
"static",
"void",
"toOracleClobEmpty",
"(",
"final",
"JSONObject",
"jsonObject",
")",
"{",
"final",
"Iterator",
"<",
"String",
">",
"keys",
"=",
"jsonObject",
".",
"keys",
"(",
")",
";",
"try",
"{",
"while",
"(",
"keys",
".",
"hasNext",
"(",
"... | Process Oracle CLOB empty string.
@param jsonObject the specified JSON object | [
"Process",
"Oracle",
"CLOB",
"empty",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/JdbcRepository.java#L951-L967 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/event/EventManager.java | EventManager.fireEventAsynchronously | public <T> Future<T> fireEventAsynchronously(final Event<?> event) {
final FutureTask<T> futureTask = new FutureTask<T>(() -> {
synchronizedEventQueue.fireEvent(event);
return null; // XXX: Our future????
});
Latkes.EXECUTOR_SERVICE.execute(futureTask);
return futureTask;
} | java | public <T> Future<T> fireEventAsynchronously(final Event<?> event) {
final FutureTask<T> futureTask = new FutureTask<T>(() -> {
synchronizedEventQueue.fireEvent(event);
return null; // XXX: Our future????
});
Latkes.EXECUTOR_SERVICE.execute(futureTask);
return futureTask;
} | [
"public",
"<",
"T",
">",
"Future",
"<",
"T",
">",
"fireEventAsynchronously",
"(",
"final",
"Event",
"<",
"?",
">",
"event",
")",
"{",
"final",
"FutureTask",
"<",
"T",
">",
"futureTask",
"=",
"new",
"FutureTask",
"<",
"T",
">",
"(",
"(",
")",
"->",
... | Fire the specified event asynchronously.
@param <T> the result type
@param event the specified event
@return future result | [
"Fire",
"the",
"specified",
"event",
"asynchronously",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/event/EventManager.java#L54-L64 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/Repositories.java | Repositories.setRepositoriesWritable | public static void setRepositoriesWritable(final boolean writable) {
for (final Map.Entry<String, Repository> entry : REPOS_HOLDER.entrySet()) {
final String repositoryName = entry.getKey();
final Repository repository = entry.getValue();
repository.setWritable(writable);
LOGGER.log(Level.INFO, "Sets repository[name={0}] writable[{1}]", new Object[]{repositoryName, writable});
}
repositoryiesWritable = writable;
} | java | public static void setRepositoriesWritable(final boolean writable) {
for (final Map.Entry<String, Repository> entry : REPOS_HOLDER.entrySet()) {
final String repositoryName = entry.getKey();
final Repository repository = entry.getValue();
repository.setWritable(writable);
LOGGER.log(Level.INFO, "Sets repository[name={0}] writable[{1}]", new Object[]{repositoryName, writable});
}
repositoryiesWritable = writable;
} | [
"public",
"static",
"void",
"setRepositoriesWritable",
"(",
"final",
"boolean",
"writable",
")",
"{",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"String",
",",
"Repository",
">",
"entry",
":",
"REPOS_HOLDER",
".",
"entrySet",
"(",
")",
")",
"{",
"final... | Sets all repositories whether is writable with the specified flag.
@param writable the specified flat, {@code true} for writable, {@code false} otherwise | [
"Sets",
"all",
"repositories",
"whether",
"is",
"writable",
"with",
"the",
"specified",
"flag",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/Repositories.java#L85-L96 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/Repositories.java | Repositories.getRepositoryNames | public static JSONArray getRepositoryNames() {
final JSONArray ret = new JSONArray();
if (null == repositoriesDescription) {
LOGGER.log(Level.INFO, "Not found repository description[repository.json] file under classpath");
return ret;
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
ret.put(repository.optString("name"));
}
return ret;
} | java | public static JSONArray getRepositoryNames() {
final JSONArray ret = new JSONArray();
if (null == repositoriesDescription) {
LOGGER.log(Level.INFO, "Not found repository description[repository.json] file under classpath");
return ret;
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
ret.put(repository.optString("name"));
}
return ret;
} | [
"public",
"static",
"JSONArray",
"getRepositoryNames",
"(",
")",
"{",
"final",
"JSONArray",
"ret",
"=",
"new",
"JSONArray",
"(",
")",
";",
"if",
"(",
"null",
"==",
"repositoriesDescription",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
... | Gets repository names.
@return repository names, for example,
<pre>
[
"repository1", "repository2", ....
]
</pre> | [
"Gets",
"repository",
"names",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/Repositories.java#L108-L126 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/Repositories.java | Repositories.getRepositoryDef | public static JSONObject getRepositoryDef(final String repositoryName) {
if (StringUtils.isBlank(repositoryName)) {
return null;
}
if (null == repositoriesDescription) {
return null;
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
if (repositoryName.equals(repository.optString("name"))) {
return repository;
}
}
throw new RuntimeException("Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json");
} | java | public static JSONObject getRepositoryDef(final String repositoryName) {
if (StringUtils.isBlank(repositoryName)) {
return null;
}
if (null == repositoriesDescription) {
return null;
}
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
if (repositoryName.equals(repository.optString("name"))) {
return repository;
}
}
throw new RuntimeException("Not found the repository [name=" + repositoryName + "] definition, please define it in repositories.json");
} | [
"public",
"static",
"JSONObject",
"getRepositoryDef",
"(",
"final",
"String",
"repositoryName",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"repositoryName",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"null",
"==",
"repositoriesDescript... | Gets the repository definition of an repository specified by the given repository name.
@param repositoryName the given repository name (maybe with table name prefix)
@return repository definition, returns {@code null} if not found | [
"Gets",
"the",
"repository",
"definition",
"of",
"an",
"repository",
"specified",
"by",
"the",
"given",
"repository",
"name",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/Repositories.java#L230-L248 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/Repositories.java | Repositories.loadRepositoryDescription | private static void loadRepositoryDescription() {
LOGGER.log(Level.INFO, "Loading repository description....");
final InputStream inputStream = AbstractRepository.class.getResourceAsStream("/repository.json");
if (null == inputStream) {
LOGGER.log(Level.INFO, "Not found repository description [repository.json] file under classpath");
return;
}
LOGGER.log(Level.INFO, "Parsing repository description....");
try {
final String description = IOUtils.toString(inputStream, "UTF-8");
LOGGER.log(Level.DEBUG, "{0}{1}", new Object[]{Strings.LINE_SEPARATOR, description});
repositoriesDescription = new JSONObject(description);
// Repository name prefix
final String tableNamePrefix = StringUtils.isNotBlank(Latkes.getLocalProperty("jdbc.tablePrefix"))
? Latkes.getLocalProperty("jdbc.tablePrefix") + "_"
: "";
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
repository.put("name", tableNamePrefix + repository.optString("name"));
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Parses repository description failed", e);
} finally {
try {
inputStream.close();
} catch (final IOException e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
throw new RuntimeException(e);
}
}
} | java | private static void loadRepositoryDescription() {
LOGGER.log(Level.INFO, "Loading repository description....");
final InputStream inputStream = AbstractRepository.class.getResourceAsStream("/repository.json");
if (null == inputStream) {
LOGGER.log(Level.INFO, "Not found repository description [repository.json] file under classpath");
return;
}
LOGGER.log(Level.INFO, "Parsing repository description....");
try {
final String description = IOUtils.toString(inputStream, "UTF-8");
LOGGER.log(Level.DEBUG, "{0}{1}", new Object[]{Strings.LINE_SEPARATOR, description});
repositoriesDescription = new JSONObject(description);
// Repository name prefix
final String tableNamePrefix = StringUtils.isNotBlank(Latkes.getLocalProperty("jdbc.tablePrefix"))
? Latkes.getLocalProperty("jdbc.tablePrefix") + "_"
: "";
final JSONArray repositories = repositoriesDescription.optJSONArray("repositories");
for (int i = 0; i < repositories.length(); i++) {
final JSONObject repository = repositories.optJSONObject(i);
repository.put("name", tableNamePrefix + repository.optString("name"));
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Parses repository description failed", e);
} finally {
try {
inputStream.close();
} catch (final IOException e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
throw new RuntimeException(e);
}
}
} | [
"private",
"static",
"void",
"loadRepositoryDescription",
"(",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Loading repository description....\"",
")",
";",
"final",
"InputStream",
"inputStream",
"=",
"AbstractRepository",
".",
"class",
".",
... | Loads repository description. | [
"Loads",
"repository",
"description",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/Repositories.java#L298-L339 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/servlet/AbstractServletListener.java | AbstractServletListener.contextInitialized | @Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
servletContext = servletContextEvent.getServletContext();
Latkes.init();
LOGGER.info("Initializing the context....");
Latkes.setLocale(Locale.SIMPLIFIED_CHINESE);
LOGGER.log(Level.INFO, "Default locale [{0}]", Latkes.getLocale());
final String realPath = servletContext.getRealPath("/");
LOGGER.log(Level.INFO, "Server [realPath={0}, contextPath={1}]", realPath, servletContext.getContextPath());
try {
final Collection<Class<?>> beanClasses = Discoverer.discover(Latkes.getScanPath());
BeanManager.start(beanClasses);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Initializes request processors failed", e);
throw new IllegalStateException("Initializes request processors failed");
}
} | java | @Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
servletContext = servletContextEvent.getServletContext();
Latkes.init();
LOGGER.info("Initializing the context....");
Latkes.setLocale(Locale.SIMPLIFIED_CHINESE);
LOGGER.log(Level.INFO, "Default locale [{0}]", Latkes.getLocale());
final String realPath = servletContext.getRealPath("/");
LOGGER.log(Level.INFO, "Server [realPath={0}, contextPath={1}]", realPath, servletContext.getContextPath());
try {
final Collection<Class<?>> beanClasses = Discoverer.discover(Latkes.getScanPath());
BeanManager.start(beanClasses);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Initializes request processors failed", e);
throw new IllegalStateException("Initializes request processors failed");
}
} | [
"@",
"Override",
"public",
"void",
"contextInitialized",
"(",
"final",
"ServletContextEvent",
"servletContextEvent",
")",
"{",
"servletContext",
"=",
"servletContextEvent",
".",
"getServletContext",
"(",
")",
";",
"Latkes",
".",
"init",
"(",
")",
";",
"LOGGER",
".... | Initializes context, locale and runtime environment.
@param servletContextEvent servlet context event | [
"Initializes",
"context",
"locale",
"and",
"runtime",
"environment",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/servlet/AbstractServletListener.java#L72-L93 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Bean.java | Bean.resolveDependencies | private void resolveDependencies(final Object reference) {
final Class<?> superclass = reference.getClass().getSuperclass().getSuperclass(); // Proxy -> Orig -> Super
resolveSuperclassFieldDependencies(reference, superclass);
resolveCurrentclassFieldDependencies(reference);
} | java | private void resolveDependencies(final Object reference) {
final Class<?> superclass = reference.getClass().getSuperclass().getSuperclass(); // Proxy -> Orig -> Super
resolveSuperclassFieldDependencies(reference, superclass);
resolveCurrentclassFieldDependencies(reference);
} | [
"private",
"void",
"resolveDependencies",
"(",
"final",
"Object",
"reference",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"superclass",
"=",
"reference",
".",
"getClass",
"(",
")",
".",
"getSuperclass",
"(",
")",
".",
"getSuperclass",
"(",
")",
";",
"// Pr... | Resolves dependencies for the specified reference.
@param reference the specified reference | [
"Resolves",
"dependencies",
"for",
"the",
"specified",
"reference",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Bean.java#L136-L141 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Bean.java | Bean.instantiateReference | private T instantiateReference() throws Exception {
final T ret = proxyClass.newInstance();
((ProxyObject) ret).setHandler(javassistMethodHandler);
LOGGER.log(Level.TRACE, "Uses Javassist method handler for bean [class={0}]", beanClass.getName());
return ret;
} | java | private T instantiateReference() throws Exception {
final T ret = proxyClass.newInstance();
((ProxyObject) ret).setHandler(javassistMethodHandler);
LOGGER.log(Level.TRACE, "Uses Javassist method handler for bean [class={0}]", beanClass.getName());
return ret;
} | [
"private",
"T",
"instantiateReference",
"(",
")",
"throws",
"Exception",
"{",
"final",
"T",
"ret",
"=",
"proxyClass",
".",
"newInstance",
"(",
")",
";",
"(",
"(",
"ProxyObject",
")",
"ret",
")",
".",
"setHandler",
"(",
"javassistMethodHandler",
")",
";",
"... | Constructs the bean object with dependencies resolved.
@return bean object
@throws Exception exception | [
"Constructs",
"the",
"bean",
"object",
"with",
"dependencies",
"resolved",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Bean.java#L149-L156 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Bean.java | Bean.resolveCurrentclassFieldDependencies | private void resolveCurrentclassFieldDependencies(final Object reference) {
for (final FieldInjectionPoint injectionPoint : fieldInjectionPoints) {
final Object injection = beanManager.getInjectableReference(injectionPoint);
final Field field = injectionPoint.getAnnotated().getJavaMember();
try {
final Field declaredField = proxyClass.getDeclaredField(field.getName());
if (declaredField.isAnnotationPresent(Inject.class)) {
try {
declaredField.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
} catch (final NoSuchFieldException ex) {
try {
field.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
} | java | private void resolveCurrentclassFieldDependencies(final Object reference) {
for (final FieldInjectionPoint injectionPoint : fieldInjectionPoints) {
final Object injection = beanManager.getInjectableReference(injectionPoint);
final Field field = injectionPoint.getAnnotated().getJavaMember();
try {
final Field declaredField = proxyClass.getDeclaredField(field.getName());
if (declaredField.isAnnotationPresent(Inject.class)) {
try {
declaredField.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
} catch (final NoSuchFieldException ex) {
try {
field.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
}
} | [
"private",
"void",
"resolveCurrentclassFieldDependencies",
"(",
"final",
"Object",
"reference",
")",
"{",
"for",
"(",
"final",
"FieldInjectionPoint",
"injectionPoint",
":",
"fieldInjectionPoints",
")",
"{",
"final",
"Object",
"injection",
"=",
"beanManager",
".",
"get... | Resolves current class field dependencies for the specified reference.
@param reference the specified reference | [
"Resolves",
"current",
"class",
"field",
"dependencies",
"for",
"the",
"specified",
"reference",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Bean.java#L163-L186 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Bean.java | Bean.resolveSuperclassFieldDependencies | private void resolveSuperclassFieldDependencies(final Object reference, final Class<?> clazz) {
if (clazz.equals(Object.class)) {
return;
}
final Class<?> superclass = clazz.getSuperclass();
resolveSuperclassFieldDependencies(reference, superclass);
if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) {
return;
}
final Bean<?> bean = beanManager.getBean(clazz);
final Set<FieldInjectionPoint> injectionPoints = bean.fieldInjectionPoints;
for (final FieldInjectionPoint injectionPoint : injectionPoints) {
final Object injection = beanManager.getInjectableReference(injectionPoint);
final Field field = injectionPoint.getAnnotated().getJavaMember();
try {
final Field declaredField = proxyClass.getDeclaredField(field.getName());
if (!Reflections.matchInheritance(declaredField, field)) { // Hide
try {
field.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
} catch (final NoSuchFieldException ex) {
throw new RuntimeException(ex);
}
}
} | java | private void resolveSuperclassFieldDependencies(final Object reference, final Class<?> clazz) {
if (clazz.equals(Object.class)) {
return;
}
final Class<?> superclass = clazz.getSuperclass();
resolveSuperclassFieldDependencies(reference, superclass);
if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) {
return;
}
final Bean<?> bean = beanManager.getBean(clazz);
final Set<FieldInjectionPoint> injectionPoints = bean.fieldInjectionPoints;
for (final FieldInjectionPoint injectionPoint : injectionPoints) {
final Object injection = beanManager.getInjectableReference(injectionPoint);
final Field field = injectionPoint.getAnnotated().getJavaMember();
try {
final Field declaredField = proxyClass.getDeclaredField(field.getName());
if (!Reflections.matchInheritance(declaredField, field)) { // Hide
try {
field.set(reference, injection);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
} catch (final NoSuchFieldException ex) {
throw new RuntimeException(ex);
}
}
} | [
"private",
"void",
"resolveSuperclassFieldDependencies",
"(",
"final",
"Object",
"reference",
",",
"final",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Object",
".",
"class",
")",
")",
"{",
"return",
";",
"}",
"fin... | Resolves super class field dependencies for the specified reference.
@param reference the specified reference
@param clazz the super class of the specified reference | [
"Resolves",
"super",
"class",
"field",
"dependencies",
"for",
"the",
"specified",
"reference",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Bean.java#L194-L229 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/Bean.java | Bean.initFieldInjectionPoints | private void initFieldInjectionPoints() {
final Set<AnnotatedField<? super T>> annotatedFields = annotatedType.getFields();
for (final AnnotatedField<? super T> annotatedField : annotatedFields) {
final FieldInjectionPoint fieldInjectionPoint = new FieldInjectionPoint(this, annotatedField);
fieldInjectionPoints.add(fieldInjectionPoint);
}
} | java | private void initFieldInjectionPoints() {
final Set<AnnotatedField<? super T>> annotatedFields = annotatedType.getFields();
for (final AnnotatedField<? super T> annotatedField : annotatedFields) {
final FieldInjectionPoint fieldInjectionPoint = new FieldInjectionPoint(this, annotatedField);
fieldInjectionPoints.add(fieldInjectionPoint);
}
} | [
"private",
"void",
"initFieldInjectionPoints",
"(",
")",
"{",
"final",
"Set",
"<",
"AnnotatedField",
"<",
"?",
"super",
"T",
">",
">",
"annotatedFields",
"=",
"annotatedType",
".",
"getFields",
"(",
")",
";",
"for",
"(",
"final",
"AnnotatedField",
"<",
"?",
... | Initializes field injection points. | [
"Initializes",
"field",
"injection",
"points",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/Bean.java#L271-L279 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/URLs.java | URLs.encode | public static String encode(final String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Encodes str [" + str + "] failed", e);
return str;
}
} | java | public static String encode(final String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Encodes str [" + str + "] failed", e);
return str;
}
} | [
"public",
"static",
"String",
"encode",
"(",
"final",
"String",
"str",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"str",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
... | Encodes the specified string.
@param str the specified string
@return URL encoded string | [
"Encodes",
"the",
"specified",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/URLs.java#L44-L52 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/URLs.java | URLs.decode | public static String decode(final String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decodes str [" + str + "] failed", e);
return str;
}
} | java | public static String decode(final String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.WARN, "Decodes str [" + str + "] failed", e);
return str;
}
} | [
"public",
"static",
"String",
"decode",
"(",
"final",
"String",
"str",
")",
"{",
"try",
"{",
"return",
"URLDecoder",
".",
"decode",
"(",
"str",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
... | Decodes the specified string.
@param str the specified string
@return URL decoded string | [
"Decodes",
"the",
"specified",
"string",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/URLs.java#L60-L68 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java | JdbcRepositories.getKeys | public static List<FieldDefinition> getKeys(final String repositoryName) {
final List<RepositoryDefinition> repositoryDefs = getRepositoryDefinitions();
for (final RepositoryDefinition repositoryDefinition : repositoryDefs) {
if (StringUtils.equals(repositoryName, repositoryDefinition.getName())) {
return repositoryDefinition.getKeys();
}
}
return null;
} | java | public static List<FieldDefinition> getKeys(final String repositoryName) {
final List<RepositoryDefinition> repositoryDefs = getRepositoryDefinitions();
for (final RepositoryDefinition repositoryDefinition : repositoryDefs) {
if (StringUtils.equals(repositoryName, repositoryDefinition.getName())) {
return repositoryDefinition.getKeys();
}
}
return null;
} | [
"public",
"static",
"List",
"<",
"FieldDefinition",
">",
"getKeys",
"(",
"final",
"String",
"repositoryName",
")",
"{",
"final",
"List",
"<",
"RepositoryDefinition",
">",
"repositoryDefs",
"=",
"getRepositoryDefinitions",
"(",
")",
";",
"for",
"(",
"final",
"Rep... | Gets keys of the repository specified by the given repository name.
@param repositoryName the given repository name
@return keys | [
"Gets",
"keys",
"of",
"the",
"repository",
"specified",
"by",
"the",
"given",
"repository",
"name",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java#L134-L143 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java | JdbcRepositories.getRepositoryDefinitions | public static List<RepositoryDefinition> getRepositoryDefinitions() {
if (null == repositoryDefinitions) {
try {
initRepositoryDefinitions();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Init repository definitions failed", e);
}
}
return repositoryDefinitions;
} | java | public static List<RepositoryDefinition> getRepositoryDefinitions() {
if (null == repositoryDefinitions) {
try {
initRepositoryDefinitions();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Init repository definitions failed", e);
}
}
return repositoryDefinitions;
} | [
"public",
"static",
"List",
"<",
"RepositoryDefinition",
">",
"getRepositoryDefinitions",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"repositoryDefinitions",
")",
"{",
"try",
"{",
"initRepositoryDefinitions",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
... | Gets the repository definitions,lazy load.
@return repository definitions | [
"Gets",
"the",
"repository",
"definitions",
"lazy",
"load",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java#L150-L160 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java | JdbcRepositories.initRepositoryDefinitions | private static void initRepositoryDefinitions() throws JSONException {
final JSONObject jsonObject = Repositories.getRepositoriesDescription();
if (null == jsonObject) {
LOGGER.warn("Loads repository description [repository.json] failed");
return;
}
repositoryDefinitions = new ArrayList<>();
final JSONArray repositoritArray = jsonObject.getJSONArray(REPOSITORIES);
JSONObject repositoryObject;
JSONObject keyObject;
for (int i = 0; i < repositoritArray.length(); i++) {
repositoryObject = repositoritArray.getJSONObject(i);
final RepositoryDefinition repositoryDefinition = new RepositoryDefinition();
repositoryDefinitions.add(repositoryDefinition);
repositoryDefinition.setName(repositoryObject.getString(NAME));
repositoryDefinition.setDescription(repositoryObject.optString(DESCRIPTION));
final List<FieldDefinition> keys = new ArrayList<>();
repositoryDefinition.setKeys(keys);
final JSONArray keysJsonArray = repositoryObject.getJSONArray(KEYS);
FieldDefinition definition;
for (int j = 0; j < keysJsonArray.length(); j++) {
keyObject = keysJsonArray.getJSONObject(j);
definition = fillFieldDefinitionData(keyObject);
keys.add(definition);
}
repositoryDefinition.setCharset(repositoryObject.optString(CHARSET));
repositoryDefinition.setCollate(repositoryObject.optString(COLLATE));
}
} | java | private static void initRepositoryDefinitions() throws JSONException {
final JSONObject jsonObject = Repositories.getRepositoriesDescription();
if (null == jsonObject) {
LOGGER.warn("Loads repository description [repository.json] failed");
return;
}
repositoryDefinitions = new ArrayList<>();
final JSONArray repositoritArray = jsonObject.getJSONArray(REPOSITORIES);
JSONObject repositoryObject;
JSONObject keyObject;
for (int i = 0; i < repositoritArray.length(); i++) {
repositoryObject = repositoritArray.getJSONObject(i);
final RepositoryDefinition repositoryDefinition = new RepositoryDefinition();
repositoryDefinitions.add(repositoryDefinition);
repositoryDefinition.setName(repositoryObject.getString(NAME));
repositoryDefinition.setDescription(repositoryObject.optString(DESCRIPTION));
final List<FieldDefinition> keys = new ArrayList<>();
repositoryDefinition.setKeys(keys);
final JSONArray keysJsonArray = repositoryObject.getJSONArray(KEYS);
FieldDefinition definition;
for (int j = 0; j < keysJsonArray.length(); j++) {
keyObject = keysJsonArray.getJSONObject(j);
definition = fillFieldDefinitionData(keyObject);
keys.add(definition);
}
repositoryDefinition.setCharset(repositoryObject.optString(CHARSET));
repositoryDefinition.setCollate(repositoryObject.optString(COLLATE));
}
} | [
"private",
"static",
"void",
"initRepositoryDefinitions",
"(",
")",
"throws",
"JSONException",
"{",
"final",
"JSONObject",
"jsonObject",
"=",
"Repositories",
".",
"getRepositoriesDescription",
"(",
")",
";",
"if",
"(",
"null",
"==",
"jsonObject",
")",
"{",
"LOGGER... | Initializes the repository definitions.
@throws JSONException JSONException | [
"Initializes",
"the",
"repository",
"definitions",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java#L167-L198 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java | JdbcRepositories.initAllTables | public static List<CreateTableResult> initAllTables() {
final List<CreateTableResult> ret = new ArrayList<>();
final List<RepositoryDefinition> repositoryDefs = getRepositoryDefinitions();
boolean isSuccess = false;
for (final RepositoryDefinition repositoryDef : repositoryDefs) {
try {
isSuccess = JdbcFactory.getInstance().createTable(repositoryDef);
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Creates table [" + repositoryDef.getName() + "] error", e);
}
ret.add(new CreateTableResult(repositoryDef.getName(), isSuccess));
}
return ret;
} | java | public static List<CreateTableResult> initAllTables() {
final List<CreateTableResult> ret = new ArrayList<>();
final List<RepositoryDefinition> repositoryDefs = getRepositoryDefinitions();
boolean isSuccess = false;
for (final RepositoryDefinition repositoryDef : repositoryDefs) {
try {
isSuccess = JdbcFactory.getInstance().createTable(repositoryDef);
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Creates table [" + repositoryDef.getName() + "] error", e);
}
ret.add(new CreateTableResult(repositoryDef.getName(), isSuccess));
}
return ret;
} | [
"public",
"static",
"List",
"<",
"CreateTableResult",
">",
"initAllTables",
"(",
")",
"{",
"final",
"List",
"<",
"CreateTableResult",
">",
"ret",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"List",
"<",
"RepositoryDefinition",
">",
"repositoryDefs",... | Initializes all tables from repository.json.
@return List<CreateTableResult> | [
"Initializes",
"all",
"tables",
"from",
"repository",
".",
"json",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/repository/jdbc/util/JdbcRepositories.java#L293-L308 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/UriTemplates.java | UriTemplates.resolve | public static Map<String, String> resolve(final String uri, final String uriTemplate) {
final String[] parts = URLs.decode(uri).split("/");
final String[] templateParts = uriTemplate.split("/");
if (parts.length != templateParts.length) {
return null;
}
final Map<String, String> ret = new HashMap<>();
for (int i = 0; i < parts.length; i++) {
final String part = parts[i];
final String templatePart = templateParts[i];
if (part.equals(templatePart)) {
continue;
}
String name = StringUtils.substringBetween(templatePart, "{", "}");
if (StringUtils.isBlank(name)) {
return null;
}
final String templatePartTmp = StringUtils.replace(templatePart, "{" + name + "}", "");
final String arg = StringUtils.replace(part, templatePartTmp, "");
ret.put(name, arg);
}
return ret;
} | java | public static Map<String, String> resolve(final String uri, final String uriTemplate) {
final String[] parts = URLs.decode(uri).split("/");
final String[] templateParts = uriTemplate.split("/");
if (parts.length != templateParts.length) {
return null;
}
final Map<String, String> ret = new HashMap<>();
for (int i = 0; i < parts.length; i++) {
final String part = parts[i];
final String templatePart = templateParts[i];
if (part.equals(templatePart)) {
continue;
}
String name = StringUtils.substringBetween(templatePart, "{", "}");
if (StringUtils.isBlank(name)) {
return null;
}
final String templatePartTmp = StringUtils.replace(templatePart, "{" + name + "}", "");
final String arg = StringUtils.replace(part, templatePartTmp, "");
ret.put(name, arg);
}
return ret;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"resolve",
"(",
"final",
"String",
"uri",
",",
"final",
"String",
"uriTemplate",
")",
"{",
"final",
"String",
"[",
"]",
"parts",
"=",
"URLs",
".",
"decode",
"(",
"uri",
")",
".",
"split",
... | Resolves the specified URI with the specified URI template.
@param uri the specified URI
@param uriTemplate the specified URI template
@return resolved mappings of name and argument, returns {@code null} if failed | [
"Resolves",
"the",
"specified",
"URI",
"with",
"the",
"specified",
"URI",
"template",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/UriTemplates.java#L39-L66 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/annotated/AnnotatedTypeImpl.java | AnnotatedTypeImpl.initAnnotatedFields | private void initAnnotatedFields() {
final Set<Field> hiddenFields = Reflections.getHiddenFields(beanClass);
inject(hiddenFields);
final Set<Field> inheritedFields = Reflections.getInheritedFields(beanClass);
inject(inheritedFields);
final Set<Field> ownFields = Reflections.getOwnFields(beanClass);
inject(ownFields);
} | java | private void initAnnotatedFields() {
final Set<Field> hiddenFields = Reflections.getHiddenFields(beanClass);
inject(hiddenFields);
final Set<Field> inheritedFields = Reflections.getInheritedFields(beanClass);
inject(inheritedFields);
final Set<Field> ownFields = Reflections.getOwnFields(beanClass);
inject(ownFields);
} | [
"private",
"void",
"initAnnotatedFields",
"(",
")",
"{",
"final",
"Set",
"<",
"Field",
">",
"hiddenFields",
"=",
"Reflections",
".",
"getHiddenFields",
"(",
"beanClass",
")",
";",
"inject",
"(",
"hiddenFields",
")",
";",
"final",
"Set",
"<",
"Field",
">",
... | Builds the annotated fields of this annotated type. | [
"Builds",
"the",
"annotated",
"fields",
"of",
"this",
"annotated",
"type",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/annotated/AnnotatedTypeImpl.java#L64-L73 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/StaticResources.java | StaticResources.isStatic | public static boolean isStatic(final HttpServletRequest request) {
final boolean requestStaticResourceChecked = null == request.getAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED)
? false
: (Boolean) request.getAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED);
if (requestStaticResourceChecked) {
return (Boolean) request.getAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE);
}
if (!inited) {
init();
}
request.setAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED, true);
request.setAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE, false);
final String requestURI = request.getRequestURI();
for (final String pattern : STATIC_RESOURCE_PATHS) {
if (AntPathMatcher.match(Latkes.getContextPath() + pattern, requestURI)) {
request.setAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE, true);
return true;
}
}
return false;
} | java | public static boolean isStatic(final HttpServletRequest request) {
final boolean requestStaticResourceChecked = null == request.getAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED)
? false
: (Boolean) request.getAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED);
if (requestStaticResourceChecked) {
return (Boolean) request.getAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE);
}
if (!inited) {
init();
}
request.setAttribute(Keys.HttpRequest.REQUEST_STATIC_RESOURCE_CHECKED, true);
request.setAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE, false);
final String requestURI = request.getRequestURI();
for (final String pattern : STATIC_RESOURCE_PATHS) {
if (AntPathMatcher.match(Latkes.getContextPath() + pattern, requestURI)) {
request.setAttribute(Keys.HttpRequest.IS_REQUEST_STATIC_RESOURCE, true);
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"isStatic",
"(",
"final",
"HttpServletRequest",
"request",
")",
"{",
"final",
"boolean",
"requestStaticResourceChecked",
"=",
"null",
"==",
"request",
".",
"getAttribute",
"(",
"Keys",
".",
"HttpRequest",
".",
"REQUEST_STATIC_RESOURCE_CH... | Determines whether the client requests a static resource with the specified request.
@param request the specified request
@return {@code true} if the client requests a static resource, returns {@code false} otherwise | [
"Determines",
"whether",
"the",
"client",
"requests",
"a",
"static",
"resource",
"with",
"the",
"specified",
"request",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/StaticResources.java#L68-L94 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/StaticResources.java | StaticResources.init | private static synchronized void init() {
LOGGER.trace("Reads static resources definition from [static-resources.xml]");
final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
if (null == staticResources || !staticResources.exists()) {
throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
}
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.parse(staticResources);
final Element root = document.getDocumentElement();
root.normalize();
final StringBuilder logBuilder = new StringBuilder("Reading static files: [").append(Strings.LINE_SEPARATOR);
final NodeList includes = root.getElementsByTagName("include");
for (int i = 0; i < includes.getLength(); i++) {
final Element include = (Element) includes.item(i);
String path = include.getAttribute("path");
final URI uri = new URI("http", "b3log.org", path, null);
final String s = uri.toASCIIString();
path = StringUtils.substringAfter(s, "b3log.org");
STATIC_RESOURCE_PATHS.add(path);
logBuilder.append(" ").append("path pattern [").append(path).append("]");
if (i < includes.getLength() - 1) {
logBuilder.append(",");
}
logBuilder.append(Strings.LINE_SEPARATOR);
}
logBuilder.append("]");
if (LOGGER.isTraceEnabled()) {
LOGGER.debug(logBuilder.toString());
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
throw new RuntimeException(e);
}
final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
while (iterator.hasNext()) {
final String pattern = iterator.next();
logBuilder.append(" ").append(pattern);
if (iterator.hasNext()) {
logBuilder.append(',');
}
logBuilder.append(Strings.LINE_SEPARATOR);
}
logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(logBuilder.toString());
}
inited = true;
} | java | private static synchronized void init() {
LOGGER.trace("Reads static resources definition from [static-resources.xml]");
final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
if (null == staticResources || !staticResources.exists()) {
throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
}
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.parse(staticResources);
final Element root = document.getDocumentElement();
root.normalize();
final StringBuilder logBuilder = new StringBuilder("Reading static files: [").append(Strings.LINE_SEPARATOR);
final NodeList includes = root.getElementsByTagName("include");
for (int i = 0; i < includes.getLength(); i++) {
final Element include = (Element) includes.item(i);
String path = include.getAttribute("path");
final URI uri = new URI("http", "b3log.org", path, null);
final String s = uri.toASCIIString();
path = StringUtils.substringAfter(s, "b3log.org");
STATIC_RESOURCE_PATHS.add(path);
logBuilder.append(" ").append("path pattern [").append(path).append("]");
if (i < includes.getLength() - 1) {
logBuilder.append(",");
}
logBuilder.append(Strings.LINE_SEPARATOR);
}
logBuilder.append("]");
if (LOGGER.isTraceEnabled()) {
LOGGER.debug(logBuilder.toString());
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
throw new RuntimeException(e);
}
final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
while (iterator.hasNext()) {
final String pattern = iterator.next();
logBuilder.append(" ").append(pattern);
if (iterator.hasNext()) {
logBuilder.append(',');
}
logBuilder.append(Strings.LINE_SEPARATOR);
}
logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(logBuilder.toString());
}
inited = true;
} | [
"private",
"static",
"synchronized",
"void",
"init",
"(",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Reads static resources definition from [static-resources.xml]\"",
")",
";",
"final",
"File",
"staticResources",
"=",
"Latkes",
".",
"getWebFile",
"(",
"\"/WEB-INF/static-... | Initializes the static resource path patterns. | [
"Initializes",
"the",
"static",
"resource",
"path",
"patterns",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/StaticResources.java#L99-L162 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/ioc/BeanManager.java | BeanManager.start | public static void start(final Collection<Class<?>> classes) {
LOGGER.log(Level.DEBUG, "Initializing Latke IoC container");
final Configurator configurator = getInstance().getConfigurator();
if (null != classes && !classes.isEmpty()) {
configurator.createBeans(classes);
}
LOGGER.log(Level.DEBUG, "Initialized Latke IoC container");
} | java | public static void start(final Collection<Class<?>> classes) {
LOGGER.log(Level.DEBUG, "Initializing Latke IoC container");
final Configurator configurator = getInstance().getConfigurator();
if (null != classes && !classes.isEmpty()) {
configurator.createBeans(classes);
}
LOGGER.log(Level.DEBUG, "Initialized Latke IoC container");
} | [
"public",
"static",
"void",
"start",
"(",
"final",
"Collection",
"<",
"Class",
"<",
"?",
">",
">",
"classes",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"DEBUG",
",",
"\"Initializing Latke IoC container\"",
")",
";",
"final",
"Configurator",
"configu... | Starts the application with the specified bean class and bean modules.
@param classes the specified bean class, nullable | [
"Starts",
"the",
"application",
"with",
"the",
"specified",
"bean",
"class",
"and",
"bean",
"modules",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/ioc/BeanManager.java#L101-L110 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.setLocalProperty | public static void setLocalProperty(final String key, final String value) {
if (null == key) {
LOGGER.log(Level.WARN, "local.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "local.props can not set null value");
return;
}
localProps.setProperty(key, value);
} | java | public static void setLocalProperty(final String key, final String value) {
if (null == key) {
LOGGER.log(Level.WARN, "local.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "local.props can not set null value");
return;
}
localProps.setProperty(key, value);
} | [
"public",
"static",
"void",
"setLocalProperty",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"null",
"==",
"key",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"local.props can not set null key\"",
... | Sets local.props with the specified key and value.
@param key the specified key
@param value the specified value | [
"Sets",
"local",
".",
"props",
"with",
"the",
"specified",
"key",
"and",
"value",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L148-L161 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.setLatkeProperty | public static void setLatkeProperty(final String key, final String value) {
if (null == key) {
LOGGER.log(Level.WARN, "latke.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "latke.props can not set null value");
return;
}
latkeProps.setProperty(key, value);
} | java | public static void setLatkeProperty(final String key, final String value) {
if (null == key) {
LOGGER.log(Level.WARN, "latke.props can not set null key");
return;
}
if (null == value) {
LOGGER.log(Level.WARN, "latke.props can not set null value");
return;
}
latkeProps.setProperty(key, value);
} | [
"public",
"static",
"void",
"setLatkeProperty",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"if",
"(",
"null",
"==",
"key",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"WARN",
",",
"\"latke.props can not set null key\"",
... | Sets latke.props with the specified key and value.
@param key the specified key
@param value the specified value | [
"Sets",
"latke",
".",
"props",
"with",
"the",
"specified",
"key",
"and",
"value",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L178-L191 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.loadLocalProps | private static void loadLocalProps() {
if (null == localProps) {
localProps = new Properties();
}
try {
InputStream resourceAsStream;
final String localPropsEnv = System.getenv("LATKE_LOCAL_PROPS");
if (StringUtils.isNotBlank(localPropsEnv)) {
LOGGER.debug("Loading local.properties from env var [$LATKE_LOCAL_PROPS=" + localPropsEnv + "]");
resourceAsStream = new FileInputStream(localPropsEnv);
} else {
LOGGER.debug("Loading local.properties from classpath [/local.properties]");
resourceAsStream = Latkes.class.getResourceAsStream("/local.properties");
}
if (null != resourceAsStream) {
localProps.load(resourceAsStream);
LOGGER.debug("Loaded local.properties");
}
} catch (final Exception e) {
LOGGER.log(Level.DEBUG, "Loads local.properties failed, ignored");
}
} | java | private static void loadLocalProps() {
if (null == localProps) {
localProps = new Properties();
}
try {
InputStream resourceAsStream;
final String localPropsEnv = System.getenv("LATKE_LOCAL_PROPS");
if (StringUtils.isNotBlank(localPropsEnv)) {
LOGGER.debug("Loading local.properties from env var [$LATKE_LOCAL_PROPS=" + localPropsEnv + "]");
resourceAsStream = new FileInputStream(localPropsEnv);
} else {
LOGGER.debug("Loading local.properties from classpath [/local.properties]");
resourceAsStream = Latkes.class.getResourceAsStream("/local.properties");
}
if (null != resourceAsStream) {
localProps.load(resourceAsStream);
LOGGER.debug("Loaded local.properties");
}
} catch (final Exception e) {
LOGGER.log(Level.DEBUG, "Loads local.properties failed, ignored");
}
} | [
"private",
"static",
"void",
"loadLocalProps",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"localProps",
")",
"{",
"localProps",
"=",
"new",
"Properties",
"(",
")",
";",
"}",
"try",
"{",
"InputStream",
"resourceAsStream",
";",
"final",
"String",
"localPropsEnv",... | Loads the local.props. | [
"Loads",
"the",
"local",
".",
"props",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L196-L219 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.loadLatkeProps | private static void loadLatkeProps() {
if (null == latkeProps) {
latkeProps = new Properties();
}
try {
InputStream resourceAsStream;
final String latkePropsEnv = System.getenv("LATKE_PROPS");
if (StringUtils.isNotBlank(latkePropsEnv)) {
LOGGER.debug("Loading latke.properties from env var [$LATKE_PROPS=" + latkePropsEnv + "]");
resourceAsStream = new FileInputStream(latkePropsEnv);
} else {
LOGGER.debug("Loading latke.properties from classpath [/latke.properties]");
resourceAsStream = Latkes.class.getResourceAsStream("/latke.properties");
}
if (null != resourceAsStream) {
latkeProps.load(resourceAsStream);
LOGGER.debug("Loaded latke.properties");
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Loads latke.properties failed", e);
throw new RuntimeException("Loads latke.properties failed");
}
} | java | private static void loadLatkeProps() {
if (null == latkeProps) {
latkeProps = new Properties();
}
try {
InputStream resourceAsStream;
final String latkePropsEnv = System.getenv("LATKE_PROPS");
if (StringUtils.isNotBlank(latkePropsEnv)) {
LOGGER.debug("Loading latke.properties from env var [$LATKE_PROPS=" + latkePropsEnv + "]");
resourceAsStream = new FileInputStream(latkePropsEnv);
} else {
LOGGER.debug("Loading latke.properties from classpath [/latke.properties]");
resourceAsStream = Latkes.class.getResourceAsStream("/latke.properties");
}
if (null != resourceAsStream) {
latkeProps.load(resourceAsStream);
LOGGER.debug("Loaded latke.properties");
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Loads latke.properties failed", e);
throw new RuntimeException("Loads latke.properties failed");
}
} | [
"private",
"static",
"void",
"loadLatkeProps",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"latkeProps",
")",
"{",
"latkeProps",
"=",
"new",
"Properties",
"(",
")",
";",
"}",
"try",
"{",
"InputStream",
"resourceAsStream",
";",
"final",
"String",
"latkePropsEnv",... | Loads the latke.props. | [
"Loads",
"the",
"latke",
".",
"props",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L224-L249 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getServerScheme | public static String getServerScheme() {
String ret = getLatkeProperty("serverScheme");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getScheme();
} else {
ret = "http";
}
}
return ret;
} | java | public static String getServerScheme() {
String ret = getLatkeProperty("serverScheme");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getScheme();
} else {
ret = "http";
}
}
return ret;
} | [
"public",
"static",
"String",
"getServerScheme",
"(",
")",
"{",
"String",
"ret",
"=",
"getLatkeProperty",
"(",
"\"serverScheme\"",
")",
";",
"if",
"(",
"null",
"==",
"ret",
")",
"{",
"final",
"RequestContext",
"requestContext",
"=",
"REQUEST_CONTEXT",
".",
"ge... | Gets server scheme.
@return server scheme | [
"Gets",
"server",
"scheme",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L286-L298 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getServerHost | public static String getServerHost() {
String ret = getLatkeProperty("serverHost");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getServerName();
} else {
initPublicIP();
return PUBLIC_IP;
}
}
return ret;
} | java | public static String getServerHost() {
String ret = getLatkeProperty("serverHost");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getServerName();
} else {
initPublicIP();
return PUBLIC_IP;
}
}
return ret;
} | [
"public",
"static",
"String",
"getServerHost",
"(",
")",
"{",
"String",
"ret",
"=",
"getLatkeProperty",
"(",
"\"serverHost\"",
")",
";",
"if",
"(",
"null",
"==",
"ret",
")",
"{",
"final",
"RequestContext",
"requestContext",
"=",
"REQUEST_CONTEXT",
".",
"get",
... | Gets server host.
@return server host | [
"Gets",
"server",
"host",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L305-L319 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.initPublicIP | public synchronized static void initPublicIP() {
if (StringUtils.isNotBlank(PUBLIC_IP)) {
return;
}
try {
final URL url = new URL("http://checkip.amazonaws.com");
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
try (final BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) {
PUBLIC_IP = in.readLine();
}
urlConnection.disconnect();
return;
} catch (final Exception e) {
try {
PUBLIC_IP = InetAddress.getLocalHost().getHostAddress();
return;
} catch (final Exception e2) {
}
}
PUBLIC_IP = "127.0.0.1";
} | java | public synchronized static void initPublicIP() {
if (StringUtils.isNotBlank(PUBLIC_IP)) {
return;
}
try {
final URL url = new URL("http://checkip.amazonaws.com");
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
try (final BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) {
PUBLIC_IP = in.readLine();
}
urlConnection.disconnect();
return;
} catch (final Exception e) {
try {
PUBLIC_IP = InetAddress.getLocalHost().getHostAddress();
return;
} catch (final Exception e2) {
}
}
PUBLIC_IP = "127.0.0.1";
} | [
"public",
"synchronized",
"static",
"void",
"initPublicIP",
"(",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"PUBLIC_IP",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"final",
"URL",
"url",
"=",
"new",
"URL",
"(",
"\"http://checkip.amazon... | Init public IP. | [
"Init",
"public",
"IP",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L326-L352 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getServerPort | public static String getServerPort() {
String ret = getLatkeProperty("serverPort");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getServerPort() + "";
}
}
return ret;
} | java | public static String getServerPort() {
String ret = getLatkeProperty("serverPort");
if (null == ret) {
final RequestContext requestContext = REQUEST_CONTEXT.get();
if (null != requestContext) {
ret = requestContext.getRequest().getServerPort() + "";
}
}
return ret;
} | [
"public",
"static",
"String",
"getServerPort",
"(",
")",
"{",
"String",
"ret",
"=",
"getLatkeProperty",
"(",
"\"serverPort\"",
")",
";",
"if",
"(",
"null",
"==",
"ret",
")",
"{",
"final",
"RequestContext",
"requestContext",
"=",
"REQUEST_CONTEXT",
".",
"get",
... | Gets server port.
@return server port | [
"Gets",
"server",
"port",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L359-L369 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getServer | public static String getServer() {
final StringBuilder serverBuilder = new StringBuilder(getServerScheme()).append("://").append(getServerHost());
final String port = getServerPort();
if (StringUtils.isNotBlank(port) && !"80".equals(port) && !"443".equals(port)) {
serverBuilder.append(':').append(port);
}
return serverBuilder.toString();
} | java | public static String getServer() {
final StringBuilder serverBuilder = new StringBuilder(getServerScheme()).append("://").append(getServerHost());
final String port = getServerPort();
if (StringUtils.isNotBlank(port) && !"80".equals(port) && !"443".equals(port)) {
serverBuilder.append(':').append(port);
}
return serverBuilder.toString();
} | [
"public",
"static",
"String",
"getServer",
"(",
")",
"{",
"final",
"StringBuilder",
"serverBuilder",
"=",
"new",
"StringBuilder",
"(",
"getServerScheme",
"(",
")",
")",
".",
"append",
"(",
"\"://\"",
")",
".",
"append",
"(",
"getServerHost",
"(",
")",
")",
... | Gets server.
@return server, ${serverScheme}://${serverHost}:${serverPort} | [
"Gets",
"server",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L376-L384 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getStaticServer | public static String getStaticServer() {
final StringBuilder staticServerBuilder = new StringBuilder(getStaticServerScheme()).append("://").append(getStaticServerHost());
final String port = getStaticServerPort();
if (StringUtils.isNotBlank(port) && !"80".equals(port) && !"443".equals(port)) {
staticServerBuilder.append(':').append(port);
}
return staticServerBuilder.toString();
} | java | public static String getStaticServer() {
final StringBuilder staticServerBuilder = new StringBuilder(getStaticServerScheme()).append("://").append(getStaticServerHost());
final String port = getStaticServerPort();
if (StringUtils.isNotBlank(port) && !"80".equals(port) && !"443".equals(port)) {
staticServerBuilder.append(':').append(port);
}
return staticServerBuilder.toString();
} | [
"public",
"static",
"String",
"getStaticServer",
"(",
")",
"{",
"final",
"StringBuilder",
"staticServerBuilder",
"=",
"new",
"StringBuilder",
"(",
"getStaticServerScheme",
"(",
")",
")",
".",
"append",
"(",
"\"://\"",
")",
".",
"append",
"(",
"getStaticServerHost"... | Gets static server.
@return static server, ${staticServerScheme}://${staticServerHost}:${staticServerPort} | [
"Gets",
"static",
"server",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L442-L450 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getContextPath | public static String getContextPath() {
if (null != contextPath) {
return contextPath;
}
final String contextPathConf = getLatkeProperty("contextPath");
if (null != contextPathConf) {
contextPath = contextPathConf;
return contextPath;
}
final ServletContext servletContext = AbstractServletListener.getServletContext();
contextPath = servletContext.getContextPath();
return contextPath;
} | java | public static String getContextPath() {
if (null != contextPath) {
return contextPath;
}
final String contextPathConf = getLatkeProperty("contextPath");
if (null != contextPathConf) {
contextPath = contextPathConf;
return contextPath;
}
final ServletContext servletContext = AbstractServletListener.getServletContext();
contextPath = servletContext.getContextPath();
return contextPath;
} | [
"public",
"static",
"String",
"getContextPath",
"(",
")",
"{",
"if",
"(",
"null",
"!=",
"contextPath",
")",
"{",
"return",
"contextPath",
";",
"}",
"final",
"String",
"contextPathConf",
"=",
"getLatkeProperty",
"(",
"\"contextPath\"",
")",
";",
"if",
"(",
"n... | Gets context path.
@return context path | [
"Gets",
"context",
"path",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L466-L482 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getStaticPath | public static String getStaticPath() {
if (null == staticPath) {
staticPath = getLatkeProperty("staticPath");
if (null == staticPath) {
staticPath = getContextPath();
}
}
return staticPath;
} | java | public static String getStaticPath() {
if (null == staticPath) {
staticPath = getLatkeProperty("staticPath");
if (null == staticPath) {
staticPath = getContextPath();
}
}
return staticPath;
} | [
"public",
"static",
"String",
"getStaticPath",
"(",
")",
"{",
"if",
"(",
"null",
"==",
"staticPath",
")",
"{",
"staticPath",
"=",
"getLatkeProperty",
"(",
"\"staticPath\"",
")",
";",
"if",
"(",
"null",
"==",
"staticPath",
")",
"{",
"staticPath",
"=",
"getC... | Gets static path.
@return static path | [
"Gets",
"static",
"path",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L498-L508 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.init | public static synchronized void init() {
if (inited) {
return;
}
inited = true;
LOGGER.log(Level.TRACE, "Initializing Latke");
loadLatkeProps();
loadLocalProps();
if (null == runtimeMode) {
final String runtimeModeValue = getLatkeProperty("runtimeMode");
if (null != runtimeModeValue) {
runtimeMode = RuntimeMode.valueOf(runtimeModeValue);
} else {
LOGGER.log(Level.TRACE, "Can't parse runtime mode in latke.properties, default to [PRODUCTION]");
runtimeMode = RuntimeMode.PRODUCTION;
}
}
if (Latkes.RuntimeMode.DEVELOPMENT == getRuntimeMode()) {
LOGGER.warn("!!!!Runtime mode is [" + Latkes.RuntimeMode.DEVELOPMENT + "], please make sure configured it with ["
+ Latkes.RuntimeMode.PRODUCTION + "] in latke.properties if deployed on production environment!!!!");
} else {
LOGGER.log(Level.DEBUG, "Runtime mode is [{0}]", getRuntimeMode());
}
final RuntimeDatabase runtimeDatabase = getRuntimeDatabase();
LOGGER.log(Level.DEBUG, "Runtime database is [{0}]", runtimeDatabase);
if (RuntimeDatabase.H2 == runtimeDatabase) {
final String newTCPServer = getLocalProperty("newTCPServer");
if ("true".equals(newTCPServer)) {
LOGGER.log(Level.DEBUG, "Starting H2 TCP server");
final String jdbcURL = getLocalProperty("jdbc.URL");
if (StringUtils.isBlank(jdbcURL)) {
throw new IllegalStateException("The jdbc.URL in local.properties is required");
}
final String[] parts = jdbcURL.split(":");
if (5 != parts.length) {
throw new IllegalStateException("jdbc.URL should like [jdbc:h2:tcp://localhost:8250/~/] (the port part is required)");
}
String port = parts[parts.length - 1];
port = StringUtils.substringBefore(port, "/");
LOGGER.log(Level.TRACE, "H2 TCP port [{0}]", port);
try {
h2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", port, "-tcpAllowOthers"}).start();
} catch (final SQLException e) {
final String msg = "H2 TCP server create failed";
LOGGER.log(Level.ERROR, msg, e);
throw new IllegalStateException(msg);
}
LOGGER.log(Level.DEBUG, "Started H2 TCP server");
}
}
final RuntimeCache runtimeCache = getRuntimeCache();
LOGGER.log(Level.INFO, "Runtime cache is [{0}]", runtimeCache);
locale = new Locale("en_US");
LOGGER.log(Level.INFO, "Initialized Latke");
} | java | public static synchronized void init() {
if (inited) {
return;
}
inited = true;
LOGGER.log(Level.TRACE, "Initializing Latke");
loadLatkeProps();
loadLocalProps();
if (null == runtimeMode) {
final String runtimeModeValue = getLatkeProperty("runtimeMode");
if (null != runtimeModeValue) {
runtimeMode = RuntimeMode.valueOf(runtimeModeValue);
} else {
LOGGER.log(Level.TRACE, "Can't parse runtime mode in latke.properties, default to [PRODUCTION]");
runtimeMode = RuntimeMode.PRODUCTION;
}
}
if (Latkes.RuntimeMode.DEVELOPMENT == getRuntimeMode()) {
LOGGER.warn("!!!!Runtime mode is [" + Latkes.RuntimeMode.DEVELOPMENT + "], please make sure configured it with ["
+ Latkes.RuntimeMode.PRODUCTION + "] in latke.properties if deployed on production environment!!!!");
} else {
LOGGER.log(Level.DEBUG, "Runtime mode is [{0}]", getRuntimeMode());
}
final RuntimeDatabase runtimeDatabase = getRuntimeDatabase();
LOGGER.log(Level.DEBUG, "Runtime database is [{0}]", runtimeDatabase);
if (RuntimeDatabase.H2 == runtimeDatabase) {
final String newTCPServer = getLocalProperty("newTCPServer");
if ("true".equals(newTCPServer)) {
LOGGER.log(Level.DEBUG, "Starting H2 TCP server");
final String jdbcURL = getLocalProperty("jdbc.URL");
if (StringUtils.isBlank(jdbcURL)) {
throw new IllegalStateException("The jdbc.URL in local.properties is required");
}
final String[] parts = jdbcURL.split(":");
if (5 != parts.length) {
throw new IllegalStateException("jdbc.URL should like [jdbc:h2:tcp://localhost:8250/~/] (the port part is required)");
}
String port = parts[parts.length - 1];
port = StringUtils.substringBefore(port, "/");
LOGGER.log(Level.TRACE, "H2 TCP port [{0}]", port);
try {
h2 = org.h2.tools.Server.createTcpServer(new String[]{"-tcpPort", port, "-tcpAllowOthers"}).start();
} catch (final SQLException e) {
final String msg = "H2 TCP server create failed";
LOGGER.log(Level.ERROR, msg, e);
throw new IllegalStateException(msg);
}
LOGGER.log(Level.DEBUG, "Started H2 TCP server");
}
}
final RuntimeCache runtimeCache = getRuntimeCache();
LOGGER.log(Level.INFO, "Runtime cache is [{0}]", runtimeCache);
locale = new Locale("en_US");
LOGGER.log(Level.INFO, "Initialized Latke");
} | [
"public",
"static",
"synchronized",
"void",
"init",
"(",
")",
"{",
"if",
"(",
"inited",
")",
"{",
"return",
";",
"}",
"inited",
"=",
"true",
";",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"TRACE",
",",
"\"Initializing Latke\"",
")",
";",
"loadLatkeProps",... | Initializes Latke framework. | [
"Initializes",
"Latke",
"framework",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L544-L614 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getRuntimeCache | public static RuntimeCache getRuntimeCache() {
final String runtimeCache = getLocalProperty("runtimeCache");
if (null == runtimeCache) {
LOGGER.debug("Not found [runtimeCache] in local.properties, uses [LOCAL_LRU] as default");
return RuntimeCache.LOCAL_LRU;
}
return RuntimeCache.valueOf(runtimeCache);
} | java | public static RuntimeCache getRuntimeCache() {
final String runtimeCache = getLocalProperty("runtimeCache");
if (null == runtimeCache) {
LOGGER.debug("Not found [runtimeCache] in local.properties, uses [LOCAL_LRU] as default");
return RuntimeCache.LOCAL_LRU;
}
return RuntimeCache.valueOf(runtimeCache);
} | [
"public",
"static",
"RuntimeCache",
"getRuntimeCache",
"(",
")",
"{",
"final",
"String",
"runtimeCache",
"=",
"getLocalProperty",
"(",
"\"runtimeCache\"",
")",
";",
"if",
"(",
"null",
"==",
"runtimeCache",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Not found [run... | Gets the runtime cache.
@return runtime cache | [
"Gets",
"the",
"runtime",
"cache",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L643-L652 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getRuntimeDatabase | public static RuntimeDatabase getRuntimeDatabase() {
final String runtimeDatabase = getLocalProperty("runtimeDatabase");
if (null == runtimeDatabase) {
throw new RuntimeException("Please configures runtime database in local.properties!");
}
final RuntimeDatabase ret = RuntimeDatabase.valueOf(runtimeDatabase);
if (null == ret) {
throw new RuntimeException("Please configures a valid runtime database in local.properties!");
}
return ret;
} | java | public static RuntimeDatabase getRuntimeDatabase() {
final String runtimeDatabase = getLocalProperty("runtimeDatabase");
if (null == runtimeDatabase) {
throw new RuntimeException("Please configures runtime database in local.properties!");
}
final RuntimeDatabase ret = RuntimeDatabase.valueOf(runtimeDatabase);
if (null == ret) {
throw new RuntimeException("Please configures a valid runtime database in local.properties!");
}
return ret;
} | [
"public",
"static",
"RuntimeDatabase",
"getRuntimeDatabase",
"(",
")",
"{",
"final",
"String",
"runtimeDatabase",
"=",
"getLocalProperty",
"(",
"\"runtimeDatabase\"",
")",
";",
"if",
"(",
"null",
"==",
"runtimeDatabase",
")",
"{",
"throw",
"new",
"RuntimeException",... | Gets the runtime database.
@return runtime database | [
"Gets",
"the",
"runtime",
"database",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L659-L671 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getLocalProperty | public static String getLocalProperty(final String key) {
String ret = localProps.getProperty(key);
if (StringUtils.isBlank(ret)) {
return ret;
}
ret = replaceEnvVars(ret);
return ret;
} | java | public static String getLocalProperty(final String key) {
String ret = localProps.getProperty(key);
if (StringUtils.isBlank(ret)) {
return ret;
}
ret = replaceEnvVars(ret);
return ret;
} | [
"public",
"static",
"String",
"getLocalProperty",
"(",
"final",
"String",
"key",
")",
"{",
"String",
"ret",
"=",
"localProps",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"ret",
")",
")",
"{",
"return",
"ret",... | Gets a property specified by the given key from file "local.properties".
@param key the given key
@return the value, returns {@code null} if not found | [
"Gets",
"a",
"property",
"specified",
"by",
"the",
"given",
"key",
"from",
"file",
"local",
".",
"properties",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L702-L711 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getLatkeProperty | public static String getLatkeProperty(final String key) {
String ret = latkeProps.getProperty(key);
if (StringUtils.isBlank(ret)) {
return ret;
}
ret = replaceEnvVars(ret);
return ret;
} | java | public static String getLatkeProperty(final String key) {
String ret = latkeProps.getProperty(key);
if (StringUtils.isBlank(ret)) {
return ret;
}
ret = replaceEnvVars(ret);
return ret;
} | [
"public",
"static",
"String",
"getLatkeProperty",
"(",
"final",
"String",
"key",
")",
"{",
"String",
"ret",
"=",
"latkeProps",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"ret",
")",
")",
"{",
"return",
"ret",... | Gets a property specified by the given key from file "latke.properties".
@param key the given key
@return the value, returns {@code null} if not found | [
"Gets",
"a",
"property",
"specified",
"by",
"the",
"given",
"key",
"from",
"file",
"latke",
".",
"properties",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L719-L728 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.shutdown | public static void shutdown() {
try {
EXECUTOR_SERVICE.shutdown();
if (RuntimeCache.REDIS == getRuntimeCache()) {
RedisCache.shutdown();
}
Connections.shutdownConnectionPool();
if (RuntimeDatabase.H2 == getRuntimeDatabase()) {
final String newTCPServer = getLocalProperty("newTCPServer");
if ("true".equals(newTCPServer)) {
h2.stop();
h2.shutdown();
LOGGER.log(Level.INFO, "Closed H2 TCP server");
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Shutdowns Latke failed", e);
}
BeanManager.close();
// Manually unregister JDBC driver, which prevents Tomcat from complaining about memory leaks
final Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
final Driver driver = drivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
LOGGER.log(Level.TRACE, "Unregistered JDBC driver [" + driver + "]");
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Unregister JDBC driver [" + driver + "] failed", e);
}
}
} | java | public static void shutdown() {
try {
EXECUTOR_SERVICE.shutdown();
if (RuntimeCache.REDIS == getRuntimeCache()) {
RedisCache.shutdown();
}
Connections.shutdownConnectionPool();
if (RuntimeDatabase.H2 == getRuntimeDatabase()) {
final String newTCPServer = getLocalProperty("newTCPServer");
if ("true".equals(newTCPServer)) {
h2.stop();
h2.shutdown();
LOGGER.log(Level.INFO, "Closed H2 TCP server");
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Shutdowns Latke failed", e);
}
BeanManager.close();
// Manually unregister JDBC driver, which prevents Tomcat from complaining about memory leaks
final Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
final Driver driver = drivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
LOGGER.log(Level.TRACE, "Unregistered JDBC driver [" + driver + "]");
} catch (final SQLException e) {
LOGGER.log(Level.ERROR, "Unregister JDBC driver [" + driver + "] failed", e);
}
}
} | [
"public",
"static",
"void",
"shutdown",
"(",
")",
"{",
"try",
"{",
"EXECUTOR_SERVICE",
".",
"shutdown",
"(",
")",
";",
"if",
"(",
"RuntimeCache",
".",
"REDIS",
"==",
"getRuntimeCache",
"(",
")",
")",
"{",
"RedisCache",
".",
"shutdown",
"(",
")",
";",
"... | Shutdowns Latke. | [
"Shutdowns",
"Latke",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L733-L769 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/Latkes.java | Latkes.getWebFile | public static File getWebFile(final String path) {
final ServletContext servletContext = AbstractServletListener.getServletContext();
File ret;
try {
final URL resource = servletContext.getResource(path);
if (null == resource) {
return null;
}
ret = FileUtils.toFile(resource);
if (null == ret) {
final File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
ret = new File(tempdir.getPath() + path);
FileUtils.copyURLToFile(resource, ret);
ret.deleteOnExit();
}
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads file [path=" + path + "] failed", e);
return null;
}
} | java | public static File getWebFile(final String path) {
final ServletContext servletContext = AbstractServletListener.getServletContext();
File ret;
try {
final URL resource = servletContext.getResource(path);
if (null == resource) {
return null;
}
ret = FileUtils.toFile(resource);
if (null == ret) {
final File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
ret = new File(tempdir.getPath() + path);
FileUtils.copyURLToFile(resource, ret);
ret.deleteOnExit();
}
return ret;
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads file [path=" + path + "] failed", e);
return null;
}
} | [
"public",
"static",
"File",
"getWebFile",
"(",
"final",
"String",
"path",
")",
"{",
"final",
"ServletContext",
"servletContext",
"=",
"AbstractServletListener",
".",
"getServletContext",
"(",
")",
";",
"File",
"ret",
";",
"try",
"{",
"final",
"URL",
"resource",
... | Gets a file in web application with the specified path.
@param path the specified path
@return file,
@see javax.servlet.ServletContext#getResource(java.lang.String)
@see javax.servlet.ServletContext#getResourceAsStream(java.lang.String) | [
"Gets",
"a",
"file",
"in",
"web",
"application",
"with",
"the",
"specified",
"path",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/Latkes.java#L800-L826 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/event/SynchronizedEventQueue.java | SynchronizedEventQueue.fireEvent | synchronized void fireEvent(final Event<?> event) {
final String eventType = event.getType();
List<Event<?>> events = synchronizedEvents.get(eventType);
if (null == events) {
events = new ArrayList<>();
synchronizedEvents.put(eventType, events);
}
events.add(event);
setChanged();
notifyListeners(event);
} | java | synchronized void fireEvent(final Event<?> event) {
final String eventType = event.getType();
List<Event<?>> events = synchronizedEvents.get(eventType);
if (null == events) {
events = new ArrayList<>();
synchronizedEvents.put(eventType, events);
}
events.add(event);
setChanged();
notifyListeners(event);
} | [
"synchronized",
"void",
"fireEvent",
"(",
"final",
"Event",
"<",
"?",
">",
"event",
")",
"{",
"final",
"String",
"eventType",
"=",
"event",
".",
"getType",
"(",
")",
";",
"List",
"<",
"Event",
"<",
"?",
">",
">",
"events",
"=",
"synchronizedEvents",
".... | Fires the specified event.
@param event the specified event | [
"Fires",
"the",
"specified",
"event",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/event/SynchronizedEventQueue.java#L56-L67 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.getEnum | public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
E val = optEnum(clazz, index);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONArray[" + index + "] is not an enum of type "
+ JSONObject.quote(clazz.getSimpleName()) + ".");
}
return val;
} | java | public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
E val = optEnum(clazz, index);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONArray[" + index + "] is not an enum of type "
+ JSONObject.quote(clazz.getSimpleName()) + ".");
}
return val;
} | [
"public",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"E",
"getEnum",
"(",
"Class",
"<",
"E",
">",
"clazz",
",",
"int",
"index",
")",
"throws",
"JSONException",
"{",
"E",
"val",
"=",
"optEnum",
"(",
"clazz",
",",
"index",
")",
";",
"if",
"("... | Get the enum value associated with an index.
@param <E>
Enum Type
@param clazz
The type of enum to retrieve.
@param index
The index must be between 0 and length() - 1.
@return The enum value at the index location
@throws JSONException
if the key is not found or if the value cannot be converted
to an enum. | [
"Get",
"the",
"enum",
"value",
"associated",
"with",
"an",
"index",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L319-L329 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optFloat | public float optFloat(int index, float defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
final float floatValue = val.floatValue();
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
// return floatValue;
// }
return floatValue;
} | java | public float optFloat(int index, float defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
final float floatValue = val.floatValue();
// if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
// return floatValue;
// }
return floatValue;
} | [
"public",
"float",
"optFloat",
"(",
"int",
"index",
",",
"float",
"defaultValue",
")",
"{",
"final",
"Number",
"val",
"=",
"this",
".",
"optNumber",
"(",
"index",
",",
"null",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"defaultValue"... | Get the optional float value associated with an index. The defaultValue
is returned if there is no value for the index, or if the value is not a
number and cannot be converted to a number.
@param index
subscript
@param defaultValue
The default value.
@return The value. | [
"Get",
"the",
"optional",
"float",
"value",
"associated",
"with",
"an",
"index",
".",
"The",
"defaultValue",
"is",
"returned",
"if",
"there",
"is",
"no",
"value",
"for",
"the",
"index",
"or",
"if",
"the",
"value",
"is",
"not",
"a",
"number",
"and",
"cann... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L605-L615 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optInt | public int optInt(int index, int defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
return val.intValue();
} | java | public int optInt(int index, int defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
return val.intValue();
} | [
"public",
"int",
"optInt",
"(",
"int",
"index",
",",
"int",
"defaultValue",
")",
"{",
"final",
"Number",
"val",
"=",
"this",
".",
"optNumber",
"(",
"index",
",",
"null",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";... | Get the optional int value associated with an index. The defaultValue is
returned if there is no value for the index, or if the value is not a
number and cannot be converted to a number.
@param index
The index must be between 0 and length() - 1.
@param defaultValue
The default value.
@return The value. | [
"Get",
"the",
"optional",
"int",
"value",
"associated",
"with",
"an",
"index",
".",
"The",
"defaultValue",
"is",
"returned",
"if",
"there",
"is",
"no",
"value",
"for",
"the",
"index",
"or",
"if",
"the",
"value",
"is",
"not",
"a",
"number",
"and",
"cannot... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L641-L647 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optJSONArray | public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
} | java | public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
} | [
"public",
"JSONArray",
"optJSONArray",
"(",
"int",
"index",
")",
"{",
"Object",
"o",
"=",
"this",
".",
"opt",
"(",
"index",
")",
";",
"return",
"o",
"instanceof",
"JSONArray",
"?",
"(",
"JSONArray",
")",
"o",
":",
"null",
";",
"}"
] | Get the optional JSONArray associated with an index.
@param index
subscript
@return A JSONArray value, or null if the index has no value, or if the
value is not a JSONArray. | [
"Get",
"the",
"optional",
"JSONArray",
"associated",
"with",
"an",
"index",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L741-L744 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optJSONObject | public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
} | java | public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
} | [
"public",
"JSONObject",
"optJSONObject",
"(",
"int",
"index",
")",
"{",
"Object",
"o",
"=",
"this",
".",
"opt",
"(",
"index",
")",
";",
"return",
"o",
"instanceof",
"JSONObject",
"?",
"(",
"JSONObject",
")",
"o",
":",
"null",
";",
"}"
] | Get the optional JSONObject associated with an index. Null is returned if
the key is not found, or null if the index has no value, or if the value
is not a JSONObject.
@param index
The index must be between 0 and length() - 1.
@return A JSONObject value. | [
"Get",
"the",
"optional",
"JSONObject",
"associated",
"with",
"an",
"index",
".",
"Null",
"is",
"returned",
"if",
"the",
"key",
"is",
"not",
"found",
"or",
"null",
"if",
"the",
"index",
"has",
"no",
"value",
"or",
"if",
"the",
"value",
"is",
"not",
"a"... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L755-L758 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optLong | public long optLong(int index, long defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
return val.longValue();
} | java | public long optLong(int index, long defaultValue) {
final Number val = this.optNumber(index, null);
if (val == null) {
return defaultValue;
}
return val.longValue();
} | [
"public",
"long",
"optLong",
"(",
"int",
"index",
",",
"long",
"defaultValue",
")",
"{",
"final",
"Number",
"val",
"=",
"this",
".",
"optNumber",
"(",
"index",
",",
"null",
")",
";",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"defaultValue",
... | Get the optional long value associated with an index. The defaultValue is
returned if there is no value for the index, or if the value is not a
number and cannot be converted to a number.
@param index
The index must be between 0 and length() - 1.
@param defaultValue
The default value.
@return The value. | [
"Get",
"the",
"optional",
"long",
"value",
"associated",
"with",
"an",
"index",
".",
"The",
"defaultValue",
"is",
"returned",
"if",
"there",
"is",
"no",
"value",
"for",
"the",
"index",
"or",
"if",
"the",
"value",
"is",
"not",
"a",
"number",
"and",
"canno... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L784-L790 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.optString | public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object
.toString();
} | java | public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object
.toString();
} | [
"public",
"String",
"optString",
"(",
"int",
"index",
",",
"String",
"defaultValue",
")",
"{",
"Object",
"object",
"=",
"this",
".",
"opt",
"(",
"index",
")",
";",
"return",
"JSONObject",
".",
"NULL",
".",
"equals",
"(",
"object",
")",
"?",
"defaultValue... | Get the optional string associated with an index. The defaultValue is
returned if the key is not found.
@param index
The index must be between 0 and length() - 1.
@param defaultValue
The default value.
@return A String value. | [
"Get",
"the",
"optional",
"string",
"associated",
"with",
"an",
"index",
".",
"The",
"defaultValue",
"is",
"returned",
"if",
"the",
"key",
"is",
"not",
"found",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L860-L864 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.put | public JSONArray put(int index, float value) throws JSONException {
return this.put(index, Float.valueOf(value));
} | java | public JSONArray put(int index, float value) throws JSONException {
return this.put(index, Float.valueOf(value));
} | [
"public",
"JSONArray",
"put",
"(",
"int",
"index",
",",
"float",
"value",
")",
"throws",
"JSONException",
"{",
"return",
"this",
".",
"put",
"(",
"index",
",",
"Float",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Put or replace a float value. If the index is greater than the length of
the JSONArray, then null elements will be added as necessary to pad it
out.
@param index
The subscript.
@param value
A float value.
@return this.
@throws JSONException
If the index is negative or if the value is non-finite. | [
"Put",
"or",
"replace",
"a",
"float",
"value",
".",
"If",
"the",
"index",
"is",
"greater",
"than",
"the",
"length",
"of",
"the",
"JSONArray",
"then",
"null",
"elements",
"will",
"be",
"added",
"as",
"necessary",
"to",
"pad",
"it",
"out",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L1035-L1037 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONArray.java | JSONArray.write | public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
try {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: 0", e);
}
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
try {
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: " + i, e);
}
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
} | java | public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
try {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: 0", e);
}
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
try {
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONArray value at index: " + i, e);
}
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
} | [
"public",
"Writer",
"write",
"(",
"Writer",
"writer",
",",
"int",
"indentFactor",
",",
"int",
"indent",
")",
"throws",
"JSONException",
"{",
"try",
"{",
"boolean",
"commanate",
"=",
"false",
";",
"int",
"length",
"=",
"this",
".",
"length",
"(",
")",
";"... | Write the contents of the JSONArray as JSON text to a writer.
<p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
one element, then the array will be output on a single line:
<pre>{@code [1]}</pre>
<p>If an array has 2 or more elements, then it will be output across
multiple lines: <pre>{@code
[
1,
"value 2",
3
]
}</pre>
<p><b>
Warning: This method assumes that the data structure is acyclical.
</b>
@param writer
Writes the serialized JSON
@param indentFactor
The number of spaces to add to each level of indentation.
@param indent
The indentation of the top level.
@return The writer.
@throws JSONException | [
"Write",
"the",
"contents",
"of",
"the",
"JSONArray",
"as",
"JSON",
"text",
"to",
"a",
"writer",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONArray.java#L1379-L1422 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/cache/redis/RedisCache.java | RedisCache.shutdown | public static void shutdown() {
try {
Connections.shutdown();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Shutdown redis connection pool failed", e);
}
} | java | public static void shutdown() {
try {
Connections.shutdown();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Shutdown redis connection pool failed", e);
}
} | [
"public",
"static",
"void",
"shutdown",
"(",
")",
"{",
"try",
"{",
"Connections",
".",
"shutdown",
"(",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"ERROR",
",",
"\"Shutdown redis connection ... | Shutdowns redis cache. | [
"Shutdowns",
"redis",
"cache",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/cache/redis/RedisCache.java#L162-L168 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Reflections.java | Reflections.getStereotypes | public static Set<Class<? extends Annotation>> getStereotypes(final Class<?> clazz) {
final Set<Class<? extends Annotation>> ret = new HashSet<>();
final Set<Annotation> annotations = getAnnotations(clazz.getAnnotations(), Stereotype.class);
if (annotations.isEmpty()) {
return ret;
}
for (final Annotation annotation : annotations) {
ret.add(annotation.annotationType());
}
return ret;
} | java | public static Set<Class<? extends Annotation>> getStereotypes(final Class<?> clazz) {
final Set<Class<? extends Annotation>> ret = new HashSet<>();
final Set<Annotation> annotations = getAnnotations(clazz.getAnnotations(), Stereotype.class);
if (annotations.isEmpty()) {
return ret;
}
for (final Annotation annotation : annotations) {
ret.add(annotation.annotationType());
}
return ret;
} | [
"public",
"static",
"Set",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
">",
"getStereotypes",
"(",
"final",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"final",
"Set",
"<",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
">",
"ret",
"=",
"n... | Gets stereo types of the specified class.
@param clazz the specified class
@return stereo types of the specified class | [
"Gets",
"stereo",
"types",
"of",
"the",
"specified",
"class",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Reflections.java#L68-L81 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Reflections.java | Reflections.getAnnotations | private static Set<Annotation> getAnnotations(final Annotation[] annotations, final Class<? extends Annotation> neededAnnotationType) {
final Set<Annotation> ret = new HashSet<>();
for (final Annotation annotation : annotations) {
annotation.annotationType().getAnnotations();
final Annotation[] metaAnnotations = annotation.annotationType().getAnnotations();
for (final Annotation metaAnnotation : metaAnnotations) {
if (metaAnnotation.annotationType().equals(neededAnnotationType)) {
ret.add(annotation);
}
}
}
return ret;
} | java | private static Set<Annotation> getAnnotations(final Annotation[] annotations, final Class<? extends Annotation> neededAnnotationType) {
final Set<Annotation> ret = new HashSet<>();
for (final Annotation annotation : annotations) {
annotation.annotationType().getAnnotations();
final Annotation[] metaAnnotations = annotation.annotationType().getAnnotations();
for (final Annotation metaAnnotation : metaAnnotations) {
if (metaAnnotation.annotationType().equals(neededAnnotationType)) {
ret.add(annotation);
}
}
}
return ret;
} | [
"private",
"static",
"Set",
"<",
"Annotation",
">",
"getAnnotations",
"(",
"final",
"Annotation",
"[",
"]",
"annotations",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"neededAnnotationType",
")",
"{",
"final",
"Set",
"<",
"Annotation",
">",
... | Gets annotations match the needed annotation type from the specified annotation.
@param annotations the specified annotations
@param neededAnnotationType the needed annotation type
@return annotation set, returns an empty set if not found | [
"Gets",
"annotations",
"match",
"the",
"needed",
"annotation",
"type",
"from",
"the",
"specified",
"annotation",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Reflections.java#L139-L153 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Reflections.java | Reflections.getMethodVariableNames | public static String[] getMethodVariableNames(final Class<?> clazz, final String targetMethodName, final Class<?>[] types) {
CtClass cc;
CtMethod cm = null;
try {
if (null == CLASS_POOL.find(clazz.getName())) {
CLASS_POOL.insertClassPath(new ClassClassPath(clazz));
}
cc = CLASS_POOL.get(clazz.getName());
final CtClass[] ptypes = new CtClass[types.length];
for (int i = 0; i < ptypes.length; i++) {
ptypes[i] = CLASS_POOL.get(types[i].getName());
}
cm = cc.getDeclaredMethod(targetMethodName, ptypes);
} catch (final NotFoundException e) {
LOGGER.log(Level.ERROR, "Get method variable names failed", e);
}
if (null == cm) {
return new String[types.length];
}
final MethodInfo methodInfo = cm.getMethodInfo();
final CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
final LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
String[] variableNames = new String[0];
try {
variableNames = new String[cm.getParameterTypes().length];
} catch (final NotFoundException e) {
LOGGER.log(Level.ERROR, "Get method variable names failed", e);
}
// final int staticIndex = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
int j = -1;
String variableName = null;
Boolean ifkill = false;
while (!"this".equals(variableName)) {
j++;
variableName = attr.variableName(j);
// to prevent heap error when there being some unknown reasons to resolve the VariableNames
if (j > 99) {
LOGGER.log(Level.WARN,
"Maybe resolve to VariableNames error [class=" + clazz.getName() + ", targetMethodName=" + targetMethodName + ']');
ifkill = true;
break;
}
}
if (!ifkill) {
for (int i = 0; i < variableNames.length; i++) {
variableNames[i] = attr.variableName(++j);
}
}
return variableNames;
} | java | public static String[] getMethodVariableNames(final Class<?> clazz, final String targetMethodName, final Class<?>[] types) {
CtClass cc;
CtMethod cm = null;
try {
if (null == CLASS_POOL.find(clazz.getName())) {
CLASS_POOL.insertClassPath(new ClassClassPath(clazz));
}
cc = CLASS_POOL.get(clazz.getName());
final CtClass[] ptypes = new CtClass[types.length];
for (int i = 0; i < ptypes.length; i++) {
ptypes[i] = CLASS_POOL.get(types[i].getName());
}
cm = cc.getDeclaredMethod(targetMethodName, ptypes);
} catch (final NotFoundException e) {
LOGGER.log(Level.ERROR, "Get method variable names failed", e);
}
if (null == cm) {
return new String[types.length];
}
final MethodInfo methodInfo = cm.getMethodInfo();
final CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
final LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
String[] variableNames = new String[0];
try {
variableNames = new String[cm.getParameterTypes().length];
} catch (final NotFoundException e) {
LOGGER.log(Level.ERROR, "Get method variable names failed", e);
}
// final int staticIndex = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
int j = -1;
String variableName = null;
Boolean ifkill = false;
while (!"this".equals(variableName)) {
j++;
variableName = attr.variableName(j);
// to prevent heap error when there being some unknown reasons to resolve the VariableNames
if (j > 99) {
LOGGER.log(Level.WARN,
"Maybe resolve to VariableNames error [class=" + clazz.getName() + ", targetMethodName=" + targetMethodName + ']');
ifkill = true;
break;
}
}
if (!ifkill) {
for (int i = 0; i < variableNames.length; i++) {
variableNames[i] = attr.variableName(++j);
}
}
return variableNames;
} | [
"public",
"static",
"String",
"[",
"]",
"getMethodVariableNames",
"(",
"final",
"Class",
"<",
"?",
">",
"clazz",
",",
"final",
"String",
"targetMethodName",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"types",
")",
"{",
"CtClass",
"cc",
";",
"CtMetho... | Get method variable names of the specified class, target method name and parameter types.
@param clazz the specific clazz
@param targetMethodName the specified target method name
@param types the specified parameter types
@return the String[] of names | [
"Get",
"method",
"variable",
"names",
"of",
"the",
"specified",
"class",
"target",
"method",
"name",
"and",
"parameter",
"types",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Reflections.java#L163-L221 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.accumulate | public JSONObject accumulate(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key,
value instanceof JSONArray ? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
} | java | public JSONObject accumulate(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key,
value instanceof JSONArray ? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
} | [
"public",
"JSONObject",
"accumulate",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"throws",
"JSONException",
"{",
"testValidity",
"(",
"value",
")",
";",
"Object",
"object",
"=",
"this",
".",
"opt",
"(",
"key",
")",
";",
"if",
"(",
"object",
"==",... | Accumulate values under a key. It is similar to the put method except
that if there is already an object stored under the key then a JSONArray
is stored under the key to hold all of the accumulated values. If there
is already a JSONArray, then the new value is appended to it. In
contrast, the put method replaces the previous value.
If only one value is accumulated that is not a JSONArray, then the result
will be the same as using put. But if multiple values are accumulated,
then the result will be like append.
@param key
A key string.
@param value
An object to be accumulated under the key.
@return this.
@throws JSONException
If the value is non-finite number.
@throws NullPointerException
If the key is <code>null</code>. | [
"Accumulate",
"values",
"under",
"a",
"key",
".",
"It",
"is",
"similar",
"to",
"the",
"put",
"method",
"except",
"that",
"if",
"there",
"is",
"already",
"an",
"object",
"stored",
"under",
"the",
"key",
"then",
"a",
"JSONArray",
"is",
"stored",
"under",
"... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L484-L497 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.getBoolean | public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a Boolean.");
} | java | public boolean getBoolean(String key) throws JSONException {
Object object = this.get(key);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a Boolean.");
} | [
"public",
"boolean",
"getBoolean",
"(",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"Object",
"object",
"=",
"this",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"object",
".",
"equals",
"(",
"Boolean",
".",
"FALSE",
")",
"||",
"(",
"object",... | Get the boolean value associated with a key.
@param key
A key string.
@return The truth.
@throws JSONException
if the value is not a Boolean or the String "true" or
"false". | [
"Get",
"the",
"boolean",
"value",
"associated",
"with",
"a",
"key",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L608-L621 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.optJSONArray | public JSONArray optJSONArray(String key) {
Object o = this.opt(key);
return o instanceof JSONArray ? (JSONArray) o : null;
} | java | public JSONArray optJSONArray(String key) {
Object o = this.opt(key);
return o instanceof JSONArray ? (JSONArray) o : null;
} | [
"public",
"JSONArray",
"optJSONArray",
"(",
"String",
"key",
")",
"{",
"Object",
"o",
"=",
"this",
".",
"opt",
"(",
"key",
")",
";",
"return",
"o",
"instanceof",
"JSONArray",
"?",
"(",
"JSONArray",
")",
"o",
":",
"null",
";",
"}"
] | Get an optional JSONArray associated with a key. It returns null if there
is no such key, or if its value is not a JSONArray.
@param key
A key string.
@return A JSONArray which is the value. | [
"Get",
"an",
"optional",
"JSONArray",
"associated",
"with",
"a",
"key",
".",
"It",
"returns",
"null",
"if",
"there",
"is",
"no",
"such",
"key",
"or",
"if",
"its",
"value",
"is",
"not",
"a",
"JSONArray",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1321-L1324 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.populateMap | private void populateMap(Object bean) {
Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
for (final Method method : methods) {
final int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers)
&& !Modifier.isStatic(modifiers)
&& method.getParameterTypes().length == 0
&& !method.isBridge()
&& method.getReturnType() != Void.TYPE
&& isValidMethodName(method.getName())) {
final String key = getKeyNameFromMethod(method);
if (key != null && !key.isEmpty()) {
try {
final Object result = method.invoke(bean);
if (result != null) {
this.map.put(key, wrap(result));
// we don't use the result anywhere outside of wrap
// if it's a resource we should be sure to close it
// after calling toString
if (result instanceof Closeable) {
try {
((Closeable) result).close();
} catch (IOException ignore) {
}
}
}
} catch (IllegalAccessException ignore) {
} catch (IllegalArgumentException ignore) {
} catch (InvocationTargetException ignore) {
}
}
}
}
} | java | private void populateMap(Object bean) {
Class<?> klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
boolean includeSuperClass = klass.getClassLoader() != null;
Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
for (final Method method : methods) {
final int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers)
&& !Modifier.isStatic(modifiers)
&& method.getParameterTypes().length == 0
&& !method.isBridge()
&& method.getReturnType() != Void.TYPE
&& isValidMethodName(method.getName())) {
final String key = getKeyNameFromMethod(method);
if (key != null && !key.isEmpty()) {
try {
final Object result = method.invoke(bean);
if (result != null) {
this.map.put(key, wrap(result));
// we don't use the result anywhere outside of wrap
// if it's a resource we should be sure to close it
// after calling toString
if (result instanceof Closeable) {
try {
((Closeable) result).close();
} catch (IOException ignore) {
}
}
}
} catch (IllegalAccessException ignore) {
} catch (IllegalArgumentException ignore) {
} catch (InvocationTargetException ignore) {
}
}
}
}
} | [
"private",
"void",
"populateMap",
"(",
"Object",
"bean",
")",
"{",
"Class",
"<",
"?",
">",
"klass",
"=",
"bean",
".",
"getClass",
"(",
")",
";",
"// If klass is a System class then set includeSuperClass to false.",
"boolean",
"includeSuperClass",
"=",
"klass",
".",
... | Populates the internal map of the JSONObject with the bean properties. The
bean can not be recursive.
@see JSONObject#JSONObject(Object)
@param bean
the bean | [
"Populates",
"the",
"internal",
"map",
"of",
"the",
"JSONObject",
"with",
"the",
"bean",
"properties",
".",
"The",
"bean",
"can",
"not",
"be",
"recursive",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1451-L1490 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.getAnnotation | private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
// if we have invalid data the result is null
if (m == null || annotationClass == null) {
return null;
}
if (m.isAnnotationPresent(annotationClass)) {
return m.getAnnotation(annotationClass);
}
// if we've already reached the Object class, return null;
Class<?> c = m.getDeclaringClass();
if (c.getSuperclass() == null) {
return null;
}
// check directly implemented interfaces for the method being checked
for (Class<?> i : c.getInterfaces()) {
try {
Method im = i.getMethod(m.getName(), m.getParameterTypes());
return getAnnotation(im, annotationClass);
} catch (final SecurityException ex) {
continue;
} catch (final NoSuchMethodException ex) {
continue;
}
}
try {
return getAnnotation(
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
annotationClass);
} catch (final SecurityException ex) {
return null;
} catch (final NoSuchMethodException ex) {
return null;
}
} | java | private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
// if we have invalid data the result is null
if (m == null || annotationClass == null) {
return null;
}
if (m.isAnnotationPresent(annotationClass)) {
return m.getAnnotation(annotationClass);
}
// if we've already reached the Object class, return null;
Class<?> c = m.getDeclaringClass();
if (c.getSuperclass() == null) {
return null;
}
// check directly implemented interfaces for the method being checked
for (Class<?> i : c.getInterfaces()) {
try {
Method im = i.getMethod(m.getName(), m.getParameterTypes());
return getAnnotation(im, annotationClass);
} catch (final SecurityException ex) {
continue;
} catch (final NoSuchMethodException ex) {
continue;
}
}
try {
return getAnnotation(
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
annotationClass);
} catch (final SecurityException ex) {
return null;
} catch (final NoSuchMethodException ex) {
return null;
}
} | [
"private",
"static",
"<",
"A",
"extends",
"Annotation",
">",
"A",
"getAnnotation",
"(",
"final",
"Method",
"m",
",",
"final",
"Class",
"<",
"A",
">",
"annotationClass",
")",
"{",
"// if we have invalid data the result is null",
"if",
"(",
"m",
"==",
"null",
"|... | Searches the class hierarchy to see if the method or it's super
implementations and interfaces has the annotation.
@param <A>
type of the annotation
@param m
method to check
@param annotationClass
annotation to look for
@return the {@link Annotation} if the annotation exists on the current method
or one of it's super class definitions | [
"Searches",
"the",
"class",
"hierarchy",
"to",
"see",
"if",
"the",
"method",
"or",
"it",
"s",
"super",
"implementations",
"and",
"interfaces",
"has",
"the",
"annotation",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1547-L1584 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.getAnnotationDepth | private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {
// if we have invalid data the result is -1
if (m == null || annotationClass == null) {
return -1;
}
if (m.isAnnotationPresent(annotationClass)) {
return 1;
}
// if we've already reached the Object class, return -1;
Class<?> c = m.getDeclaringClass();
if (c.getSuperclass() == null) {
return -1;
}
// check directly implemented interfaces for the method being checked
for (Class<?> i : c.getInterfaces()) {
try {
Method im = i.getMethod(m.getName(), m.getParameterTypes());
int d = getAnnotationDepth(im, annotationClass);
if (d > 0) {
// since the annotation was on the interface, add 1
return d + 1;
}
} catch (final SecurityException ex) {
continue;
} catch (final NoSuchMethodException ex) {
continue;
}
}
try {
int d = getAnnotationDepth(
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
annotationClass);
if (d > 0) {
// since the annotation was on the superclass, add 1
return d + 1;
}
return -1;
} catch (final SecurityException ex) {
return -1;
} catch (final NoSuchMethodException ex) {
return -1;
}
} | java | private static int getAnnotationDepth(final Method m, final Class<? extends Annotation> annotationClass) {
// if we have invalid data the result is -1
if (m == null || annotationClass == null) {
return -1;
}
if (m.isAnnotationPresent(annotationClass)) {
return 1;
}
// if we've already reached the Object class, return -1;
Class<?> c = m.getDeclaringClass();
if (c.getSuperclass() == null) {
return -1;
}
// check directly implemented interfaces for the method being checked
for (Class<?> i : c.getInterfaces()) {
try {
Method im = i.getMethod(m.getName(), m.getParameterTypes());
int d = getAnnotationDepth(im, annotationClass);
if (d > 0) {
// since the annotation was on the interface, add 1
return d + 1;
}
} catch (final SecurityException ex) {
continue;
} catch (final NoSuchMethodException ex) {
continue;
}
}
try {
int d = getAnnotationDepth(
c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
annotationClass);
if (d > 0) {
// since the annotation was on the superclass, add 1
return d + 1;
}
return -1;
} catch (final SecurityException ex) {
return -1;
} catch (final NoSuchMethodException ex) {
return -1;
}
} | [
"private",
"static",
"int",
"getAnnotationDepth",
"(",
"final",
"Method",
"m",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
")",
"{",
"// if we have invalid data the result is -1",
"if",
"(",
"m",
"==",
"null",
"||",
"annotatio... | Searches the class hierarchy to see if the method or it's super
implementations and interfaces has the annotation. Returns the depth of the
annotation in the hierarchy.
@param <A>
type of the annotation
@param m
method to check
@param annotationClass
annotation to look for
@return Depth of the annotation or -1 if the annotation is not on the method. | [
"Searches",
"the",
"class",
"hierarchy",
"to",
"see",
"if",
"the",
"method",
"or",
"it",
"s",
"super",
"implementations",
"and",
"interfaces",
"has",
"the",
"annotation",
".",
"Returns",
"the",
"depth",
"of",
"the",
"annotation",
"in",
"the",
"hierarchy",
".... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1600-L1646 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.isDecimalNotation | protected static boolean isDecimalNotation(final String val) {
return val.indexOf('.') > -1 || val.indexOf('e') > -1
|| val.indexOf('E') > -1 || "-0".equals(val);
} | java | protected static boolean isDecimalNotation(final String val) {
return val.indexOf('.') > -1 || val.indexOf('e') > -1
|| val.indexOf('E') > -1 || "-0".equals(val);
} | [
"protected",
"static",
"boolean",
"isDecimalNotation",
"(",
"final",
"String",
"val",
")",
"{",
"return",
"val",
".",
"indexOf",
"(",
"'",
"'",
")",
">",
"-",
"1",
"||",
"val",
".",
"indexOf",
"(",
"'",
"'",
")",
">",
"-",
"1",
"||",
"val",
".",
... | Tests if the value should be tried as a decimal. It makes no test if there are actual digits.
@param val value to test
@return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. | [
"Tests",
"if",
"the",
"value",
"should",
"be",
"tried",
"as",
"a",
"decimal",
".",
"It",
"makes",
"no",
"test",
"if",
"there",
"are",
"actual",
"digits",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L2059-L2062 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.stringToNumber | protected static Number stringToNumber(final String val) throws NumberFormatException {
char initial = val.charAt(0);
if ((initial >= '0' && initial <= '9') || initial == '-') {
// decimal representation
if (isDecimalNotation(val)) {
// quick dirty way to see if we need a BigDecimal instead of a Double
// this only handles some cases of overflow or underflow
if (val.length()>14) {
return new BigDecimal(val);
}
final Double d = Double.valueOf(val);
if (d.isInfinite() || d.isNaN()) {
// if we can't parse it as a double, go up to BigDecimal
// this is probably due to underflow like 4.32e-678
// or overflow like 4.65e5324. The size of the string is small
// but can't be held in a Double.
return new BigDecimal(val);
}
return d;
}
// integer representation.
// This will narrow any values to the smallest reasonable Object representation
// (Integer, Long, or BigInteger)
// string version
// The compare string length method reduces GC,
// but leads to smaller integers being placed in larger wrappers even though not
// needed. i.e. 1,000,000,000 -> Long even though it's an Integer
// 1,000,000,000,000,000,000 -> BigInteger even though it's a Long
//if(val.length()<=9){
// return Integer.valueOf(val);
//}
//if(val.length()<=18){
// return Long.valueOf(val);
//}
//return new BigInteger(val);
// BigInteger version: We use a similar bitLenth compare as
// BigInteger#intValueExact uses. Increases GC, but objects hold
// only what they need. i.e. Less runtime overhead if the value is
// long lived. Which is the better tradeoff? This is closer to what's
// in stringToValue.
BigInteger bi = new BigInteger(val);
if(bi.bitLength()<=31){
return Integer.valueOf(bi.intValue());
}
if(bi.bitLength()<=63){
return Long.valueOf(bi.longValue());
}
return bi;
}
throw new NumberFormatException("val ["+val+"] is not a valid number.");
} | java | protected static Number stringToNumber(final String val) throws NumberFormatException {
char initial = val.charAt(0);
if ((initial >= '0' && initial <= '9') || initial == '-') {
// decimal representation
if (isDecimalNotation(val)) {
// quick dirty way to see if we need a BigDecimal instead of a Double
// this only handles some cases of overflow or underflow
if (val.length()>14) {
return new BigDecimal(val);
}
final Double d = Double.valueOf(val);
if (d.isInfinite() || d.isNaN()) {
// if we can't parse it as a double, go up to BigDecimal
// this is probably due to underflow like 4.32e-678
// or overflow like 4.65e5324. The size of the string is small
// but can't be held in a Double.
return new BigDecimal(val);
}
return d;
}
// integer representation.
// This will narrow any values to the smallest reasonable Object representation
// (Integer, Long, or BigInteger)
// string version
// The compare string length method reduces GC,
// but leads to smaller integers being placed in larger wrappers even though not
// needed. i.e. 1,000,000,000 -> Long even though it's an Integer
// 1,000,000,000,000,000,000 -> BigInteger even though it's a Long
//if(val.length()<=9){
// return Integer.valueOf(val);
//}
//if(val.length()<=18){
// return Long.valueOf(val);
//}
//return new BigInteger(val);
// BigInteger version: We use a similar bitLenth compare as
// BigInteger#intValueExact uses. Increases GC, but objects hold
// only what they need. i.e. Less runtime overhead if the value is
// long lived. Which is the better tradeoff? This is closer to what's
// in stringToValue.
BigInteger bi = new BigInteger(val);
if(bi.bitLength()<=31){
return Integer.valueOf(bi.intValue());
}
if(bi.bitLength()<=63){
return Long.valueOf(bi.longValue());
}
return bi;
}
throw new NumberFormatException("val ["+val+"] is not a valid number.");
} | [
"protected",
"static",
"Number",
"stringToNumber",
"(",
"final",
"String",
"val",
")",
"throws",
"NumberFormatException",
"{",
"char",
"initial",
"=",
"val",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"(",
"initial",
">=",
"'",
"'",
"&&",
"initial",
"... | Converts a string to a number using the narrowest possible type. Possible
returns for this function are BigDecimal, Double, BigInteger, Long, and Integer.
When a Double is returned, it should always be a valid Double and not NaN or +-infinity.
@param val value to convert
@return Number representation of the value.
@throws NumberFormatException thrown if the value is not a valid number. A public
caller should catch this and wrap it in a {@link JSONException} if applicable. | [
"Converts",
"a",
"string",
"to",
"a",
"number",
"using",
"the",
"narrowest",
"possible",
"type",
".",
"Possible",
"returns",
"for",
"this",
"function",
"are",
"BigDecimal",
"Double",
"BigInteger",
"Long",
"and",
"Integer",
".",
"When",
"a",
"Double",
"is",
"... | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L2074-L2126 | train |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.write | public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
writer.write('{');
if (length == 1) {
final Entry<String,?> entry = this.entrySet().iterator().next();
final String key = entry.getKey();
writer.write(quote(key));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
try{
writeValue(writer, entry.getValue(), indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (final Entry<String,?> entry : this.entrySet()) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, newindent);
final String key = entry.getKey();
writer.write(quote(key));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
try {
writeValue(writer, entry.getValue(), indentFactor, newindent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, indent);
}
writer.write('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
} | java | public Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
writer.write('{');
if (length == 1) {
final Entry<String,?> entry = this.entrySet().iterator().next();
final String key = entry.getKey();
writer.write(quote(key));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
try{
writeValue(writer, entry.getValue(), indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (final Entry<String,?> entry : this.entrySet()) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, newindent);
final String key = entry.getKey();
writer.write(quote(key));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
try {
writeValue(writer, entry.getValue(), indentFactor, newindent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, indent);
}
writer.write('}');
return writer;
} catch (IOException exception) {
throw new JSONException(exception);
}
} | [
"public",
"Writer",
"write",
"(",
"Writer",
"writer",
",",
"int",
"indentFactor",
",",
"int",
"indent",
")",
"throws",
"JSONException",
"{",
"try",
"{",
"boolean",
"commanate",
"=",
"false",
";",
"final",
"int",
"length",
"=",
"this",
".",
"length",
"(",
... | Write the contents of the JSONObject as JSON text to a writer.
<p>If <code>indentFactor > 0</code> and the {@link JSONObject}
has only one key, then the object will be output on a single line:
<pre>{@code {"key": 1}}</pre>
<p>If an object has 2 or more keys, then it will be output across
multiple lines: <code><pre>{
"key1": 1,
"key2": "value 2",
"key3": 3
}</pre></code>
<p><b>
Warning: This method assumes that the data structure is acyclical.
</b>
@param writer
Writes the serialized JSON
@param indentFactor
The number of spaces to add to each level of indentation.
@param indent
The indentation of the top level.
@return The writer.
@throws JSONException | [
"Write",
"the",
"contents",
"of",
"the",
"JSONObject",
"as",
"JSON",
"text",
"to",
"a",
"writer",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L2463-L2516 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Templates.java | Templates.hasExpression | public static boolean hasExpression(final Template template, final String expression) {
final TemplateElement rootTreeNode = template.getRootTreeNode();
return hasExpression(template, expression, rootTreeNode);
} | java | public static boolean hasExpression(final Template template, final String expression) {
final TemplateElement rootTreeNode = template.getRootTreeNode();
return hasExpression(template, expression, rootTreeNode);
} | [
"public",
"static",
"boolean",
"hasExpression",
"(",
"final",
"Template",
"template",
",",
"final",
"String",
"expression",
")",
"{",
"final",
"TemplateElement",
"rootTreeNode",
"=",
"template",
".",
"getRootTreeNode",
"(",
")",
";",
"return",
"hasExpression",
"("... | Determines whether exists a variable specified by the given expression
in the specified template.
@param template the specified template
@param expression the given expression, for example,
"${aVariable}", "<#list recentComments as comment>"
@return {@code true} if it exists, returns {@code false} otherwise | [
"Determines",
"whether",
"exists",
"a",
"variable",
"specified",
"by",
"the",
"given",
"expression",
"in",
"the",
"specified",
"template",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Templates.java#L53-L57 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Execs.java | Execs.exec | public static String exec(final String cmd, final long timeout) {
final StringTokenizer st = new StringTokenizer(cmd);
final String[] cmds = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
cmds[i] = st.nextToken();
}
return exec(cmds, timeout);
} | java | public static String exec(final String cmd, final long timeout) {
final StringTokenizer st = new StringTokenizer(cmd);
final String[] cmds = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
cmds[i] = st.nextToken();
}
return exec(cmds, timeout);
} | [
"public",
"static",
"String",
"exec",
"(",
"final",
"String",
"cmd",
",",
"final",
"long",
"timeout",
")",
"{",
"final",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"cmd",
")",
";",
"final",
"String",
"[",
"]",
"cmds",
"=",
"new",
"Strin... | Executes the specified command with the specified timeout.
@param cmd the specified command
@param timeout the specified timeout
@return execution output, returns {@code null} if execution failed | [
"Executes",
"the",
"specified",
"command",
"with",
"the",
"specified",
"timeout",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Execs.java#L48-L56 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/util/Execs.java | Execs.exec | public static String exec(final String[] cmds, final long timeout) {
try {
final Process process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
final StringWriter writer = new StringWriter();
new Thread(() -> {
try {
IOUtils.copy(process.getInputStream(), writer, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads input stream failed: " + e.getMessage());
}
}).start();
if (!process.waitFor(timeout, TimeUnit.MILLISECONDS)) {
LOGGER.log(Level.WARN, "Executes commands [" + Arrays.toString(cmds) + "] timeout");
process.destroy();
}
return writer.toString();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Executes commands [" + Arrays.toString(cmds) + "] failed", e);
return null;
}
} | java | public static String exec(final String[] cmds, final long timeout) {
try {
final Process process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
final StringWriter writer = new StringWriter();
new Thread(() -> {
try {
IOUtils.copy(process.getInputStream(), writer, "UTF-8");
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Reads input stream failed: " + e.getMessage());
}
}).start();
if (!process.waitFor(timeout, TimeUnit.MILLISECONDS)) {
LOGGER.log(Level.WARN, "Executes commands [" + Arrays.toString(cmds) + "] timeout");
process.destroy();
}
return writer.toString();
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Executes commands [" + Arrays.toString(cmds) + "] failed", e);
return null;
}
} | [
"public",
"static",
"String",
"exec",
"(",
"final",
"String",
"[",
"]",
"cmds",
",",
"final",
"long",
"timeout",
")",
"{",
"try",
"{",
"final",
"Process",
"process",
"=",
"new",
"ProcessBuilder",
"(",
"cmds",
")",
".",
"redirectErrorStream",
"(",
"true",
... | Executes the specified commands with the specified timeout.
@param cmds the specified commands
@param timeout the specified timeout in milliseconds
@return execution output, returns {@code null} if execution failed | [
"Executes",
"the",
"specified",
"commands",
"with",
"the",
"specified",
"timeout",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Execs.java#L65-L88 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/cache/CacheFactory.java | CacheFactory.getCache | public static synchronized Cache getCache(final String cacheName) {
LOGGER.log(Level.INFO, "Constructing cache [name={0}]....", cacheName);
Cache ret = CACHES.get(cacheName);
try {
if (null == ret) {
Class<Cache> cacheClass;
switch (Latkes.getRuntimeCache()) {
case LOCAL_LRU:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.caffeine.CaffeineCache");
break;
case REDIS:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.redis.RedisCache");
break;
case NONE:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.NoneCache");
break;
default:
throw new RuntimeException("Latke runs in the hell.... Please set the environment correctly");
}
ret = cacheClass.newInstance();
ret.setName(cacheName);
CACHES.put(cacheName, ret);
}
} catch (final Exception e) {
throw new RuntimeException("Can not get cache: " + e.getMessage(), e);
}
LOGGER.log(Level.INFO, "Constructed cache [name={0}, runtime={1}]", cacheName, Latkes.getRuntimeCache());
return ret;
} | java | public static synchronized Cache getCache(final String cacheName) {
LOGGER.log(Level.INFO, "Constructing cache [name={0}]....", cacheName);
Cache ret = CACHES.get(cacheName);
try {
if (null == ret) {
Class<Cache> cacheClass;
switch (Latkes.getRuntimeCache()) {
case LOCAL_LRU:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.caffeine.CaffeineCache");
break;
case REDIS:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.redis.RedisCache");
break;
case NONE:
cacheClass = (Class<Cache>) Class.forName("org.b3log.latke.cache.NoneCache");
break;
default:
throw new RuntimeException("Latke runs in the hell.... Please set the environment correctly");
}
ret = cacheClass.newInstance();
ret.setName(cacheName);
CACHES.put(cacheName, ret);
}
} catch (final Exception e) {
throw new RuntimeException("Can not get cache: " + e.getMessage(), e);
}
LOGGER.log(Level.INFO, "Constructed cache [name={0}, runtime={1}]", cacheName, Latkes.getRuntimeCache());
return ret;
} | [
"public",
"static",
"synchronized",
"Cache",
"getCache",
"(",
"final",
"String",
"cacheName",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Constructing cache [name={0}]....\"",
",",
"cacheName",
")",
";",
"Cache",
"ret",
"=",
"CACHES",
".... | Gets a cache specified by the given cache name.
@param cacheName the given cache name
@return a cache specified by the given cache name | [
"Gets",
"a",
"cache",
"specified",
"by",
"the",
"given",
"cache",
"name",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/cache/CacheFactory.java#L56-L93 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/cache/CacheFactory.java | CacheFactory.clear | public static synchronized void clear() {
for (final Map.Entry<String, Cache> entry : CACHES.entrySet()) {
final Cache cache = entry.getValue();
cache.clear();
LOGGER.log(Level.TRACE, "Cleared cache [name={0}]", entry.getKey());
}
} | java | public static synchronized void clear() {
for (final Map.Entry<String, Cache> entry : CACHES.entrySet()) {
final Cache cache = entry.getValue();
cache.clear();
LOGGER.log(Level.TRACE, "Cleared cache [name={0}]", entry.getKey());
}
} | [
"public",
"static",
"synchronized",
"void",
"clear",
"(",
")",
"{",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"String",
",",
"Cache",
">",
"entry",
":",
"CACHES",
".",
"entrySet",
"(",
")",
")",
"{",
"final",
"Cache",
"cache",
"=",
"entry",
".",... | Clears all caches. | [
"Clears",
"all",
"caches",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/cache/CacheFactory.java#L98-L104 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java | RequestContext.getDataModel | public Map<String, Object> getDataModel() {
final AbstractResponseRenderer renderer = getRenderer();
if (null == renderer) {
return null;
}
return renderer.getRenderDataModel();
} | java | public Map<String, Object> getDataModel() {
final AbstractResponseRenderer renderer = getRenderer();
if (null == renderer) {
return null;
}
return renderer.getRenderDataModel();
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"getDataModel",
"(",
")",
"{",
"final",
"AbstractResponseRenderer",
"renderer",
"=",
"getRenderer",
"(",
")",
";",
"if",
"(",
"null",
"==",
"renderer",
")",
"{",
"return",
"null",
";",
"}",
"return",
"r... | Gets the data model of renderer bound with this context.
@return data model, returns {@code null} if not found | [
"Gets",
"the",
"data",
"model",
"of",
"renderer",
"bound",
"with",
"this",
"context",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java#L146-L153 | train |
b3log/latke | latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java | RequestContext.sendRedirect | public void sendRedirect(final String location) {
try {
response.sendRedirect(location);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Sends redirect [" + location + "] failed: " + e.getMessage());
}
} | java | public void sendRedirect(final String location) {
try {
response.sendRedirect(location);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Sends redirect [" + location + "] failed: " + e.getMessage());
}
} | [
"public",
"void",
"sendRedirect",
"(",
"final",
"String",
"location",
")",
"{",
"try",
"{",
"response",
".",
"sendRedirect",
"(",
"location",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"log",
"(",
"Level",
".",
"ER... | Sends redirect to the specified location.
@param location the specified location | [
"Sends",
"redirect",
"to",
"the",
"specified",
"location",
"."
] | f7e08a47eeecea5f7c94006382c24f353585de33 | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/servlet/RequestContext.java#L169-L175 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.