_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q180100
Controller.template
test
protected String template(String view) { final Enumeration<String> attrs = getAttrNames(); final Map<String, Object> root = Maps.newHashMap(); while (attrs.hasMoreElements()) { String attrName = attrs.nextElement(); root.put(attrName, getAttr(attrName)); } return Freemarkers.processString(view, root); }
java
{ "resource": "" }
q180101
Controller.parsePath
test
protected String parsePath(String currentActionPath, String url) { if (url.startsWith(SLASH)) { return url.split("\\?")[0]; } else if (!url.contains(SLASH)) { return SLASH + currentActionPath.split(SLASH)[1] + SLASH + url.split("\\?")[0]; } else if (url.contains("http:") || url.contains("https:")) { return null; } ///abc/def","bcd/efg?abc return currentActionPath + SLASH + url.split("\\?")[0]; }
java
{ "resource": "" }
q180102
Controller.renderDataTables
test
protected void renderDataTables(Class<? extends Model> m_cls) { DTCriterias criterias = getCriterias(); Preconditions.checkNotNull(criterias, "datatable criterias is must be not null."); DTResponse response = criterias.response(m_cls); renderJson(response); }
java
{ "resource": "" }
q180103
Controller.renderEmptyDataTables
test
protected void renderEmptyDataTables(DTCriterias criterias) { Preconditions.checkNotNull(criterias, "datatable criterias is must be not null."); DTResponse response = DTResponse.build(criterias, Collections.EMPTY_LIST, 0, 0); renderJson(response); }
java
{ "resource": "" }
q180104
ComboBoxEditingSupport.setItems
test
public void setItems(List<V> items) { final List<V> its = items == null ? ImmutableList.of() : items; this.items = its; getComboBoxCellEditor().setInput(items); }
java
{ "resource": "" }
q180105
Redirect.to
test
public void to(WebContext context) { HttpServletResponse response = context.response(); if (!mediaType.isEmpty()) { response.setHeader("Content-Type", mediaType); } if (status > 0) { response.setStatus(status); } try { response.sendRedirect(response.encodeRedirectURL(url)); } catch (IOException e) { throw new UncheckedException(e); } }
java
{ "resource": "" }
q180106
ExtensionList.list
test
public List<T> list(Injector injector) { List<T> r = new ArrayList<T>(); for (Injector i= injector; i!=null; i=i.getParent()) { for (Entry<Key<?>, Binding<?>> e : i.getBindings().entrySet()) { if (e.getKey().getTypeLiteral().equals(type)) r.add((T)e.getValue().getProvider().get()); } } return r; }
java
{ "resource": "" }
q180107
RuntimeKit.currentMethod
test
public static String currentMethod() { StackTraceElement[] ste = new Exception().getStackTrace(); int ndx = (ste.length > 1) ? 1 : 0; return new Exception().getStackTrace()[ndx].toString(); }
java
{ "resource": "" }
q180108
RuntimeKit.compactMemory
test
public static void compactMemory() { try { final byte[][] unused = new byte[128][]; for (int i = unused.length; i-- != 0; ) { unused[i] = new byte[2000000000]; } } catch (OutOfMemoryError ignore) { } System.gc(); }
java
{ "resource": "" }
q180109
LogUtil.propagate
test
@Nullable public static MetricsCollection propagate(Metrics metrics) { final MetricsCollection metricsCollection = getLocalMetricsCollection(); if (metricsCollection != null) { metricsCollection.add(metrics); } return metricsCollection; }
java
{ "resource": "" }
q180110
LogUtil.encodeString
test
public static String encodeString(String value) { int estimatedSize = 0; final int len = value.length(); // estimate output string size to find out whether encoding is required and avoid reallocations in string builder for (int i = 0; i < len; ++i) { final char ch = value.charAt(i); if (ch <= ' ' || ch == ',') { estimatedSize += 3; continue; } ++estimatedSize; } if (value.length() == estimatedSize) { return value; // return value as is - it does not contain any special characters } final StringBuilder builder = new StringBuilder(estimatedSize); for (int i = 0; i < len; ++i) { final char ch = value.charAt(i); if (ch <= ' ') { builder.append("%20"); continue; } if (ch == ',') { builder.append("%2c"); continue; } builder.append(ch); } return builder.toString(); }
java
{ "resource": "" }
q180111
FileEncodingKit.charset
test
public static Optional<Charset> charset(File file) { if (!file.exists()) { logger.error("The file [ {} ] is not exist.", file.getAbsolutePath()); return Optional.absent(); } FileInputStream fileInputStream = null; BufferedInputStream bin = null; try { fileInputStream = new FileInputStream(file); bin = new BufferedInputStream(fileInputStream); int p = (bin.read() << 8) + bin.read(); Optional<Charset> charset; //其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数 switch (p) { case 0xefbb: charset = Optional.of(Charsets.UTF_8); break; case 0xfffe: charset = Optional.of(Charset.forName("Unicode")); break; case 0xfeff: charset = Optional.of(Charsets.UTF_16BE); break; case 0x5c75: charset = Optional.of(Charsets.US_ASCII); break; default: charset = Optional.of(Charset.forName("GBK")); } return charset; } catch (FileNotFoundException e) { logger.error("The file [ {} ] is not exist.", file.getAbsolutePath(), e); } catch (IOException e) { logger.error("Read file has error, {}.", file.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(bin); } return Optional.absent(); }
java
{ "resource": "" }
q180112
StreamUtil.copy
test
public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[ioBufferSize]; int count = 0; int read; while (true) { read = input.read(buffer, 0, ioBufferSize); if (read == -1) { break; } output.write(buffer, 0, read); count += read; } return count; }
java
{ "resource": "" }
q180113
StreamUtil.copy
test
public static int copy(InputStream input, OutputStream output, int byteCount) throws IOException { byte buffer[] = new byte[ioBufferSize]; int count = 0; int read; while (byteCount > 0) { if (byteCount < ioBufferSize) { read = input.read(buffer, 0, byteCount); } else { read = input.read(buffer, 0, ioBufferSize); } if (read == -1) { break; } byteCount -= read; count += read; output.write(buffer, 0, read); } return count; }
java
{ "resource": "" }
q180114
StreamUtil.copy
test
public static void copy(InputStream input, Writer output) throws IOException { copy(input, output, Const.DEFAULT_ENCODING); }
java
{ "resource": "" }
q180115
StreamUtil.copy
test
public static int copy(Reader input, Writer output) throws IOException { char[] buffer = new char[ioBufferSize]; int count = 0; int read; while ((read = input.read(buffer, 0, ioBufferSize)) >= 0) { output.write(buffer, 0, read); count += read; } output.flush(); return count; }
java
{ "resource": "" }
q180116
StreamUtil.copy
test
public static int copy(Reader input, Writer output, int charCount) throws IOException { char buffer[] = new char[ioBufferSize]; int count = 0; int read; while (charCount > 0) { if (charCount < ioBufferSize) { read = input.read(buffer, 0, charCount); } else { read = input.read(buffer, 0, ioBufferSize); } if (read == -1) { break; } charCount -= read; count += read; output.write(buffer, 0, read); } return count; }
java
{ "resource": "" }
q180117
StreamUtil.copy
test
public static void copy(Reader input, OutputStream output) throws IOException { copy(input, output, Const.DEFAULT_ENCODING); }
java
{ "resource": "" }
q180118
StreamUtil.copy
test
public static void copy(Reader input, OutputStream output, String encoding) throws IOException { Writer out = new OutputStreamWriter(output, encoding); copy(input, out); out.flush(); }
java
{ "resource": "" }
q180119
StreamUtil.compare
test
public static boolean compare(InputStream input1, InputStream input2) throws IOException { if (!(input1 instanceof BufferedInputStream)) { input1 = new BufferedInputStream(input1); } if (!(input2 instanceof BufferedInputStream)) { input2 = new BufferedInputStream(input2); } int ch = input1.read(); while (ch != -1) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return (ch2 == -1); }
java
{ "resource": "" }
q180120
StreamUtil.compare
test
public static boolean compare(Reader input1, Reader input2) throws IOException { if (!(input1 instanceof BufferedReader)) { input1 = new BufferedReader(input1); } if (!(input2 instanceof BufferedReader)) { input2 = new BufferedReader(input2); } int ch = input1.read(); while (ch != -1) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return (ch2 == -1); }
java
{ "resource": "" }
q180121
Pipeline.apply
test
@SuppressWarnings("unchecked") public T apply(T io) { logger.debug("Pipeline began"); try { for (int i = 0; i < stages.size(); i++) { Object stage = stages.get(i); String name = names.get(stage); logger.debug("Stage-" + i + ((name != null && !name.isEmpty()) ? " [" + name + "] " : " ") + "processing"); if (stage instanceof Function) { if ((io = ((Function<T, T>) stage).apply(io)) == null) { return io; } } else if (stage instanceof Predicate) { if (!((Predicate<T>) stage).apply(io)) { return io; } } } return io; } finally { logger.debug("Pipeline ended"); } }
java
{ "resource": "" }
q180122
SqlKit.sql
test
public static String sql(String groupNameAndsqlId) { final SqlNode sqlNode = SQL_MAP.get(groupNameAndsqlId); return sqlNode == null ? StringPool.EMPTY : sqlNode.sql; }
java
{ "resource": "" }
q180123
JaxbKit.unmarshal
test
@SuppressWarnings("unchecked") public static <T> T unmarshal(String src, Class<T> clazz) { T result = null; try { Unmarshaller avm = JAXBContext.newInstance(clazz).createUnmarshaller(); result = (T) avm.unmarshal(new StringReader(src)); } catch (JAXBException e) { Throwables.propagate(e); } return result; }
java
{ "resource": "" }
q180124
ZipKit.unzip
test
public static void unzip(File zipFile, File destDir, String... patterns) throws IOException { ZipFile zip = new ZipFile(zipFile); Enumeration zipEntries = zip.entries(); while (zipEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipEntries.nextElement(); String entryName = entry.getName(); if (patterns != null && patterns.length > 0) { if (Wildcard.matchPathOne(entryName, patterns) == -1) { continue; } } File file = (destDir != null) ? new File(destDir, entryName) : new File(entryName); if (entry.isDirectory()) { if (!file.mkdirs()) { if (!file.isDirectory()) { throw new IOException("Failed to create directory: " + file); } } } else { File parent = file.getParentFile(); if (parent != null && !parent.exists()) { if (!parent.mkdirs()) { if (!file.isDirectory()) { throw new IOException("Failed to create directory: " + parent); } } } InputStream in = zip.getInputStream(entry); OutputStream out = null; try { out = new FileOutputStream(file); StreamUtil.copy(in, out); } finally { StreamUtil.close(out); StreamUtil.close(in); } } } close(zip); }
java
{ "resource": "" }
q180125
PermissionDialogFragment.getInstance
test
public static PermissionDialogFragment getInstance(PermBean bean, int requestCode) { if (bean == null) throw new NullPointerException("Permission Beans cannot be null !"); Bundle extras = new Bundle(3); // convert map to two arrays. HashMap<Permission, String> map = (HashMap<Permission, String>) bean.getPermissions(); // put arrays in extras. extras.putSerializable(PERMISSION, map); extras.putInt(REQUEST, requestCode); // set extras in fragment and return. PermissionDialogFragment fragment = new PermissionDialogFragment(); fragment.setArguments(extras); return fragment; }
java
{ "resource": "" }
q180126
PermissionDialogFragment.onResume
test
@Override public void onResume() { super.onResume(); getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent keyEvent) { return keyCode != KeyEvent.ACTION_DOWN; } }); }
java
{ "resource": "" }
q180127
Types.addCoreValueType
test
public static void addCoreValueType(Class<?> clazz, Converter converter) { ConvertUtils.register(converter, clazz); values.add(clazz); }
java
{ "resource": "" }
q180128
Validator.match
test
public static boolean match(String regex, String value) { Pattern pattern = Pattern.compile(regex); return pattern.matcher(value).find(); }
java
{ "resource": "" }
q180129
Validator.isMobile
test
public static boolean isMobile(String value) { String check = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$"; return match(check, Pattern.CASE_INSENSITIVE, value); }
java
{ "resource": "" }
q180130
Validator.isPhone
test
public static boolean isPhone(String value) { String telcheck = "^\\d{3,4}-?\\d{7,9}$"; String mobilecheck = "^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\\d{8})$"; return match(telcheck, Pattern.CASE_INSENSITIVE, value) || match(mobilecheck, Pattern.CASE_INSENSITIVE, value); }
java
{ "resource": "" }
q180131
Validator.isBirthDay
test
public static boolean isBirthDay(String value) { String check = "(\\d{4})(/|-|\\.)(\\d{1,2})(/|-|\\.)(\\d{1,2})$"; if (match(check, Pattern.CASE_INSENSITIVE, value)) { int year = Integer.parseInt(value.substring(0, 4)); int month = Integer.parseInt(value.substring(5, 7)); int day = Integer.parseInt(value.substring(8, 10)); if (month < 1 || month > 12) { return false; } if (day < 1 || day > 31) { return false; } if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) { return false; } if (month == 2) { boolean isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day > 29 || (day == 29 && !isleap)) { return false; } } return true; } else { return false; } }
java
{ "resource": "" }
q180132
Validator.isUrl
test
public static boolean isUrl(String value) { String check = "^((https?|ftp):\\/\\/)?(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)*)*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$"; return match(check, Pattern.CASE_INSENSITIVE, value); }
java
{ "resource": "" }
q180133
Validator.isDateTime
test
public static boolean isDateTime(String value) { String check = "^(\\d{4})(/|-|\\.|年)(\\d{1,2})(/|-|\\.|月)(\\d{1,2})(日)?(\\s+\\d{1,2}(:|时)\\d{1,2}(:|分)?(\\d{1,2}(秒)?)?)?$";// check = "^(\\d{4})(/|-|\\.)(\\d{1,2})(/|-|\\.)(\\d{1,2})$"; return match(check, Pattern.CASE_INSENSITIVE, value); }
java
{ "resource": "" }
q180134
BootlegFilter.doFilter
test
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { pipeline.apply(new WebContext(configuration, (HttpServletRequest) request, (HttpServletResponse) response, chain)); } catch (Exception e) { logger.warn("Failed to process HTTP request", e); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
java
{ "resource": "" }
q180135
Codec.encodeBASE64
test
public static String encodeBASE64(String value) { try { return new String(Base64.encodeBase64(value.getBytes(StringPool.UTF_8))); } catch (UnsupportedEncodingException ex) { throw new UnexpectedException(ex); } }
java
{ "resource": "" }
q180136
Codec.decodeBASE64
test
public static byte[] decodeBASE64(String value) { try { return Base64.decodeBase64(value.getBytes(StringPool.UTF_8)); } catch (UnsupportedEncodingException ex) { throw new UnexpectedException(ex); } }
java
{ "resource": "" }
q180137
Codec.hexStringToByte
test
public static byte[] hexStringToByte(String hexString) { try { return Hex.decodeHex(hexString.toCharArray()); } catch (DecoderException e) { throw new UnexpectedException(e); } }
java
{ "resource": "" }
q180138
IO.readUtf8Properties
test
public static Properties readUtf8Properties(InputStream is) { Properties properties = new OrderSafeProperties(); try { properties.load(is); is.close(); } catch (Exception e) { throw new RuntimeException(e); } return properties; }
java
{ "resource": "" }
q180139
IO.readContentAsString
test
public static String readContentAsString(InputStream is, String encoding) { String res = null; try { res = IOUtils.toString(is, encoding); } catch (Exception e) { throw new RuntimeException(e); } finally { try { is.close(); } catch (Exception e) { // } } return res; }
java
{ "resource": "" }
q180140
IO.readContentAsString
test
public static String readContentAsString(File file, String encoding) { InputStream is = null; try { is = new FileInputStream(file); StringWriter result = new StringWriter(); PrintWriter out = new PrintWriter(result); BufferedReader reader = new BufferedReader(new InputStreamReader(is, encoding)); String line = null; while ((line = reader.readLine()) != null) { out.println(line); } return result.toString(); } catch (IOException e) { throw new UnexpectedException(e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { // } } } }
java
{ "resource": "" }
q180141
IO.write
test
public static void write(byte[] data, File file) { OutputStream os = null; try { os = new FileOutputStream(file); os.write(data); os.flush(); } catch (IOException e) { throw new UnexpectedException(e); } finally { try { if (os != null) os.close(); } catch (Exception e) { // } } }
java
{ "resource": "" }
q180142
IO.copyDirectory
test
public static void copyDirectory(File source, File target) { if (source.isDirectory()) { if (!target.exists()) { target.mkdir(); } for (String child : source.list()) { copyDirectory(new File(source, child), new File(target, child)); } } else { try { write(new FileInputStream(source), new FileOutputStream(target)); } catch (IOException e) { throw new UnexpectedException(e); } } }
java
{ "resource": "" }
q180143
XML.serialize
test
public static String serialize(Document document) { StringWriter writer = new StringWriter(); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(writer); transformer.transform(domSource, streamResult); } catch (TransformerException e) { throw new RuntimeException( "Error when serializing XML document.", e); } return writer.toString(); }
java
{ "resource": "" }
q180144
XML.getDocument
test
public static Document getDocument(File file) { try { return newDocumentBuilder().parse(file); } catch (SAXException e) { logger.warn("Parsing error when building Document object from xml file '" + file + "'.", e); } catch (IOException e) { logger.warn("Reading error when building Document object from xml file '" + file + "'.", e); } return null; }
java
{ "resource": "" }
q180145
XML.getDocument
test
public static Document getDocument(String xml) { InputSource source = new InputSource(new StringReader(xml)); try { return newDocumentBuilder().parse(source); } catch (SAXException e) { logger.warn("Parsing error when building Document object from xml data.", e); } catch (IOException e) { logger.warn("Reading error when building Document object from xml data.", e); } return null; }
java
{ "resource": "" }
q180146
XML.getDocument
test
public static Document getDocument(InputStream stream) { try { return newDocumentBuilder().parse(stream); } catch (SAXException e) { logger.warn("Parsing error when building Document object from xml data.", e); } catch (IOException e) { logger.warn("Reading error when building Document object from xml data.", e); } return null; }
java
{ "resource": "" }
q180147
XML.validSignature
test
public static boolean validSignature(Document document, Key publicKey) { Node signatureNode = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature").item(0); KeySelector keySelector = KeySelector.singletonKeySelector(publicKey); try { String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureNode); XMLSignature signature = fac.unmarshalXMLSignature(valContext); return signature.validate(valContext); } catch (Exception e) { logger.warn("Error validating an XML signature.", e); return false; } }
java
{ "resource": "" }
q180148
XML.sign
test
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory(); try { Reference ref = fac.newReference( "", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList( fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement()); KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey); KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue)); XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); } catch (Exception e) { logger.warn("Error while signing an XML document.", e); } return document; }
java
{ "resource": "" }
q180149
ClassKit.isCacheSafe
test
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) { Preconditions.checkNotNull(clazz, "Class must not be null"); try { ClassLoader target = clazz.getClassLoader(); if (target == null) { return true; } ClassLoader cur = classLoader; if (cur == target) { return true; } while (cur != null) { cur = cur.getParent(); if (cur == target) { return true; } } return false; } catch (SecurityException ex) { // Probably from the system ClassLoader - let's consider it safe. return true; } }
java
{ "resource": "" }
q180150
ClassKit.isPrimitiveArray
test
public static boolean isPrimitiveArray(Class<?> clazz) { Preconditions.checkNotNull(clazz, "Class must not be null"); return (clazz.isArray() && clazz.getComponentType().isPrimitive()); }
java
{ "resource": "" }
q180151
ClassKit.isPrimitiveWrapperArray
test
public static boolean isPrimitiveWrapperArray(Class<?> clazz) { Preconditions.checkNotNull(clazz, "Class must not be null"); return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType())); }
java
{ "resource": "" }
q180152
ClassKit.resolvePrimitiveIfNecessary
test
public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) { Preconditions.checkNotNull(clazz, "Class must not be null"); return (clazz.isPrimitive() && clazz != void.class ? primitiveTypeToWrapperMap.get(clazz) : clazz); }
java
{ "resource": "" }
q180153
ClassKit.isAssignable
test
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) { Preconditions.checkNotNull(lhsType, "Left-hand side type must not be null"); Preconditions.checkNotNull(rhsType, "Right-hand side type must not be null"); if (lhsType.isAssignableFrom(rhsType)) { return true; } if (lhsType.isPrimitive()) { Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType); if (resolvedPrimitive != null && lhsType.equals(resolvedPrimitive)) { return true; } } else { Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType); if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) { return true; } } return false; }
java
{ "resource": "" }
q180154
ClassKit.isAssignableValue
test
public static boolean isAssignableValue(Class<?> type, Object value) { Preconditions.checkNotNull(type, "Type must not be null"); return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive()); }
java
{ "resource": "" }
q180155
ClassKit.getAllInterfaces
test
public static Class<?>[] getAllInterfaces(Object instance) { Preconditions.checkNotNull(instance, "Instance must not be null"); return getAllInterfacesForClass(instance.getClass()); }
java
{ "resource": "" }
q180156
ClassKit.getAllInterfacesAsSet
test
public static Set<Class<?>> getAllInterfacesAsSet(Object instance) { Preconditions.checkNotNull(instance, "Instance must not be null"); return getAllInterfacesForClassAsSet(instance.getClass()); }
java
{ "resource": "" }
q180157
TempConfiguration.writeToTempFile
test
public URL writeToTempFile() throws IOException { final File tempConfigFile = File.createTempFile("brikar-tempconfig-", ".properties"); tempConfigFile.deleteOnExit(); // store properties final Properties props = new Properties(); props.putAll(properties); try (final FileOutputStream fileOutputStream = new FileOutputStream(tempConfigFile)) { props.store(fileOutputStream, "[brikar-maintenance] TempConfiguration - Autogenerated properties"); } return tempConfigFile.toURI().toURL(); }
java
{ "resource": "" }
q180158
URITemplate.variables
test
public Map<String, String> variables(String uri) { Map<String, String> variables = new HashMap<String, String>(); Matcher matcher = pattern.matcher(uri); if (matcher.matches()) { for (int i = 0; i < matcher.groupCount(); i++) { variables.put(this.variables.get(i), matcher.group(i + 1)); } } return variables; }
java
{ "resource": "" }
q180159
PermBean.put
test
public PermBean put(Permission permission, String message) { if (permission == null) throw new IllegalArgumentException("Permission can't be null"); mPermissions.put(permission, message); return this; }
java
{ "resource": "" }
q180160
DruidDbIntializer.druidPlugin
test
public static DruidPlugin druidPlugin( Properties dbProp ) { String dbUrl = dbProp.getProperty(GojaPropConst.DBURL), username = dbProp.getProperty(GojaPropConst.DBUSERNAME), password = dbProp.getProperty(GojaPropConst.DBPASSWORD); if (!Strings.isNullOrEmpty(dbUrl)) { String dbtype = JdbcUtils.getDbType(dbUrl, StringUtils.EMPTY); String driverClassName; try { driverClassName = JdbcUtils.getDriverClassName(dbUrl); } catch (SQLException e) { throw new DatabaseException(e.getMessage(), e); } final DruidPlugin druidPlugin = new DruidPlugin(dbUrl, username, password, driverClassName); // set validator setValidatorQuery(dbtype, druidPlugin); druidPlugin.addFilter(new StatFilter()); final String initialSize = dbProp.getProperty(GojaPropConst.DB_INITIAL_SIZE); if (!Strings.isNullOrEmpty(initialSize)) { druidPlugin.setInitialSize(MoreObjects.firstNonNull(Ints.tryParse(initialSize), 6)); } final String initial_minidle = dbProp.getProperty(GojaPropConst.DB_INITIAL_MINIDLE); if (!Strings.isNullOrEmpty(initial_minidle)) { druidPlugin.setMinIdle(MoreObjects.firstNonNull(Ints.tryParse(initial_minidle), 5)); } final String initial_maxwait = dbProp.getProperty(GojaPropConst.DB_INITIAL_MAXWAIT); if (!Strings.isNullOrEmpty(initial_maxwait)) { druidPlugin.setMaxWait(MoreObjects.firstNonNull(Ints.tryParse(initial_maxwait), 5)); } final String initial_active = dbProp.getProperty(GojaPropConst.DB_INITIAL_ACTIVE); if (!Strings.isNullOrEmpty(initial_active)) { druidPlugin.setMaxActive(MoreObjects.firstNonNull(Ints.tryParse(initial_active), 5)); } final String timeBetweenEvictionRunsMillis = dbProp.getProperty(GojaPropConst.DB_TIME_BETWEEN_EVICTION_RUNS_MILLIS); if (!Strings.isNullOrEmpty(timeBetweenEvictionRunsMillis)) { final Integer millis = MoreObjects.firstNonNull(Ints.tryParse(timeBetweenEvictionRunsMillis), 10000); druidPlugin.setTimeBetweenEvictionRunsMillis(millis); } final String minEvictableIdleTimeMillis = dbProp.getProperty(GojaPropConst.DB_MIN_EVICTABLE_IDLE_TIME_MILLIS); if (!Strings.isNullOrEmpty(minEvictableIdleTimeMillis)) { final Integer idleTimeMillis = MoreObjects.firstNonNull(Ints.tryParse(minEvictableIdleTimeMillis), 10000); druidPlugin.setMinEvictableIdleTimeMillis(idleTimeMillis); } final WallFilter wall = new WallFilter(); wall.setDbType(dbtype); druidPlugin.addFilter(wall); if (GojaConfig.getPropertyToBoolean(GojaPropConst.DBLOGFILE, false)) { // 增加 LogFilter 输出JDBC执行的日志 druidPlugin.addFilter(new Slf4jLogFilter()); } return druidPlugin; } return null; }
java
{ "resource": "" }
q180161
ExtensionFinder.bind
test
protected <T> void bind(Class<? extends T> impl, Class<T> extensionPoint) { ExtensionLoaderModule<T> lm = createLoaderModule(extensionPoint); lm.init(impl,extensionPoint); install(lm); }
java
{ "resource": "" }
q180162
AbstractRequest.builtin
test
protected Object builtin(Type type) { Class<?> rawType = Types.getRawType(type); if (rawType.equals(WebContext.class)) { return context; } else if (rawType.equals(HttpServletRequest.class)) { return context.request(); } else if (rawType.equals(HttpServletResponse.class)) { return context.response(); } else if (rawType.equals(HttpSession.class)) { return context.session(); } else if (rawType.equals(ServletContext.class)) { return context.application(); } else { // org.eiichiro.bootleg.Request. return this; } }
java
{ "resource": "" }
q180163
AbstractRequest.primitive
test
protected Object primitive(Type type) { Class<?> rawType = Types.getRawType(type); if (rawType.equals(Boolean.TYPE)) { return (boolean) false; } else if (rawType.equals(Character.TYPE)) { return (char) 0; } else if (rawType.equals(Byte.TYPE)) { return (byte) 0; } else if (rawType.equals(Double.TYPE)) { return (double) 0.0; } else if (rawType.equals(Float.TYPE)) { return (float) 0.0; } else if (rawType.equals(Integer.TYPE)) { return (int) 0; } else { // short. return (short) 0; } }
java
{ "resource": "" }
q180164
AbstractRequest.convert
test
protected Object convert(Object object, Class<?> type) { try { return ConvertUtils.convert(object, type); } catch (Exception e) { logger.warn("Cannot convert [" + object + "] to [" + type + "]", e); return null; } }
java
{ "resource": "" }
q180165
AbstractRequest.convertUserDefinedValueType
test
protected Object convertUserDefinedValueType(Object object, Class<?> type) { if (type.isAssignableFrom(object.getClass())) { return object; } else if (object instanceof String) { try { Constructor<?> constructor = type.getConstructor(String.class); return constructor.newInstance(object); } catch (Exception e) { logger.debug("Cannot invoke [public " + type.getName() + "(String.class)] constrcutor on [" + type + "]", e); } try { return type.getMethod("valueOf", String.class).invoke(null, object); } catch (Exception e1) { logger.debug("Cannot invoke [public static " + type.getName() + ".valueOf(String.class)]" + "method on [" + type + "]", e1); } } else { logger.warn("Parameter [" + object + "] cannot be converted to [" + type + "]"); } return null; }
java
{ "resource": "" }
q180166
AbstractRequest.query
test
protected Object query(Type type, String name) { return parameter(type, name, new Function<String, Object>() { public Object apply(String name) { return context.request().getParameter(name); } }, new Function<String, Collection<Object>>() { @SuppressWarnings("unchecked") public Collection<Object> apply(String name) { HttpServletRequest request = context.request(); Map<String, Object> map = new TreeMap<String, Object>(); for (Object object : Collections.list(request.getParameterNames())) { String key = (String) object; if (key.startsWith(name + "[")) { map.put(key, request.getParameter(key)); } } return (map.isEmpty()) ? null : map.values(); } }); }
java
{ "resource": "" }
q180167
AbstractRequest.cookie
test
protected Object cookie(Type type, String name) { return parameter(type, name, new Function<String, Object>() { public Object apply(String name) { Cookie[] cookies = context.request().getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie.getValue(); } } } return null; } }, new Function<String, Collection<Object>>() { public Collection<Object> apply(String name) { HttpServletRequest request = context.request(); Map<String, Object> map = new TreeMap<String, Object>(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String key = cookie.getName(); if (key.startsWith(name + "[")) { map.put(key, cookie.getValue()); } } } return (map.isEmpty()) ? null : map.values(); } }); }
java
{ "resource": "" }
q180168
AbstractRequest.session
test
protected Object session(Type type, String name) { return parameter(type, name, new Function<String, Object>() { public Object apply(String name) { return context.session().getAttribute(name); } }, new Function<String, Collection<Object>>() { @SuppressWarnings("unchecked") public Collection<Object> apply(String name) { HttpSession session = context.session(); Object attribute = session.getAttribute(name); if (attribute instanceof Collection<?>) { return (Collection<Object>) attribute; } Map<String, Object> map = new TreeMap<String, Object>(); for (Object object : Collections.list(session.getAttributeNames())) { String key = (String) object; if (key.startsWith(name + "[")) { map.put(key, session.getAttribute(key)); } } return (map.isEmpty()) ? null : map.values(); } }); }
java
{ "resource": "" }
q180169
Goja.initDataSource
test
private void initDataSource(final Plugins plugins) { final Map<String, Properties> dbConfig = GojaConfig.loadDBConfig(GojaConfig.getConfigProps()); for (String db_config : dbConfig.keySet()) { final Properties db_props = dbConfig.get(db_config); if (db_props != null && !db_props.isEmpty()) { DruidDbIntializer.init(db_config, plugins, db_props); } } if (GojaConfig.getPropertyToBoolean(GojaPropConst.DB_SQLINXML, true)) { plugins.add(new SqlInXmlPlugin()); } }
java
{ "resource": "" }
q180170
Goja.setFtlSharedVariable
test
private void setFtlSharedVariable() { // custmer variable final Configuration config = FreeMarkerRender.getConfiguration(); config.setSharedVariable("block", new BlockDirective()); config.setSharedVariable("extends", new ExtendsDirective()); config.setSharedVariable("override", new OverrideDirective()); config.setSharedVariable("super", new SuperDirective()); // 增加日期美化指令(类似 几分钟前) config.setSharedVariable("prettytime", new PrettyTimeDirective()); if (GojaConfig.isSecurity()) { config.setSharedVariable("shiro", new ShiroTags(config.getObjectWrapper())); } }
java
{ "resource": "" }
q180171
DTCriterias.setParam
test
public void setParam(String field, Condition condition, Object value) { this.params.add(Triple.of(field, condition, value)); }
java
{ "resource": "" }
q180172
DTCriterias.setParam
test
public void setParam(String field, Object value) { this.setParam(field, Condition.EQ, value); }
java
{ "resource": "" }
q180173
RequestPermission.showDialog
test
private void showDialog(PermBean permBean) { PermissionDialogFragment fragment = PermissionDialogFragment.getInstance(permBean, requestCode); fragment.show(mActivity.getSupportFragmentManager(), TAG); }
java
{ "resource": "" }
q180174
RequestPermission.allValuesGranted
test
private static boolean allValuesGranted(Object[] values, HashMap<Permission, Result> resultMap) { if (values instanceof Permission[]) { Set<Permission> valueSet = new HashSet<>(Arrays.asList((Permission[]) values)); if (resultMap.keySet().containsAll(valueSet)) { for (Object value : values) { if (Result.GRANTED != resultMap.get((Permission) value)) { mLog.i(TAG, "denied - " + value.toString()); return false; } } return true; } } else if (values instanceof String[]) { Set<String> valueSet = new HashSet<>(Arrays.asList((String[]) values)); Set<String> permission = new HashSet<>(); for (Permission perm : resultMap.keySet()) { permission.add(perm.toString()); } if (permission.containsAll(valueSet)) { for (Object value : values) { if (Result.GRANTED != resultMap.get(Permission.get(String.valueOf(value)))) { mLog.i(TAG, "denied - " + value); return false; } } return true; } } return false; }
java
{ "resource": "" }
q180175
RequestPermission.anyValueDenied
test
private static boolean anyValueDenied(Object[] values, HashMap<Permission, Result> resultMap) { if (values instanceof Permission[]) { Set<Permission> valueSet = new LinkedHashSet<>(Arrays.asList((Permission[]) values)); if (resultMap.keySet().containsAll(valueSet)) { for (Object value : values) { if (Result.DENIED == resultMap.get((Permission) value)) { mLog.i(TAG, "denied - " + value.toString()); return true; } } } } else if (values instanceof String[]) { Set<String> valueSet = new HashSet<>(Arrays.asList((String[]) values)); Set<String> permissionSet = new HashSet<>(); for (Permission perm : resultMap.keySet()) { permissionSet.add(perm.toString()); } if (permissionSet.containsAll(valueSet)) { for (Object value : values) { if (Result.DENIED == resultMap.get(Permission.get((String) value))) { mLog.i(TAG, "denied - " + value); return true; } } } } return false; }
java
{ "resource": "" }
q180176
Dao.findBy
test
public static List<Record> findBy(SqlSelect sqlSelect) { Preconditions.checkNotNull(sqlSelect, "The Query SqlNode is must be not null."); return Db.find(sqlSelect.toString(), sqlSelect.getParams().toArray()); }
java
{ "resource": "" }
q180177
Dao.findOne
test
public static Record findOne(SqlSelect sqlSelect) { Preconditions.checkNotNull(sqlSelect, "The Query SqlNode is must be not null."); return Db.findFirst(sqlSelect.toString(), sqlSelect.getParams().toArray()); }
java
{ "resource": "" }
q180178
Dao.isNew
test
public static <M extends Model> boolean isNew(M m, String pk_column) { final Object val = m.get(pk_column); return val == null || val instanceof Number && ((Number) val).intValue() <= 0; }
java
{ "resource": "" }
q180179
ReflectionKit.declaresException
test
public static boolean declaresException(Method method, Class<?> exceptionType) { Preconditions.checkNotNull(method, "Method must not be null"); Class<?>[] declaredExceptions = method.getExceptionTypes(); for (Class<?> declaredException : declaredExceptions) { if (declaredException.isAssignableFrom(exceptionType)) { return true; } } return false; }
java
{ "resource": "" }
q180180
ConcurrentSoftHashMap.processQueue
test
private void processQueue() { SoftValue<?, ?> sv; while ((sv = (SoftValue<?, ?>) queue.poll()) != null) { //noinspection SuspiciousMethodCalls map.remove(sv.key); // we can access private data! } }
java
{ "resource": "" }
q180181
ConcurrentSoftHashMap.put
test
@Override public V put(K key, V value) { processQueue(); // throw out garbage collected values first SoftValue<V, K> sv = new SoftValue<V, K>(value, key, queue); SoftValue<V, K> previous = map.put(key, sv); addToStrongReferences(value); return previous != null ? previous.get() : null; }
java
{ "resource": "" }
q180182
WildcharUtils.match
test
public static boolean match(String string, String pattern) { if (string.equals(pattern)) { // speed-up return true; } return match(string, pattern, 0, 0); }
java
{ "resource": "" }
q180183
ArgumentHandler.readArguments
test
public static <A> A readArguments(Class<A> interfaceClass, String[] args) { A result = null; try { final ArgumentHandler argumentHandler = new ArgumentHandler(args); result = argumentHandler.getInstance(interfaceClass); argumentHandler.processArguments(new ArgumentProcessor() { @Override public void process(List<String> remaining) throws InvalidArgumentsException { if (remaining.size() > 0) { throw new InvalidArgumentsException("The following arguments could not be understood: " + remaining); } } }); } catch (InvalidArgumentsException e) { System.out.println(e.getMessage()); showUsage(interfaceClass); result = null; } if (result instanceof ArgumentsWithHelp) { if (((ArgumentsWithHelp)result).getHelp()) { showUsage(interfaceClass); result = null; } } return result; }
java
{ "resource": "" }
q180184
ProtobufSerializerUtils.getProtobufEntity
test
public static final ProtobufEntity getProtobufEntity(Class<?> clazz) { final ProtobufEntity protoBufEntity = clazz.getAnnotation(ProtobufEntity.class); if (protoBufEntity != null) { return protoBufEntity; } return null; }
java
{ "resource": "" }
q180185
ProtobufSerializerUtils.isProtbufEntity
test
public static final boolean isProtbufEntity(Class<?> clazz) { final ProtobufEntity protoBufEntity = getProtobufEntity(clazz); if (protoBufEntity != null) { return true; } return false; }
java
{ "resource": "" }
q180186
ProtobufSerializerUtils.getAllProtbufFields
test
public static final Map<Field, ProtobufAttribute> getAllProtbufFields(Class<? extends Object> fromClazz) { Map<Field, ProtobufAttribute> protoBufFields = CLASS_TO_FIELD_MAP_CACHE.get(fromClazz.getCanonicalName()); if (protoBufFields != null) { return protoBufFields; } else { protoBufFields = new HashMap<>(); } final List<Field> fields = JReflectionUtils.getAllFields(new ArrayList<Field>(), fromClazz); for (Field field : fields) { final Annotation annotation = field.getAnnotation(ProtobufAttribute.class); if (annotation == null) { continue; } final ProtobufAttribute gpbAnnotation = (ProtobufAttribute)annotation; protoBufFields.put(field, gpbAnnotation); } // Caching to increase speed CLASS_TO_FIELD_MAP_CACHE.put(fromClazz.getCanonicalName(), protoBufFields); return protoBufFields; }
java
{ "resource": "" }
q180187
ProtobufSerializerUtils.getProtobufGetter
test
public static final String getProtobufGetter(ProtobufAttribute protobufAttribute, Field field) { final String fieldName = field.getName(); final String upperClassName = field.getDeclaringClass().getCanonicalName(); // Look at the cache first Map<String, String> map = CLASS_TO_FIELD_GETTERS_MAP_CACHE.get(upperClassName); if (map != null) { if (!map.isEmpty() && map.containsKey(fieldName)) { return map.get(fieldName); } } else { map = new ConcurrentHashMap<>(); } final String upperCaseFirstFieldName = JStringUtils.upperCaseFirst(field.getName()); String getter = "get" + upperCaseFirstFieldName; if (Collection.class.isAssignableFrom(field.getType())) { getter += "List"; } if (!protobufAttribute.protobufGetter().isEmpty()) { return protobufAttribute.protobufGetter(); } map.put(fieldName, getter); CLASS_TO_FIELD_GETTERS_MAP_CACHE.put(upperClassName, map); return getter; }
java
{ "resource": "" }
q180188
ProtobufSerializerUtils.getPojoSetter
test
public static final String getPojoSetter(ProtobufAttribute protobufAttribute, Field field) { final String fieldName = field.getName(); final String upperClassName = field.getDeclaringClass().getCanonicalName(); // Look at the cache first Map<String, String> map = CLASS_TO_FIELD_SETTERS_MAP_CACHE.get(upperClassName); if (map != null) { if (!map.isEmpty() && map.containsKey(fieldName)) { return map.get(fieldName); } } else { map = new ConcurrentHashMap<>(); } final String upperCaseFirstFieldName = JStringUtils.upperCaseFirst(field.getName()); String setter = "set" + upperCaseFirstFieldName; if (!protobufAttribute.pojoSetter().isEmpty()) { return protobufAttribute.pojoSetter(); } map.put(fieldName, setter); CLASS_TO_FIELD_SETTERS_MAP_CACHE.put(upperClassName, map); return setter; }
java
{ "resource": "" }
q180189
JsonUtil.getMapper
test
public static ObjectMapper getMapper() { ObjectMapper mapper = threadMapper.get(); if (mapper == null) { mapper = initMapper(); threadMapper.set(mapper); } return mapper; }
java
{ "resource": "" }
q180190
JsonUtil.getJsonFactory
test
public static JsonFactory getJsonFactory() { JsonFactory jsonFactory = threadJsonFactory.get(); if (jsonFactory == null) { jsonFactory = new JsonFactory(); // JsonParser.Feature for configuring parsing settings: // to allow C/C++ style comments in JSON (non-standard, disabled by // default) jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS); // to allow (non-standard) unquoted field names in JSON: jsonFactory.disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES); // to allow use of apostrophes (single quotes), non standard jsonFactory.disable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); // JsonGenerator.Feature for configuring low-level JSON generation: // no escaping of non-ASCII characters: jsonFactory.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII); threadJsonFactory.set(jsonFactory); } return jsonFactory; }
java
{ "resource": "" }
q180191
JsonUtil.toJson
test
public static <T> String toJson(T obj) { StringWriter writer = new StringWriter(); String jsonStr = ""; JsonGenerator gen = null; try { gen = getJsonFactory().createGenerator(writer); getMapper().writeValue(gen, obj); writer.flush(); jsonStr = writer.toString(); } catch (IOException e) { log.error("{}", e.getMessage(), e); } finally { if (gen != null) { try { gen.close(); } catch (IOException e) { } } } return jsonStr; }
java
{ "resource": "" }
q180192
DefaultContentRect.setBorders
test
public void setBorders(int top, int right, int bottom, int left) { setTopBorder(top); setRightBorder(right); setBottomBorder(bottom); setLeftBorder(left); }
java
{ "resource": "" }
q180193
JdbcPasswordAuthenticator.getUserRecord
test
@edu.umd.cs.findbugs.annotations.SuppressWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING") private UserRecord getUserRecord(final String domain, final String userName) throws LoginException { String userId; String credential; Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = getDatabaseConnection(); statement = connection.prepareStatement(dbProps.get().getSqlUserQuery()); statement.setString(1, domain); statement.setString(2, userName); resultSet = statement.executeQuery(); if (resultSet.next()) { userId = resultSet.getString(1); credential = resultSet.getString(2); } else { final String error = "Username '" + userName + "' does not exist (query returned zero results)"; LOG.warn(error); throw new LoginException(error); } resultSet.close(); statement.close(); } catch (SQLException e) { final String error = "Error executing SQL query"; LOG.warn(error, e); throw Util.newLoginException(error, e); } finally { DbUtil.close(resultSet); DbUtil.close(statement); DbUtil.close(connection); } return new UserRecord(domain, userName, userId, credential); }
java
{ "resource": "" }
q180194
AttributeInjector.copyOutAttributes
test
public void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues, Map<String, Method> attributeSetters, ObjectName objectName) { this.copyOutAttributes(target, jmxAttributeValues, attributeSetters, "oname", objectName); }
java
{ "resource": "" }
q180195
AttributeInjector.copyOutAttributes
test
protected void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues, Map<String, Method> attributeSetters, String identifierKey, Object identifier) { for (Attribute oneAttribute : jmxAttributeValues) { String attributeName = oneAttribute.getName(); Method setter = attributeSetters.get(attributeName); Object value = oneAttribute.getValue(); try { // // Automatically down-convert longs to integers as-needed. // if ((setter.getParameterTypes()[0].isAssignableFrom(Integer.class)) || (setter.getParameterTypes()[0].isAssignableFrom(int.class))) { if (value instanceof Long) { value = ((Long) value).intValue(); } } setter.invoke(target, value); } catch (InvocationTargetException invocationExc) { this.log.info("invocation exception storing mbean results: {}={}; attributeName={}", identifierKey, identifier, attributeName, invocationExc); } catch (IllegalAccessException illegalAccessExc) { this.log.info("illegal access exception storing mbean results: {}={}; attributeName={}", identifierKey, identifier, attributeName, illegalAccessExc); } catch (IllegalArgumentException illegalArgumentExc) { this.log.info("illegal argument exception storing mbean results: {}={}; attributeName={}", identifierKey, identifier, attributeName, illegalArgumentExc); } } }
java
{ "resource": "" }
q180196
AppRunner.getProperty
test
public String getProperty(String key) { if (m_properties == null) return null; return m_properties.getProperty(key); }
java
{ "resource": "" }
q180197
AppRunner.setProperty
test
public void setProperty(String key, String value) { if (m_properties == null) m_properties = new Properties(); m_properties.setProperty(key, value); }
java
{ "resource": "" }
q180198
AppRunner.addAppToFrame
test
public JFrame addAppToFrame() { JFrame frame = new JFrame(); frame.setTitle(this.getTitle()); frame.setBackground(Color.lightGray); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(this, BorderLayout.CENTER); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setSize(frame.getPreferredSize().width, frame.getPreferredSize().height); return frame; }
java
{ "resource": "" }
q180199
PrefAuthPersistence.saveToken
test
@Override public void saveToken(Token token) { set(ACCESS_TOKEN_TOKEN_PREF, token.getToken()); set(ACCESS_TOKEN_SECRET_PREF, token.getSecret()); }
java
{ "resource": "" }