_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q180200
|
PrefAuthPersistence.getToken
|
test
|
@Override
public Token getToken() {
String token = get(ACCESS_TOKEN_TOKEN_PREF);
String secret = get(ACCESS_TOKEN_SECRET_PREF);
return token != null ? new Token(token, secret) : null;
}
|
java
|
{
"resource": ""
}
|
q180201
|
ClassLoaderUtils.getDefault
|
test
|
public static ClassLoader getDefault() {
ClassLoader loader = null;
try {
loader = Thread.currentThread().getContextClassLoader();
} catch (Exception e) {
}
if (loader == null) {
loader = ClassLoaderUtils.class.getClassLoader();
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
}
return loader;
}
|
java
|
{
"resource": ""
}
|
q180202
|
ClassLoaderUtils.getResource
|
test
|
public static URL getResource(String name, ClassLoader classLoader) {
Validate.notNull(name, "resourceName must be not null");
if (name.startsWith("/")) {
name = name.substring(1);
}
if (classLoader != null) {
URL url = classLoader.getResource(name);
if (url != null) {
return url;
}
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader != null && loader != classLoader) {
URL url = loader.getResource(name);
if (url != null) {
return url;
}
}
return ClassLoader.getSystemResource(name);
}
|
java
|
{
"resource": ""
}
|
q180203
|
ClassLoaderUtils.getResourceAsStream
|
test
|
public static InputStream getResourceAsStream(String name, ClassLoader classLoader) throws IOException {
URL url = getResource(name, classLoader);
if (url != null) {
return url.openStream();
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180204
|
ClassLoaderUtils.getClassAsStream
|
test
|
public static InputStream getClassAsStream(Class<?> clazz) throws IOException {
return getResourceAsStream(getClassFileName(clazz), clazz.getClassLoader());
}
|
java
|
{
"resource": ""
}
|
q180205
|
URI.initialize
|
test
|
private void initialize(URI p_other) {
m_scheme = p_other.getScheme();
m_userinfo = p_other.getUserinfo();
m_host = p_other.getHost();
m_port = p_other.m_port;
n_port = p_other.n_port;
m_path = p_other.getPath();
m_queryString = p_other.getQueryString();
m_fragment = p_other.getFragment();
}
|
java
|
{
"resource": ""
}
|
q180206
|
URI.initializeScheme
|
test
|
private void initializeScheme(String p_uriSpec)
throws MalformedURIException {
int uriSpecLen = p_uriSpec.length();
int index = p_uriSpec.indexOf(':');
if (index < 1)
throw new MalformedURIException("No scheme found in URI.");
if (index == uriSpecLen - 1)
throw new MalformedURIException("A bare scheme name is not a URI.");
setScheme(p_uriSpec.substring(0, index));
}
|
java
|
{
"resource": ""
}
|
q180207
|
URI.initializePath
|
test
|
private void initializePath(String p_uriSpec)
throws MalformedURIException {
if (p_uriSpec == null) {
throw new MalformedURIException("Cannot initialize path from null string!");
}
int index = 0;
int start = 0;
int end = p_uriSpec.length();
char testChar = '\0';
// path - everything up to query string or fragment
while (index < end) {
testChar = p_uriSpec.charAt(index);
if (testChar == '?' || testChar == '#') {
break;
}
// check for valid escape sequence
if (testChar == '%') {
if (index + 2 >= end
|| !isHex(p_uriSpec.charAt(index + 1))
|| !isHex(p_uriSpec.charAt(index + 2))) {
throw new MalformedURIException("Path contains invalid escape sequence!");
}
} else if (
!isReservedCharacter(testChar)
&& !isUnreservedCharacter(testChar)) {
throw new MalformedURIException(
"Path contains invalid character: " + testChar);
}
index++;
}
m_path = p_uriSpec.substring(start, index);
// query - starts with ? and up to fragment or end
if (testChar == '?') {
index++;
start = index;
while (index < end) {
testChar = p_uriSpec.charAt(index);
if (testChar == '#') {
break;
}
if (testChar == '%') {
if (index + 2 >= end
|| !isHex(p_uriSpec.charAt(index + 1))
|| !isHex(p_uriSpec.charAt(index + 2))) {
throw new MalformedURIException("Query string contains invalid escape sequence!");
}
} else if (
!isReservedCharacter(testChar)
&& !isUnreservedCharacter(testChar)) {
throw new MalformedURIException(
"Query string contains invalid character:" + testChar);
}
index++;
}
m_queryString = p_uriSpec.substring(start, index);
}
// fragment - starts with #
if (testChar == '#') {
index++;
start = index;
while (index < end) {
testChar = p_uriSpec.charAt(index);
if (testChar == '%') {
if (index + 2 >= end
|| !isHex(p_uriSpec.charAt(index + 1))
|| !isHex(p_uriSpec.charAt(index + 2))) {
throw new MalformedURIException("Fragment contains invalid escape sequence!");
}
} else if (
!isReservedCharacter(testChar)
&& !isUnreservedCharacter(testChar)) {
throw new MalformedURIException(
"Fragment contains invalid character:" + testChar);
}
index++;
}
m_fragment = p_uriSpec.substring(start, index);
}
}
|
java
|
{
"resource": ""
}
|
q180208
|
URI.setScheme
|
test
|
private void setScheme(String p_scheme) throws MalformedURIException {
if (p_scheme == null) {
throw new MalformedURIException("Cannot set scheme from null string!");
}
if (!isConformantSchemeName(p_scheme)) {
throw new MalformedURIException("The scheme is not conformant.");
}
m_scheme = p_scheme; //.toLowerCase();
}
|
java
|
{
"resource": ""
}
|
q180209
|
URI.setUserinfo
|
test
|
private void setUserinfo(String p_userinfo) throws MalformedURIException {
if (p_userinfo == null) {
m_userinfo = null;
} else {
if (m_host == null) {
throw new MalformedURIException("Userinfo cannot be set when host is null!");
}
// userinfo can contain alphanumerics, mark characters, escaped
// and ';',':','&','=','+','$',','
int index = 0;
int end = p_userinfo.length();
char testChar = '\0';
while (index < end) {
testChar = p_userinfo.charAt(index);
if (testChar == '%') {
if (index + 2 >= end
|| !isHex(p_userinfo.charAt(index + 1))
|| !isHex(p_userinfo.charAt(index + 2))) {
throw new MalformedURIException("Userinfo contains invalid escape sequence!");
}
} else if (
!isUnreservedCharacter(testChar)
&& USERINFO_CHARACTERS.indexOf(testChar) == -1) {
throw new MalformedURIException(
"Userinfo contains invalid character:" + testChar);
}
index++;
}
}
m_userinfo = p_userinfo;
}
|
java
|
{
"resource": ""
}
|
q180210
|
URI.setHost
|
test
|
private void setHost(String p_host) throws MalformedURIException {
if (p_host == null || p_host.length() == 0) {
m_host = p_host;
m_userinfo = null;
m_port = null;
n_port = -1;
} else if (!isWellFormedAddress(p_host)) {
throw new MalformedURIException("Host is not a well formed address!");
}
m_host = p_host;
}
|
java
|
{
"resource": ""
}
|
q180211
|
URI.setPort
|
test
|
private void setPort(int p_port) throws MalformedURIException {
if (p_port >= 0 && p_port <= 65535) {
if (m_host == null) {
throw new MalformedURIException("Port cannot be set when host is null!");
}
} else if (p_port != -1) {
throw new MalformedURIException("Invalid port number!");
}
n_port = p_port;
}
|
java
|
{
"resource": ""
}
|
q180212
|
URI.appendPath
|
test
|
private void appendPath(String p_addToPath) throws MalformedURIException {
if (p_addToPath == null || p_addToPath.length() == 0) {
return;
}
if (!isURIString(p_addToPath)) {
throw new MalformedURIException("Path contains invalid character!");
}
if (m_path == null || m_path.length() == 0) {
if (p_addToPath.startsWith("/")) {
m_path = p_addToPath;
} else {
m_path = "/" + p_addToPath;
}
} else if (m_path.endsWith("/")) {
if (p_addToPath.startsWith("/")) {
m_path = m_path.concat(p_addToPath.substring(1));
} else {
m_path = m_path.concat(p_addToPath);
}
} else {
if (p_addToPath.startsWith("/")) {
m_path = m_path.concat(p_addToPath);
} else {
m_path = m_path.concat("/" + p_addToPath);
}
}
}
|
java
|
{
"resource": ""
}
|
q180213
|
URI.setQueryString
|
test
|
private void setQueryString(String p_queryString)
throws MalformedURIException {
if (p_queryString == null) {
m_queryString = null;
} else if (!isGenericURI()) {
throw new MalformedURIException("Query string can only be set for a generic URI!");
} else if (getPath() == null) {
throw new MalformedURIException("Query string cannot be set when path is null!");
} else if (!isURIString(p_queryString)) {
throw new MalformedURIException("Query string contains invalid character!");
} else {
m_queryString = p_queryString;
}
}
|
java
|
{
"resource": ""
}
|
q180214
|
URI.setFragment
|
test
|
public void setFragment(String p_fragment) throws MalformedURIException {
if (p_fragment == null) {
m_fragment = null;
} else if (!isGenericURI()) {
throw new MalformedURIException("Fragment can only be set for a generic URI!");
} else if (getPath() == null) {
throw new MalformedURIException("Fragment cannot be set when path is null!");
} else if (!isURIString(p_fragment)) {
throw new MalformedURIException("Fragment contains invalid character!");
} else {
m_fragment = p_fragment;
}
}
|
java
|
{
"resource": ""
}
|
q180215
|
URI.getURIString
|
test
|
public String getURIString() {
StringBuffer uriSpecString = new StringBuffer();
if (m_scheme != null) {
uriSpecString.append(m_scheme);
uriSpecString.append(':');
}
uriSpecString.append(getSchemeSpecificPart());
return uriSpecString.toString();
}
|
java
|
{
"resource": ""
}
|
q180216
|
PreparedStatementCreator.createByIterator
|
test
|
protected static PreparedStatement createByIterator(Connection conn, String sql, Iterator<?> parameters) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql);
if (parameters != null) {
int index = 1;
while (parameters.hasNext()) {
Object parameter = parameters.next();
if (parameter == null) {
ps.setObject(index, null);
} else {
ps.setObject(index, parameter);
}
index++;
}
}
return ps;
}
|
java
|
{
"resource": ""
}
|
q180217
|
MuffinManager.init
|
test
|
public void init(Object applet)
{
try {
m_ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService");
m_bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
m_strCodeBase = m_bs.getCodeBase().toString();
} catch (UnavailableServiceException e) {
m_ps = null;
m_bs = null;
}
}
|
java
|
{
"resource": ""
}
|
q180218
|
MuffinManager.getMuffin
|
test
|
public String getMuffin(String strParam)
{
try {
URL url = new URL(m_strCodeBase + strParam);
FileContents fc = m_ps.get(url);
if (fc == null)
return null;
// read in the contents of a muffin
byte[] buf = new byte[(int)fc.getLength()];
InputStream is = fc.getInputStream();
int pos = 0;
while((pos = is.read(buf, pos, buf.length - pos)) > 0) {
// just loop
}
is.close();
String strValue = new String(buf, ENCODING);
return strValue;
} catch (Exception ex) {
// Return null for any exception
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180219
|
MuffinManager.setMuffin
|
test
|
public void setMuffin(String strParam, String strValue)
{
FileContents fc = null;
URL url = null;
try {
url = new URL(m_strCodeBase + strParam);
} catch (Exception ex) {
return;
}
try {
fc = m_ps.get(url);
fc.getMaxLength(); // This will throw an exception if there is no muffin yet.
} catch (Exception ex) {
fc = null;
}
try {
if (fc == null)
{
m_ps.create(url, 100);
fc = m_ps.get(url);
} // don't append
if (strValue != null)
{
OutputStream os = fc.getOutputStream(false);
byte[] buf = strValue.getBytes(ENCODING);
os.write(buf);
os.close();
m_ps.setTag(url, PersistenceService.DIRTY);
}
else
m_ps.delete(url);
} catch (Exception ex) {
ex.printStackTrace(); // Return null for any exception
}
}
|
java
|
{
"resource": ""
}
|
q180220
|
MuffinManager.getClipboardContents
|
test
|
public Transferable getClipboardContents()
{
if ((clipboardReadStatus & CLIPBOARD_DISABLED) == CLIPBOARD_DISABLED)
return null; // Rejected it last time, don't ask again
clipboardReadStatus = CLIPBOARD_DISABLED;
if (cs == null)
{
try {
cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
} catch (UnavailableServiceException e) {
cs = null;
}
}
if (cs != null) {
// get the contents of the system clipboard and print them
Transferable tr = cs.getContents();
if (tr != null)
clipboardReadStatus = CLIPBOARD_ENABLED;
return tr;
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180221
|
MuffinManager.setClipboardContents
|
test
|
public boolean setClipboardContents(Transferable data)
{
if (data == null)
return false;
if ((clipboardWriteStatus & CLIPBOARD_DISABLED) == CLIPBOARD_DISABLED)
return false; // Rejected it last time, don't ask again
clipboardWriteStatus = CLIPBOARD_ENABLED;
if (cs == null)
{
try {
cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
} catch (UnavailableServiceException e) {
cs = null;
}
}
if (cs != null)
{ // set the system clipboard contents to a string selection
try {
cs.setContents(data);
clipboardWriteStatus = CLIPBOARD_ENABLED;
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q180222
|
MuffinManager.openFileStream
|
test
|
public InputStream openFileStream(String pathHint, String[] extensions)
{
if (fos == null)
{
try {
fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
} catch (UnavailableServiceException e) {
fos = null;
}
}
if (fos != null) {
try {
// ask user to select a file through this service
FileContents fc = fos.openFileDialog(pathHint, extensions);
return fc.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180223
|
ServiceManager.loadServicesByType
|
test
|
public static <T extends Service> Map<String, T> loadServicesByType(Class<T> clazz)
{
ServiceLoader<T> loader = ServiceLoader.load(clazz);
Iterator<T> it = loader.iterator();
Map<String, T> ret = new HashMap<String, T>();
while (it.hasNext())
{
T op = it.next();
ret.put(op.getId(), op);
if (op instanceof ParametrizedOperation)
addParametrizedService(op.getId(), (ParametrizedOperation) op);
if (op instanceof ScriptObject)
addScriptObject(((ScriptObject) op).getVarName(), (ScriptObject) op);
}
return ret;
}
|
java
|
{
"resource": ""
}
|
q180224
|
ServiceManager.setServiceParams
|
test
|
public static void setServiceParams(ParametrizedOperation op, Map<String, Object> params)
{
if (params != null)
{
for (Map.Entry<String, Object> entry : params.entrySet())
{
op.setParam(entry.getKey(), entry.getValue());
}
}
}
|
java
|
{
"resource": ""
}
|
q180225
|
ServiceManager.getServiceParams
|
test
|
public static Map<String, Object> getServiceParams(ParametrizedOperation op)
{
Map<String, Object> ret = new HashMap<String, Object>();
for (Parameter param : op.getParams())
{
ret.put(param.getName(), op.getParam(param.getName()));
}
return ret;
}
|
java
|
{
"resource": ""
}
|
q180226
|
ServiceManager.findParmetrizedService
|
test
|
public static ParametrizedOperation findParmetrizedService(String id)
{
if (parametrizedServices == null)
return null;
else
return parametrizedServices.get(id);
}
|
java
|
{
"resource": ""
}
|
q180227
|
ServiceManager.findByClass
|
test
|
public static <T> T findByClass(Collection<?> services, Class<T> clazz)
{
for (Object serv : services)
{
if (clazz.isInstance(serv))
return clazz.cast(serv);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180228
|
CubeSensorsApiV1.parseQuery
|
test
|
private <T> T parseQuery(final String response, final Class<T> responseClass) {
T queryResponse;
try {
/*
* Possible exceptions:
*
* IOException - if the underlying input source has problems during parsing
*
* JsonParseException - if parser has problems parsing content
*
* JsonMappingException - if the parser does not have any more content to map (note: Json "null" value is considered content; enf-of-stream not)
*/
queryResponse = MAPPER.readValue(response, responseClass);
} catch (JsonParseException | JsonMappingException e) {
try {
final ErrorResponse error = MAPPER.readValue(response, ErrorResponse.class);
LOGGER.error("Query returned an error: {}", error);
return null;
} catch (final IOException e1) {
LOGGER.error("Failed to read error response.", e1);
}
LOGGER.error("Error reading response.", e);
return null;
} catch (final IOException e) {
LOGGER.error("Error reading response.", e);
return null;
}
return queryResponse;
}
|
java
|
{
"resource": ""
}
|
q180229
|
FastBuffer.iterator
|
test
|
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int iteratorIndex;
int iteratorBufferIndex;
int iteratorOffset;
@Override
public boolean hasNext() {
return iteratorIndex < size;
}
@Override
public E next() {
if (iteratorIndex >= size) {
throw new NoSuchElementException();
}
E[] buf = buffers[iteratorBufferIndex];
E result = buf[iteratorOffset];
// increment
iteratorIndex++;
iteratorOffset++;
if (iteratorOffset >= buf.length) {
iteratorOffset = 0;
iteratorBufferIndex++;
}
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
|
java
|
{
"resource": ""
}
|
q180230
|
XmlUtil.getEncoding
|
test
|
public static String getEncoding(String xmlStr) {
String result;
String xml = xmlStr.trim();
if (xml.startsWith("<?xml")) {
int end = xml.indexOf("?>");
int encIndex = xml.indexOf("encoding=");
if (encIndex != -1) {
String sub = xml.substring(encIndex + 9, end);
result = CommUtil.substringBetween(sub, "\"", "\"");
return result;
}
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180231
|
JdbcLogDriver.getParentLogger
|
test
|
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
if (drivers.size() == 1) {
return getFirstDriver().getParentLogger();
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180232
|
JdbcLogConnection.getInstance
|
test
|
public static Connection getInstance(Connection conn) {
InvocationHandler handler = new JdbcLogConnection(conn);
ClassLoader cl = Connection.class.getClassLoader();
return (Connection) Proxy.newProxyInstance(cl, new Class[] { Connection.class }, handler);
}
|
java
|
{
"resource": ""
}
|
q180233
|
ConsoleAuthProvider.getAuthorization
|
test
|
@Override
public String getAuthorization(String authorizationUrl)
throws CubeSensorsException {
System.out.println("authorizationUrl:" + authorizationUrl);
System.out.print("provide authorization code:");
try (Scanner in = new Scanner(System.in)) {
String authorization = in.nextLine();
return authorization;
}
}
|
java
|
{
"resource": ""
}
|
q180234
|
DeclarationScanner.visitPackageDeclaration
|
test
|
public void visitPackageDeclaration(PackageDeclaration d) {
d.accept(pre);
for (ClassDeclaration classDecl : d.getClasses()) {
classDecl.accept(this);
}
for (InterfaceDeclaration interfaceDecl : d.getInterfaces()) {
interfaceDecl.accept(this);
}
d.accept(post);
}
|
java
|
{
"resource": ""
}
|
q180235
|
DeclarationScanner.visitClassDeclaration
|
test
|
public void visitClassDeclaration(ClassDeclaration d) {
d.accept(pre);
for (TypeParameterDeclaration tpDecl : d.getFormalTypeParameters()) {
tpDecl.accept(this);
}
for (FieldDeclaration fieldDecl : d.getFields()) {
fieldDecl.accept(this);
}
for (MethodDeclaration methodDecl : d.getMethods()) {
methodDecl.accept(this);
}
for (TypeDeclaration typeDecl : d.getNestedTypes()) {
typeDecl.accept(this);
}
for (ConstructorDeclaration ctorDecl : d.getConstructors()) {
ctorDecl.accept(this);
}
d.accept(post);
}
|
java
|
{
"resource": ""
}
|
q180236
|
DeclarationScanner.visitExecutableDeclaration
|
test
|
public void visitExecutableDeclaration(ExecutableDeclaration d) {
d.accept(pre);
for (TypeParameterDeclaration tpDecl : d.getFormalTypeParameters()) {
tpDecl.accept(this);
}
for (ParameterDeclaration pDecl : d.getParameters()) {
pDecl.accept(this);
}
d.accept(post);
}
|
java
|
{
"resource": ""
}
|
q180237
|
JaasBasedCommonPropsBuilder.getOption
|
test
|
@SuppressWarnings("unchecked")
private static <T> T getOption(final String key, final Map<String, ?> properties) {
// private method asserts
assert key != null : "The key cannot be null";
return (T) properties.get(key);
}
|
java
|
{
"resource": ""
}
|
q180238
|
DeclarationFilter.getFilter
|
test
|
public static DeclarationFilter getFilter(
final Collection<Modifier> mods) {
return new DeclarationFilter() {
public boolean matches(Declaration d) {
return d.getModifiers().containsAll(mods);
}
};
}
|
java
|
{
"resource": ""
}
|
q180239
|
DeclarationFilter.getFilter
|
test
|
public static DeclarationFilter getFilter(
final Class<? extends Declaration> kind) {
return new DeclarationFilter() {
public boolean matches(Declaration d) {
return kind.isInstance(d);
}
};
}
|
java
|
{
"resource": ""
}
|
q180240
|
DeclarationFilter.and
|
test
|
public DeclarationFilter and(DeclarationFilter f) {
final DeclarationFilter f1 = this;
final DeclarationFilter f2 = f;
return new DeclarationFilter() {
public boolean matches(Declaration d) {
return f1.matches(d) && f2.matches(d);
}
};
}
|
java
|
{
"resource": ""
}
|
q180241
|
DeclarationFilter.or
|
test
|
public DeclarationFilter or(DeclarationFilter f) {
final DeclarationFilter f1 = this;
final DeclarationFilter f2 = f;
return new DeclarationFilter() {
public boolean matches(Declaration d) {
return f1.matches(d) || f2.matches(d);
}
};
}
|
java
|
{
"resource": ""
}
|
q180242
|
StringEnumeratedMap.getAsMap
|
test
|
protected Map<String, V> getAsMap() {
Map<String, V> result = map;
if (result == null) {
synchronized (this) {
result = map;
if (result == null) {
map = (result = initialize());
}
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180243
|
ReflexUtil.makeAccessible
|
test
|
public static <T> void makeAccessible(final Constructor<T> constructor) {
if (!Modifier.isPublic(constructor.getModifiers())
|| !Modifier.isPublic(constructor.getDeclaringClass()
.getModifiers())) {
constructor.setAccessible(true);
}
}
|
java
|
{
"resource": ""
}
|
q180244
|
ObjectQueryPreparer.prepareObjectQuery
|
test
|
public ObjectQueryInfo prepareObjectQuery(Object obj) throws MalformedObjectNameException {
ObjectQueryInfo result;
//
// Extract the mbean info from the object (TBD: cache this information ahead of time)
//
String onamePattern = MBeanAnnotationUtil.getLocationONamePattern(obj);
if (onamePattern != null) {
//
// Locate the setters and continue only if at least one was found.
//
Map<String, Method> attributeSetters = MBeanAnnotationUtil.getAttributes(obj);
if (attributeSetters.size() > 0) {
String onameString;
if (obj instanceof MBeanLocationParameterSource) {
onameString = this.parameterReplacer
.replaceObjectNameParameters(onamePattern, (MBeanLocationParameterSource) obj);
} else {
onameString = onamePattern;
}
ObjectName oname = new ObjectName(onameString);
result = new ObjectQueryInfo(obj, oname, attributeSetters);
} else {
this.logNoAttributeThrottle.warn(log,
"ignoring attempt to prepare to poll an MBean object with no attributes: onamePattern={}",
onamePattern);
result = null;
}
} else {
log.warn("ignoring attempt to prepare to poll object that has no MBeanLocation");
result = null;
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180245
|
Util.replaceSlashWithHyphen
|
test
|
public static String replaceSlashWithHyphen(String origin) {
char[] resulltChars = origin.toCharArray();
for (int i = 0; i < resulltChars.length - 1; i++) {
if (resulltChars[i] == '/') {
resulltChars[i] = '-';
}
}
return new String(resulltChars, 0, resulltChars.length - 1);
}
|
java
|
{
"resource": ""
}
|
q180246
|
Util.bytes2HexString
|
test
|
public static String bytes2HexString(byte[] bytes) {
StringBuffer resultBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
resultBuffer.append(byte2Hex(bytes[i]));
}
return resultBuffer.toString();
}
|
java
|
{
"resource": ""
}
|
q180247
|
NamedParameterStatement.getIndexes
|
test
|
private List<Integer> getIndexes(String name) {
List<Integer> indexes = nameIndexMap.get(name);
if (indexes == null) {
throw new IllegalArgumentException("Parameter not found: " + name);
}
return indexes;
}
|
java
|
{
"resource": ""
}
|
q180248
|
NamedParameterStatement.parseNamedSql
|
test
|
private static String parseNamedSql(String sql, Map<String, List<Integer>> nameIndexMap) {
// I was originally using regular expressions, but they didn't work well for ignoring
// parameter-like strings inside quotes.
int length = sql.length();
StringBuffer parsedSql = new StringBuffer(length);
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
int index = 1;
for (int i = 0; i < length; i++) {
char c = sql.charAt(i);
if (inSingleQuote) {
if (c == '\'') {
inSingleQuote = false;
}
} else if (inDoubleQuote) {
if (c == '"') {
inDoubleQuote = false;
}
} else {
if (c == '\'') {
inSingleQuote = true;
} else if (c == '"') {
inDoubleQuote = true;
} else if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(sql.charAt(i + 1))) {
int j = i + 2;
while (j < length && Character.isJavaIdentifierPart(sql.charAt(j))) {
j++;
}
String name = sql.substring(i + 1, j);
c = '?'; // replace the parameter with a question mark
i += name.length(); // skip past the end if the parameter
List<Integer> indexList = nameIndexMap.get(name);
if (indexList == null) {
indexList = new LinkedList<Integer>();
nameIndexMap.put(name, indexList);
}
indexList.add(index);
index++;
}
}
parsedSql.append(c);
}
return parsedSql.toString();
}
|
java
|
{
"resource": ""
}
|
q180249
|
ProtobufSerializer.convertCollectionToProtobufs
|
test
|
private static final Object convertCollectionToProtobufs(Collection<Object> collectionOfNonProtobufs) throws JException
{
if (collectionOfNonProtobufs.isEmpty())
{
return collectionOfNonProtobufs;
}
final Object first = collectionOfNonProtobufs.toArray()[0];
if (!ProtobufSerializerUtils.isProtbufEntity(first))
{
return collectionOfNonProtobufs;
}
final Collection<Object> newCollectionValues;
/**
* Maintain the Collection type of value at this stage (if it is a Set), and if conversion is required to a
* different Collection type, that will be handled by a converter later on
*/
if (collectionOfNonProtobufs instanceof Set)
{
newCollectionValues = new HashSet<>();
}
else
{
newCollectionValues = new ArrayList<>();
}
for (Object iProtobufGenObj : collectionOfNonProtobufs)
{
newCollectionValues.add(serializeToProtobufEntity(iProtobufGenObj));
}
return newCollectionValues;
}
|
java
|
{
"resource": ""
}
|
q180250
|
ProtobufSerializer.setProtobufFieldValue
|
test
|
private static final void setProtobufFieldValue(ProtobufAttribute protobufAttribute, Builder protoObjBuilder, String setter,
Object fieldValue) throws NoSuchMethodException, SecurityException, ProtobufAnnotationException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class<? extends Object> fieldValueClass = fieldValue.getClass();
Class<? extends Object> gpbClass = fieldValueClass;
final Class<? extends IProtobufConverter> converterClazz = protobufAttribute.converter();
if (converterClazz != NullConverter.class)
{
final IProtobufConverter protoBufConverter = (IProtobufConverter)converterClazz.newInstance();
fieldValue = protoBufConverter.convertToProtobuf(fieldValue);
gpbClass = fieldValue.getClass();
fieldValueClass = gpbClass;
}
// Need to convert the argument class from non-primitives to primitives, as Protobuf uses these.
gpbClass = ProtobufSerializerUtils.getProtobufClass(fieldValue, gpbClass);
final Method gpbMethod = protoObjBuilder.getClass().getDeclaredMethod(setter, gpbClass);
gpbMethod.invoke(protoObjBuilder, fieldValue);
}
|
java
|
{
"resource": ""
}
|
q180251
|
ProtobufSerializer.setPojoFieldValue
|
test
|
private static final void setPojoFieldValue(Object pojo, String setter, Object protobufValue, ProtobufAttribute protobufAttribute)
throws InstantiationException, IllegalAccessException, JException
{
/**
* convertCollectionFromProtoBufs() above returns an ArrayList, and we may have a converter to convert to a Set,
* so we are performing the conversion there
*/
final Class<? extends IProtobufConverter> fromProtoBufConverter = protobufAttribute.converter();
if (fromProtoBufConverter != NullConverter.class)
{
final IProtobufConverter converter = fromProtoBufConverter.newInstance();
protobufValue = converter.convertFromProtobuf(protobufValue);
}
Class<? extends Object> argClazz = protobufValue.getClass();
JReflectionUtils.runSetter(pojo, setter, protobufValue, argClazz);
}
|
java
|
{
"resource": ""
}
|
q180252
|
FileExtensionFilter.accept
|
test
|
public boolean accept(File pathname)
{
String name = pathname.getName();
int iLastDot = name.lastIndexOf('.');
String strExtension = "";
if ((iLastDot != -1)
&& (iLastDot != name.length() -1 ))
strExtension = name.substring(iLastDot + 1);
if (m_rgstrIncludeExtensions != null)
{
for (int i = 0; i < m_rgstrIncludeExtensions.length; i++)
{
if (m_rgstrIncludeExtensions[i].equalsIgnoreCase(strExtension))
return true; // Accept
}
return false; // Not in included - return
}
if (m_rgstrExcludeExtensions != null)
{
for (int i = 0; i < m_rgstrExcludeExtensions.length; i++)
{
if (m_rgstrExcludeExtensions[i].equalsIgnoreCase(strExtension))
return false; // Don't accept
}
}
return true; // Accept this file
}
|
java
|
{
"resource": ""
}
|
q180253
|
JdbcLogResultSet.getInstance
|
test
|
public static ResultSet getInstance(ResultSet rs) {
InvocationHandler handler = new JdbcLogResultSet(rs);
ClassLoader cl = ResultSet.class.getClassLoader();
return (ResultSet) Proxy.newProxyInstance(cl, new Class[] { ResultSet.class }, handler);
}
|
java
|
{
"resource": ""
}
|
q180254
|
StateParser.mapLabels
|
test
|
private static Map<ExpectedLabels, Integer> mapLabels(final List<String> labels) {
final Map<ExpectedLabels, Integer> map = new EnumMap<>(ExpectedLabels.class);
final List<ExpectedLabels> unusedLabels = new ArrayList<>(Arrays.asList(ExpectedLabels.values()));
for (int index = 0; index < labels.size(); index++) {
final String next = labels.get(index);
ExpectedLabels labelValue;
try {
labelValue = ExpectedLabels.valueOf(next);
unusedLabels.remove(labelValue);
if (map.containsKey(labelValue)) {
LOGGER.warn("Duplicate state label: {} ({})", next, labels);
}
map.put(labelValue, index);
} catch (final IllegalArgumentException e) {
LOGGER.warn("Unexpected state label: {}", next);
}
}
for (final ExpectedLabels label : unusedLabels) {
LOGGER.warn("Unused label: {}", label);
}
return map;
}
|
java
|
{
"resource": ""
}
|
q180255
|
StateParser.extractValues
|
test
|
private static State extractValues(final List<Object> values, final Map<ExpectedLabels, Integer> map) {
final ZonedDateTime time = ZonedDateTime.parse((String) values.get(map.get(ExpectedLabels.time)));
final int temp = safeInt((Integer) values.get(map.get(ExpectedLabels.temp)));
final int pressure = safeInt((Integer) values.get(map.get(ExpectedLabels.pressure)));
final int humidity = safeInt((Integer) values.get(map.get(ExpectedLabels.humidity)));
final int voc = safeInt((Integer) values.get(map.get(ExpectedLabels.voc)));
final int light = safeInt((Integer) values.get(map.get(ExpectedLabels.light)));
final int noise = safeInt((Integer) values.get(map.get(ExpectedLabels.noise)));
final int noisedba = safeInt((Integer) values.get(map.get(ExpectedLabels.noisedba)));
final int battery = safeInt((Integer) values.get(map.get(ExpectedLabels.battery)));
final boolean shake = safeBoolean((Boolean) values.get(map.get(ExpectedLabels.shake)));
final boolean cable = safeBoolean((Boolean) values.get(map.get(ExpectedLabels.cable)));
final int vocResistance = safeInt((Integer) values.get(map.get(ExpectedLabels.voc_resistance)));
final int rssi = safeInt((Integer) values.get(map.get(ExpectedLabels.rssi)));
return new State(time, temp, pressure, humidity, voc, light, noise, noisedba, battery, shake, cable, vocResistance, rssi);
}
|
java
|
{
"resource": ""
}
|
q180256
|
TypeResolverUtils.getGenericSupertype
|
test
|
public static Class<?> getGenericSupertype(Class<?> type, int index) {
return getComponentType(type.getGenericSuperclass(), null, index);
}
|
java
|
{
"resource": ""
}
|
q180257
|
JmxAttributePoller.poll
|
test
|
public void poll() throws IOException {
synchronized (this) {
// Make sure not to check and create a connection if shutting down.
if (shutdownInd) {
return;
}
// Atomically indicate polling is active now so a caller can determine with certainty whether polling is
// completely shutdown.
pollActiveInd = true;
}
try {
this.checkConnection();
this.concurrencyTestHooks.beforePollProcessorStart();
if (this.mBeanAccessConnection instanceof MBeanBatchCapableAccessConnection) {
this.batchPollProcessor.pollBatch((MBeanBatchCapableAccessConnection) this.mBeanAccessConnection,
this.polledObjects);
} else {
this.pollIndividually();
}
} catch (IOException ioExc) {
this.safeClose(this.mBeanAccessConnection);
this.mBeanAccessConnection = null;
throw ioExc;
} finally {
this.concurrencyTestHooks.afterPollProcessorFinish();
synchronized (this) {
pollActiveInd = false;
this.notifyAll();
}
}
}
|
java
|
{
"resource": ""
}
|
q180258
|
JmxAttributePoller.pollIndividually
|
test
|
protected boolean pollIndividually() throws IOException {
this.concurrencyTestHooks.onStartPollIndividually();
List<SchedulerProcessExecutionSlip> processExecutionSlipList = new LinkedList<>();
for (final Object onePolledObject : this.polledObjects) {
// Stop as soon as possible if shutting down.
if (shutdownInd) {
return true;
}
SchedulerProcess process = new PollOneObjectSchedulerProcess(onePolledObject);
SchedulerProcessExecutionSlip executionSlip = this.scheduler.startProcess(process);
processExecutionSlipList.add(executionSlip);
}
for (SchedulerProcessExecutionSlip oneExecutionSlip : processExecutionSlipList) {
try {
//
// Wait for this process to complete
//
oneExecutionSlip.waitUntilComplete();
//
// Check for a failure
//
PollOneObjectSchedulerProcess process =
(PollOneObjectSchedulerProcess) oneExecutionSlip.getSchedulerProcess();
Exception exc = process.getFailureException();
if (exc != null) {
log.warn("failed to poll object", exc);
// Propagate IOExceptions since they most likely mean that the connection needs to be recovered.
if (exc instanceof IOException) {
throw (IOException) exc;
}
}
} catch (InterruptedException intExc) {
log.info("interrupted while polling object");
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q180259
|
ClassUtil.getDeclaredField
|
test
|
public static Field getDeclaredField(Class<?> clazz, String fieldName,
boolean recursively) {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && recursively) {
return getDeclaredField(superClass, fieldName, true);
}
} catch (SecurityException e) {
log.error("{}",e.getMessage(),e);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180260
|
ClassUtil.getDeclaredMethods
|
test
|
public static Method[] getDeclaredMethods(Class<?> clazz,
boolean recursively) {
List<Method> methods = new LinkedList<Method>();
Method[] declaredMethods = clazz.getDeclaredMethods();
Collections.addAll(methods, declaredMethods);
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && recursively) {
Method[] declaredMethodsOfSuper = getDeclaredMethods(superClass,
true);
if (declaredMethodsOfSuper.length > 0)
Collections.addAll(methods, declaredMethodsOfSuper);
}
return methods.toArray(new Method[methods.size()]);
}
|
java
|
{
"resource": ""
}
|
q180261
|
ClassUtil.getDeclaredMethod
|
test
|
public static Method getDeclaredMethod(Class<?> clazz, boolean recursively,
String methodName, Class<?>... parameterTypes) {
try {
return clazz.getDeclaredMethod(methodName,
parameterTypes);
} catch (NoSuchMethodException e) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && recursively) {
return getDeclaredMethod(superClass, true, methodName,
parameterTypes);
}
} catch (SecurityException e) {
log.error("{}",e.getMessage(),e);
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180262
|
ClassUtil.getAnnotatedDeclaredMethods
|
test
|
public static Method[] getAnnotatedDeclaredMethods(Class<?> clazz,
Class<? extends Annotation> annotationClass, boolean recursively) {
Method[] allMethods = getDeclaredMethods(clazz, recursively);
List<Method> annotatedMethods = new LinkedList<Method>();
for (Method method : allMethods) {
if (method.isAnnotationPresent(annotationClass))
annotatedMethods.add(method);
}
return annotatedMethods.toArray(new Method[annotatedMethods.size()]);
}
|
java
|
{
"resource": ""
}
|
q180263
|
ClassUtil.getAnnotatedDeclaredConstructors
|
test
|
public static Constructor<?>[] getAnnotatedDeclaredConstructors(
Class<?> clazz, Class<? extends Annotation> annotationClass,
boolean recursively) {
Constructor<?>[] allConstructors = getDeclaredConstructors(clazz,
recursively);
List<Constructor<?>> annotatedConstructors = new LinkedList<Constructor<?>>();
for (Constructor<?> field : allConstructors) {
if (field.isAnnotationPresent(annotationClass))
annotatedConstructors.add(field);
}
return annotatedConstructors
.toArray(new Constructor<?>[annotatedConstructors.size()]);
}
|
java
|
{
"resource": ""
}
|
q180264
|
DebugOutputStream.dumpByte
|
test
|
protected void dumpByte(int b) {
if (passThrough == true) {
System.out.print('\t');
}
if (b < 0) {
b += 128;
}
if (b < 0x10) {
System.out.print('0');
}
System.out.print(' ');
System.out.print(Integer.toHexString(b).toUpperCase());
}
|
java
|
{
"resource": ""
}
|
q180265
|
StringUtils.indexOfIgnoreCase
|
test
|
public static int indexOfIgnoreCase(String s, String substr, int startIndex, int endIndex) {
if (startIndex < 0) {
startIndex = 0;
}
int srclen = s.length();
if (endIndex > srclen) {
endIndex = srclen;
}
int sublen = substr.length();
if (sublen == 0) {
return startIndex > srclen ? srclen : startIndex;
}
substr = substr.toLowerCase();
int total = endIndex - sublen + 1;
char c = substr.charAt(0);
mainloop: for (int i = startIndex; i < total; i++) {
if (Character.toLowerCase(s.charAt(i)) != c) {
continue;
}
int j = 1;
int k = i + 1;
while (j < sublen) {
char source = Character.toLowerCase(s.charAt(k));
if (substr.charAt(j) != source) {
continue mainloop;
}
j++;
k++;
}
return i;
}
return -1;
}
|
java
|
{
"resource": ""
}
|
q180266
|
StringUtils.removeChars
|
test
|
public static String removeChars(String s, String chars) {
int i = s.length();
StringBuilder sb = new StringBuilder(i);
for (int j = 0; j < i; j++) {
char c = s.charAt(j);
if (chars.indexOf(c) == -1) {
sb.append(c);
}
}
return sb.toString();
}
|
java
|
{
"resource": ""
}
|
q180267
|
PasswordLoginModule.cleanState
|
test
|
@SuppressWarnings("PMD.NullAssignment")
private void cleanState() {
// null-assignments for de-referencing objects are okay
domain = null;
username = null;
Cleanser.wipe(password);
pendingSubject = null;
committedSubject = null;
}
|
java
|
{
"resource": ""
}
|
q180268
|
PasswordLoginModule.initAudit
|
test
|
@SuppressWarnings("PMD.ConfusingTernary")
private void initAudit(final CommonProperties commonProps) {
try {
final String auditClassName = commonProps.getAuditClassName();
// this would be harder to read when following PMD's advice - ignoring the PMD warning
if (!commonProps.isAuditEnabled()) {
final String error = "Auditing has been disabled in the JAAS configuration";
LOG.info(error);
} else if (auditClassName == null) {
final String error =
"Auditing has been enabled in the JAAS configuration, but no audit class has been configured";
LOG.error(error);
throw new IllegalStateException(error);
} else {
if (commonProps.isAuditSingleton()) {
LOG.debug("Requesting singleton audit class instance of '" + auditClassName
+ "' from the audit factory");
this.audit = AuditFactory.getSingleton(auditClassName, commonProps);
} else {
LOG.debug("Requesting non-singleton audit class instance of '" + auditClassName
+ "' from the audit factory");
this.audit = AuditFactory.getInstance(auditClassName, commonProps);
}
}
} catch (FactoryException e) {
final String error = "The audit class cannot be instantiated. This is most likely a configuration"
+ " problem. Is the configured class available in the classpath?";
LOG.error(error, e);
throw new IllegalStateException(error, e);
}
}
|
java
|
{
"resource": ""
}
|
q180269
|
PasswordLoginModule.initMessageQueue
|
test
|
@SuppressWarnings("PMD.ConfusingTernary")
private void initMessageQueue(final CommonProperties commonProps) {
try {
final String messageClassName = commonProps.getMessageQueueClassName();
// this would be harder to read when following PMD's advice - ignoring the PMD warning
if (!commonProps.isMessageQueueEnabled()) {
final String error = "Message queue has been disabled in the JAAS configuration";
LOG.info(error);
} else if (messageClassName == null) {
final String error = "Message queue has been enabled in the JAAS configuration, "
+ "but no message queue class has been configured";
LOG.error(error);
throw new IllegalStateException(error);
} else {
if (commonProps.isMessageQueueSingleton()) {
LOG.debug("Requesting singleton message class instance of '" + messageClassName
+ "' from the message factory");
this.messageQ = MessageQFactory.getSingleton(messageClassName, commonProps);
} else {
LOG.debug("Requesting non-singleton message class instance of '" + messageClassName
+ "' from the message factory");
this.messageQ = MessageQFactory.getInstance(messageClassName, commonProps);
}
}
} catch (FactoryException e) {
final String error = "The message class cannot be instantiated. This is most likely a configuration"
+ " problem. Is the configured class available in the classpath?";
LOG.error(error, e);
throw new IllegalStateException(error, e);
}
}
|
java
|
{
"resource": ""
}
|
q180270
|
PasswordLoginModule.initPwValidator
|
test
|
private void initPwValidator(final CommonProperties commonProps) {
try {
final String validatorClass = commonProps.getPasswordValidatorClassName();
if (validatorClass == null) {
final String error = "No password validator class has been configured in the JAAS configuration";
LOG.error(error);
throw new IllegalStateException(error);
} else {
if (commonProps.isPasswordValidatorSingleton()) {
// Fortify will report a violation here because of disclosure of potentially confidential
// information. However, the class name is not confidential, which makes this a non-issue / false
// positive.
LOG.debug("Requesting singleton validator class instance of '" + validatorClass
+ "' from the validator factory");
this.pwValidator = PasswordValidatorFactory.getSingleton(validatorClass, commonProps);
} else {
// Fortify will report a violation here because of disclosure of potentially confidential
// information. However, the class name is not confidential, which makes this a non-issue / false
// positive.
LOG.debug("Requesting non-singleton validator class instance of '" + validatorClass
+ "' from the validator factory");
this.pwValidator = PasswordValidatorFactory.getInstance(validatorClass, commonProps);
}
}
} catch (FactoryException e) {
final String error = "The validator class cannot be instantiated. This is most likely a configuration"
+ " problem. Is the configured class available in the classpath?";
LOG.error(error, e);
throw new IllegalStateException(error, e);
}
}
|
java
|
{
"resource": ""
}
|
q180271
|
PasswordLoginModule.initPwAuthenticator
|
test
|
private void initPwAuthenticator(final CommonProperties commonProps) {
try {
final String authNticatorClass = commonProps.getPasswordAuthenticatorClassName();
if (authNticatorClass == null) {
final String error = "No password authenticator class has been configured in the JAAS configuration";
LOG.error(error);
throw new IllegalStateException(error);
} else {
if (commonProps.isPasswordAuthenticatorSingleton()) {
// Fortify will report a violation here because of disclosure of potentially confidential
// information. However, the class name is not confidential, which makes this a non-issue / false
// positive.
LOG.debug("Requesting singleton authenticator class instance of '" + authNticatorClass
+ "' from the authenticator factory");
this.pwAuthenticator = PasswordAuthenticatorFactory.getSingleton(authNticatorClass, commonProps);
} else {
// Fortify will report a violation here because of disclosure of potentially confidential
// information. However, the class name is not confidential, which makes this a non-issue / false
// positive.
LOG.debug("Requesting non-singleton authenticator class instance of '" + authNticatorClass
+ "' from the authenticator factory");
this.pwAuthenticator = PasswordAuthenticatorFactory.getInstance(authNticatorClass, commonProps);
}
}
} catch (FactoryException e) {
final String error = "The validator class cannot be instantiated. This is most likely a configuration"
+ " problem. Is the configured class available in the classpath?";
LOG.error(error, e);
throw new IllegalStateException(error, e);
}
}
|
java
|
{
"resource": ""
}
|
q180272
|
LocaleUtils.resolveLocaleCode
|
test
|
public static String resolveLocaleCode(final Locale locale) {
return resolveLocaleCode(locale.getLanguage(), locale.getCountry(), locale.getVariant());
}
|
java
|
{
"resource": ""
}
|
q180273
|
LocaleUtils.lookupLocaleInfo
|
test
|
protected static LocaleInfo lookupLocaleInfo(final String code) {
LocaleInfo info = locales.get(code);
if (info == null) {
String[] data = decodeLocaleCode(code);
info = new LocaleInfo(new Locale(data[0], data[1], data[2]));
locales.put(code, info);
}
return info;
}
|
java
|
{
"resource": ""
}
|
q180274
|
JdbcLogStatement.getInstance
|
test
|
public static Statement getInstance(Statement stmt) {
InvocationHandler handler = new JdbcLogStatement(stmt);
ClassLoader cl = Statement.class.getClassLoader();
return (Statement) Proxy.newProxyInstance(cl, new Class[] { Statement.class }, handler);
}
|
java
|
{
"resource": ""
}
|
q180275
|
ArrayStack.clear
|
test
|
public void clear() {
int i = size;
Object[] els = elements;
while (i-- > 0) {
els[i] = null;
}
this.size = 0;
}
|
java
|
{
"resource": ""
}
|
q180276
|
ArrayStack.push
|
test
|
public T push(T element) {
int i;
Object[] els;
if ((i = size++) >= (els = elements).length) {
System.arraycopy(els, 0, els = elements = new Object[i << 1], 0, i);
}
els[i] = element;
return element;
}
|
java
|
{
"resource": ""
}
|
q180277
|
ArrayStack.pop
|
test
|
@SuppressWarnings("unchecked")
public T pop() throws EmptyStackException {
int i;
if ((i = --size) >= 0) {
T element = (T) elements[i];
elements[i] = null;
return element;
} else {
size = 0;
throw new EmptyStackException();
}
}
|
java
|
{
"resource": ""
}
|
q180278
|
BaseSourceFile.makeInStream
|
test
|
public InputStream makeInStream()
{
if (m_InputStream != null)
return m_InputStream;
try {
return new FileInputStream(m_inputFile);
} catch (FileNotFoundException ex) {
System.out.println("Warning: scanned file does not exist: " + m_inputFile.getPath()); // Skip this file
}
return null;
}
|
java
|
{
"resource": ""
}
|
q180279
|
AppUtilities.parseArgs
|
test
|
public static Properties parseArgs(Properties properties, String[] args)
{
if (properties == null)
properties = new Properties();
if (args == null)
return properties;
for (int i = 0; i < args.length; i++)
AppUtilities.addParam(properties, args[i], false);
return properties;
}
|
java
|
{
"resource": ""
}
|
q180280
|
WildcharPathUtils.matchTokens
|
test
|
protected static boolean matchTokens(String[] tokens, String[] patterns) {
int patNdxStart = 0;
int patNdxEnd = patterns.length - 1;
int tokNdxStart = 0;
int tokNdxEnd = tokens.length - 1;
while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // find first **
String patDir = patterns[patNdxStart];
if (patDir.equals(PATH_MATCH)) {
break;
}
if (!WildcharUtils.match(tokens[tokNdxStart], patDir)) {
return false;
}
patNdxStart++;
tokNdxStart++;
}
if (tokNdxStart > tokNdxEnd) {
for (int i = patNdxStart; i <= patNdxEnd; i++) { // string is finished
if (!patterns[i].equals(PATH_MATCH)) {
return false;
}
}
return true;
}
if (patNdxStart > patNdxEnd) {
return false; // string is not finished, but pattern is
}
while (patNdxStart <= patNdxEnd && tokNdxStart <= tokNdxEnd) { // to the last **
String patDir = patterns[patNdxEnd];
if (patDir.equals(PATH_MATCH)) {
break;
}
if (!WildcharUtils.match(tokens[tokNdxEnd], patDir)) {
return false;
}
patNdxEnd--;
tokNdxEnd--;
}
if (tokNdxStart > tokNdxEnd) {
for (int i = patNdxStart; i <= patNdxEnd; i++) { // string is finished
if (!patterns[i].equals(PATH_MATCH)) {
return false;
}
}
return true;
}
while ((patNdxStart != patNdxEnd) && (tokNdxStart <= tokNdxEnd)) {
int patIdxTmp = -1;
for (int i = patNdxStart + 1; i <= patNdxEnd; i++) {
if (patterns[i].equals(PATH_MATCH)) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == patNdxStart + 1) {
patNdxStart++; // skip **/** situation
continue;
}
// find the pattern between padIdxStart & padIdxTmp in str between strIdxStart & strIdxEnd
int patLength = (patIdxTmp - patNdxStart - 1);
int strLength = (tokNdxEnd - tokNdxStart + 1);
int ndx = -1;
strLoop: for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = patterns[patNdxStart + j + 1];
String subStr = tokens[tokNdxStart + i + j];
if (!WildcharUtils.match(subStr, subPat)) {
continue strLoop;
}
}
ndx = tokNdxStart + i;
break;
}
if (ndx == -1) {
return false;
}
patNdxStart = patIdxTmp;
tokNdxStart = ndx + patLength;
}
for (int i = patNdxStart; i <= patNdxEnd; i++) {
if (!patterns[i].equals(PATH_MATCH)) {
return false;
}
}
return true;
}
|
java
|
{
"resource": ""
}
|
q180281
|
Rectangular.move
|
test
|
public void move(int xofs, int yofs)
{
x1 += xofs;
y1 += yofs;
x2 += xofs;
y2 += yofs;
}
|
java
|
{
"resource": ""
}
|
q180282
|
Rectangular.encloses
|
test
|
public boolean encloses(Rectangular other)
{
return x1 <= other.x1 &&
y1 <= other.y1 &&
x2 >= other.x2 &&
y2 >= other.y2;
}
|
java
|
{
"resource": ""
}
|
q180283
|
Rectangular.contains
|
test
|
public boolean contains(int x, int y)
{
return x1 <= x &&
y1 <= y &&
x2 >= x &&
y2 >= y;
}
|
java
|
{
"resource": ""
}
|
q180284
|
Rectangular.intersection
|
test
|
public Rectangular intersection(Rectangular other)
{
if (this.intersects(other))
{
return new Rectangular(Math.max(x1, other.x1),
Math.max(y1, other.y1),
Math.min(x2, other.x2),
Math.min(y2, other.y2));
}
else
{
return new Rectangular(); //an empty rectangle
}
}
|
java
|
{
"resource": ""
}
|
q180285
|
Rectangular.union
|
test
|
public Rectangular union(Rectangular other)
{
return new Rectangular(Math.min(x1, other.x1),
Math.min(y1, other.y1),
Math.max(x2, other.x2),
Math.max(y2, other.y2));
}
|
java
|
{
"resource": ""
}
|
q180286
|
Rectangular.replaceX
|
test
|
public Rectangular replaceX(Rectangular other)
{
Rectangular ret = new Rectangular(this);
ret.x1 = other.x1;
ret.x2 = other.x2;
return ret;
}
|
java
|
{
"resource": ""
}
|
q180287
|
Rectangular.replaceY
|
test
|
public Rectangular replaceY(Rectangular other)
{
Rectangular ret = new Rectangular(this);
ret.y1 = other.y1;
ret.y2 = other.y2;
return ret;
}
|
java
|
{
"resource": ""
}
|
q180288
|
AreaGrid.getColOfs
|
test
|
public int getColOfs(int col) throws ArrayIndexOutOfBoundsException
{
if (col < width)
{
int ofs = 0;
for (int i = 0; i < col; i++)
ofs += cols[i];
return ofs;
}
else if (col == width)
return abspos.getWidth();
else
throw new ArrayIndexOutOfBoundsException(col + ">" + width);
}
|
java
|
{
"resource": ""
}
|
q180289
|
AreaGrid.getRowOfs
|
test
|
public int getRowOfs(int row) throws ArrayIndexOutOfBoundsException
{
if (row < height)
{
int ofs = 0;
for (int i = 0; i < row; i++)
ofs += rows[i];
return ofs;
}
else if (row == height)
return abspos.getHeight();
else
throw new ArrayIndexOutOfBoundsException(row + ">" + height);
}
|
java
|
{
"resource": ""
}
|
q180290
|
AreaGrid.getCellBoundsRelative
|
test
|
public Rectangular getCellBoundsRelative(int x, int y)
{
int x1 = getColOfs(x);
int y1 = getRowOfs(y);
int x2 = (x == width-1) ? abspos.getWidth() - 1 : x1 + cols[x] - 1;
int y2 = (y == height-1) ? abspos.getHeight() - 1 : y1 + rows[y] - 1;
return new Rectangular(x1, y1, x2, y2);
}
|
java
|
{
"resource": ""
}
|
q180291
|
AreaGrid.calculateColumns
|
test
|
private void calculateColumns()
{
//create the sorted list of points
GridPoint points[] = new GridPoint[areas.size() * 2];
int pi = 0;
for (Area area : areas)
{
points[pi] = new GridPoint(area.getX1(), area, true);
points[pi+1] = new GridPoint(area.getX2() + 1, area, false);
pi += 2;
//X2+1 ensures that the end of one box will be on the same point
//as the start of the following box
}
Arrays.sort(points);
//calculate the number of columns
int cnt = 0;
int last = abspos.getX1();
for (int i = 0; i < points.length; i++)
if (!theSame(points[i].value, last))
{
last = points[i].value;
cnt++;
}
if (!theSame(last, abspos.getX2()))
cnt++; //last column finishes the whole area
width = cnt;
//calculate the column widths and the layout
maxindent = 0;
minindent = -1;
cols = new int[width];
cnt = 0;
last = abspos.getX1();
for (int i = 0; i < points.length; i++)
{
if (!theSame(points[i].value, last))
{
cols[cnt] = points[i].value - last;
last = points[i].value;
cnt++;
}
if (points[i].begin)
{
target.getPosition(points[i].area).setX1(cnt);
maxindent = cnt;
if (minindent == -1) minindent = maxindent;
//points[i].node.getArea().setX1(parent.getArea().getX1() + getColOfs(cnt));
}
else
{
Rectangular pos = target.getPosition(points[i].area);
pos.setX2(cnt-1);
if (pos.getX2() < pos.getX1())
pos.setX2(pos.getX1());
//points[i].node.getArea().setX2(parent.getArea().getX1() + getColOfs(pos.getX2()+1));
}
}
if (!theSame(last, abspos.getX2()))
cols[cnt] = abspos.getX2() - last;
if (minindent == -1)
minindent = 0;
}
|
java
|
{
"resource": ""
}
|
q180292
|
AreaGrid.calculateRows
|
test
|
private void calculateRows()
{
//create the sorted list of points
GridPoint points[] = new GridPoint[areas.size() * 2];
int pi = 0;
for (Area area : areas)
{
points[pi] = new GridPoint(area.getY1(), area, true);
points[pi+1] = new GridPoint(area.getY2() + 1, area, false);
pi += 2;
//Y2+1 ensures that the end of one box will be on the same point
//as the start of the following box
}
Arrays.sort(points);
//calculate the number of rows
int cnt = 0;
int last = abspos.getY1();
for (int i = 0; i < points.length; i++)
if (!theSame(points[i].value, last))
{
last = points[i].value;
cnt++;
}
if (!theSame(last, abspos.getY2()))
cnt++; //last row finishes the whole area
height = cnt;
//calculate the row heights and the layout
rows = new int[height];
cnt = 0;
last = abspos.getY1();
for (int i = 0; i < points.length; i++)
{
if (!theSame(points[i].value, last))
{
rows[cnt] = points[i].value - last;
last = points[i].value;
cnt++;
}
if (points[i].begin)
{
target.getPosition(points[i].area).setY1(cnt);
//points[i].node.getArea().setY1(parent.getArea().getY1() + getRowOfs(cnt));
}
else
{
Rectangular pos = target.getPosition(points[i].area);
pos.setY2(cnt-1);
if (pos.getY2() < pos.getY1())
pos.setY2(pos.getY1());
//points[i].node.getArea().setY2(parent.getArea().getY1() + getRowOfs(pos.getY2()+1));
}
}
if (!theSame(last, abspos.getY2()))
rows[cnt] = abspos.getY2() - last;
}
|
java
|
{
"resource": ""
}
|
q180293
|
JdbcLogSupport.unwrapThrowable
|
test
|
protected Throwable unwrapThrowable(Throwable t) {
Throwable e = t;
while (true) {
if (e instanceof InvocationTargetException) {
e = ((InvocationTargetException) t).getTargetException();
} else if (t instanceof UndeclaredThrowableException) {
e = ((UndeclaredThrowableException) t).getUndeclaredThrowable();
} else {
return e;
}
}
}
|
java
|
{
"resource": ""
}
|
q180294
|
Main.main
|
test
|
public static void main(String[] args)
{
try
{
Main main = new Main();
main.start();
Runtime.getRuntime().addShutdownHook(main.getShutdownHook());
main.awaitTermination(1, TimeUnit.DAYS);
}
catch (InterruptedException e)
{
e = null;
Thread.currentThread().interrupt();
}
}
|
java
|
{
"resource": ""
}
|
q180295
|
ByteCodeMonitor.onCodeUpdate
|
test
|
public void onCodeUpdate(ByteBuffer codeBuffer, int start, int length, VariableAndFunctorInterner interner,
WAMCodeView codeView)
{
log.fine("public void onCodeUpdate(ByteBuffer codeBuffer, int start = " + start + ", int length = " + length +
", VariableAndFunctorInterner interner, WAMCodeView codeView): called");
// Take a copy of the new bytecode.
copyAndResizeCodeBuffer(codeBuffer, start, length);
// Disassemble the new area of byte code.
SizeableList<WAMInstruction> instructions =
WAMInstruction.disassemble(start, length, this.codeBuffer, interner, codeView);
// Figure out where to start writing the disassembled code into the table.
Map.Entry<Integer, Integer> entry = addressToRow.floorEntry(start);
int firstRow = (entry == null) ? 0 : (entry.getValue() + 1);
int address = start;
int row = firstRow;
// Build the mapping between addresses and rows.
for (WAMInstruction instruction : instructions)
{
addressToRow.put(address, row);
rowToAddress.add(row, address);
row++;
address += instruction.sizeof();
}
// Render the instructions into the table to be displayed.
renderInstructions(instructions, firstRow, start);
}
|
java
|
{
"resource": ""
}
|
q180296
|
ByteCodeMonitor.copyAndResizeCodeBuffer
|
test
|
private void copyAndResizeCodeBuffer(ByteBuffer codeBuffer, int start, int length)
{
// Check the internal code buffer is large enough or resize it, then copy in the new instructions.
int max = start + length;
if (this.codeBuffer.limit() <= max)
{
ByteBuffer newCodeBuffer = ByteBuffer.allocate(max * 2);
newCodeBuffer.put(this.codeBuffer.array(), 0, this.codeBuffer.limit());
log.fine("Re-sized code buffer to " + (max * 2));
}
codeBuffer.position(start);
codeBuffer.get(this.codeBuffer.array(), start, length);
}
|
java
|
{
"resource": ""
}
|
q180297
|
ByteCodeMonitor.renderInstructions
|
test
|
private void renderInstructions(Iterable<WAMInstruction> instructions, int row, int address)
{
for (WAMInstruction instruction : instructions)
{
WAMLabel label = instruction.getLabel();
labeledTable.put(ADDRESS, row, String.format("%08X", address));
labeledTable.put(LABEL, row, (label == null) ? "" : (label.toPrettyString() + ":"));
labeledTable.put(MNEMONIC, row, instruction.getMnemonic().getPretty());
int fieldMask = instruction.getMnemonic().getFieldMask();
String arg = "";
for (int i = 2; i < 32; i = i * 2)
{
if ((fieldMask & i) != 0)
{
if (!"".equals(arg))
{
arg += ", ";
}
switch (i)
{
case 2:
arg += Integer.toString(instruction.getReg1());
break;
case 4:
arg += Integer.toString(instruction.getReg2());
break;
case 8:
FunctorName fn = instruction.getFn();
if (fn != null)
{
arg += fn.getName() + "/" + fn.getArity();
}
break;
case 16:
WAMLabel target1 = instruction.getTarget1();
if (target1 != null)
{
arg += target1.getName() + "/" + target1.getArity() + "_" + target1.getId();
}
break;
}
}
}
labeledTable.put(ARG_1, row, arg);
row++;
address += instruction.sizeof();
}
}
|
java
|
{
"resource": ""
}
|
q180298
|
PropertyLoaderServlet.init
|
test
|
public void init()
{
log.fine("public void init(): called");
// Get the name of the property file resource to load and the application variable name to store it under
String propertyResource = getInitParameter(PROPERTY_RESOURCE);
String varName = getInitParameter(APP_VAR_NAME);
log.fine("varName = " + varName);
// Use the default property reader to load the resource
Properties properties = DefaultPropertyReader.getProperties(propertyResource);
log.fine("properties = " + properties);
// Store the properties under the specified variable name in the application scope
getServletContext().setAttribute(varName, properties);
}
|
java
|
{
"resource": ""
}
|
q180299
|
QueryParameter.partialCopy
|
test
|
public QueryParameter partialCopy(final QueryParameterKind... excludedElements) {
List<QueryParameterKind> excludedList = Arrays.asList(excludedElements);
QueryParameter returnValue = new QueryParameter();
if (!excludedList.contains(QueryParameterKind.CONSTRAINTS)) {
returnValue.rawConstraints = this.rawConstraints;
}
if (!excludedList.contains(QueryParameterKind.GROUPS)) {
returnValue.groups = this.groups;
}
if (!excludedList.contains(QueryParameterKind.ORDERS)) {
returnValue.orders = this.orders;
}
if (!excludedList.contains(QueryParameterKind.PAGE)) {
returnValue.pageSize = this.pageSize;
returnValue.page = this.page;
}
if (!excludedList.contains(QueryParameterKind.TIMEZONE)) {
returnValue.timezoneName = this.timezoneName;
}
return returnValue;
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.