_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q176300 | SyslogAppender.handleThrowableFirstLine | test | private void handleThrowableFirstLine(OutputStream sw, IThrowableProxy tp, String stackTracePrefix, boolean isRootException) throws IOException {
StringBuilder sb = new StringBuilder().append(stackTracePrefix);
if (!isRootException) {
sb.append(CoreConstants.CAUSED_BY);
}
sb.append(tp.getClassName()).append(": ").append(tp.getMessage());
sw.write(sb.toString().getBytes());
sw.flush();
} | java | {
"resource": ""
} |
q176301 | AbstractComponentTracker.getFromEitherMap | test | private Entry<C> getFromEitherMap(String key) {
Entry<C> entry = liveMap.get(key);
if (entry != null)
return entry;
else {
return lingerersMap.get(key);
}
} | java | {
"resource": ""
} |
q176302 | AbstractComponentTracker.endOfLife | test | public void endOfLife(String key) {
Entry<C> entry = liveMap.remove(key);
if (entry == null)
return;
lingerersMap.put(key, entry);
} | java | {
"resource": ""
} |
q176303 | FormatInfo.valueOf | test | public static FormatInfo valueOf(String str) throws IllegalArgumentException {
if (str == null) {
throw new NullPointerException("Argument cannot be null");
}
FormatInfo fi = new FormatInfo();
int indexOfDot = str.indexOf('.');
String minPart = null;
String maxPart = null;
if (indexOfDot != -1) {
minPart = str.substring(0, indexOfDot);
if (indexOfDot + 1 == str.length()) {
throw new IllegalArgumentException("Formatting string [" + str
+ "] should not end with '.'");
} else {
maxPart = str.substring(indexOfDot + 1);
}
} else {
minPart = str;
}
if (minPart != null && minPart.length() > 0) {
int min = Integer.parseInt(minPart);
if (min >= 0) {
fi.min = min;
} else {
fi.min = -min;
fi.leftPad = false;
}
}
if (maxPart != null && maxPart.length() > 0) {
int max = Integer.parseInt(maxPart);
if (max >= 0) {
fi.max = max;
} else {
fi.max = -max;
fi.leftTruncate = false;
}
}
return fi;
} | java | {
"resource": ""
} |
q176304 | RenameUtil.rename | test | public void rename(String src, String target) throws RolloverFailure {
if (src.equals(target)) {
addWarn("Source and target files are the same [" + src + "]. Skipping.");
return;
}
File srcFile = new File(src);
if (srcFile.exists()) {
File targetFile = new File(target);
createMissingTargetDirsIfNecessary(targetFile);
addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]");
boolean result = srcFile.renameTo(targetFile);
if (!result) {
addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "].");
Boolean areOnDifferentVolumes = areOnDifferentVolumes(srcFile, targetFile);
if (Boolean.TRUE.equals(areOnDifferentVolumes)) {
addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying.");
renameByCopying(src, target);
return;
} else {
addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty.");
addWarn("See also " + RENAMING_ERROR_URL);
}
}
} else {
throw new RolloverFailure("File [" + src + "] does not exist.");
}
} | java | {
"resource": ""
} |
q176305 | RenameUtil.areOnDifferentVolumes | test | Boolean areOnDifferentVolumes(File srcFile, File targetFile) throws RolloverFailure {
if (!EnvUtil.isJDK7OrHigher()) {
return false;
}
// target file is not certain to exist but its parent has to exist given the call hierarchy of this method
File parentOfTarget = targetFile.getAbsoluteFile().getParentFile();
if (parentOfTarget == null) {
addWarn("Parent of target file ["+targetFile+"] is null");
return null;
}
if (!parentOfTarget.exists()) {
addWarn("Parent of target file [" + targetFile + "] does not exist");
return null;
}
try {
boolean onSameFileStore = FileStoreUtil.areOnSameFileStore(srcFile, parentOfTarget);
return !onSameFileStore;
} catch (RolloverFailure rf) {
addWarn("Error while checking file store equality", rf);
return null;
}
} | java | {
"resource": ""
} |
q176306 | OptionHelper.getEnv | test | public static String getEnv(String key) {
try {
return System.getenv(key);
} catch (SecurityException e) {
return null;
}
} | java | {
"resource": ""
} |
q176307 | OptionHelper.getAndroidSystemProperty | test | public static String getAndroidSystemProperty(String key) {
try {
return SystemPropertiesProxy.getInstance().get(key, null);
} catch (IllegalArgumentException e) {
return null;
}
} | java | {
"resource": ""
} |
q176308 | LoggingEvent.setMDCPropertyMap | test | public void setMDCPropertyMap(Map<String, String> map) {
if (mdcPropertyMap != null) {
throw new IllegalStateException(
"The MDCPropertyMap has been already set for this event.");
}
this.mdcPropertyMap = map;
} | java | {
"resource": ""
} |
q176309 | MDCConverter.outputMDCForAllKeys | test | private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
if (first) {
first = false;
} else {
buf.append(", ");
}
//format: key0=value0, key1=value1
buf.append(entry.getKey()).append('=').append(entry.getValue());
}
return buf.toString();
} | java | {
"resource": ""
} |
q176310 | CallerData.extract | test | public static StackTraceElement[] extract(Throwable t,
String fqnOfInvokingClass, final int maxDepth,
List<String> frameworkPackageList) {
if (t == null) {
return null;
}
StackTraceElement[] steArray = t.getStackTrace();
StackTraceElement[] callerDataArray;
int found = LINE_NA;
for (int i = 0; i < steArray.length; i++) {
if (isInFrameworkSpace(steArray[i].getClassName(),
fqnOfInvokingClass, frameworkPackageList)) {
// the caller is assumed to be the next stack frame, hence the +1.
found = i + 1;
} else {
if (found != LINE_NA) {
break;
}
}
}
// we failed to extract caller data
if (found == LINE_NA) {
return EMPTY_CALLER_DATA_ARRAY;
}
int availableDepth = steArray.length - found;
int desiredDepth = maxDepth < (availableDepth) ? maxDepth : availableDepth;
callerDataArray = new StackTraceElement[desiredDepth];
for (int i = 0; i < desiredDepth; i++) {
callerDataArray[i] = steArray[found + i];
}
return callerDataArray;
} | java | {
"resource": ""
} |
q176311 | CallerData.isInFrameworkSpaceList | test | private static boolean isInFrameworkSpaceList(String currentClass, List<String> frameworkPackageList) {
if (frameworkPackageList == null)
return false;
for (String s : frameworkPackageList) {
if (currentClass.startsWith(s))
return true;
}
return false;
} | java | {
"resource": ""
} |
q176312 | BasicStatusManager.add | test | public void add(Status newStatus) {
// LBCORE-72: fire event before the count check
fireStatusAddEvent(newStatus);
count++;
if (newStatus.getLevel() > level) {
level = newStatus.getLevel();
}
synchronized (statusListLock) {
if (statusList.size() < MAX_HEADER_COUNT) {
statusList.add(newStatus);
} else {
tailBuffer.add(newStatus);
}
}
} | java | {
"resource": ""
} |
q176313 | BasicStatusManager.add | test | public boolean add(StatusListener listener) {
synchronized (statusListenerListLock) {
if (listener instanceof OnConsoleStatusListener) {
boolean alreadyPresent = checkForPresence(statusListenerList, listener.getClass());
if (alreadyPresent) {
return false;
}
}
statusListenerList.add(listener);
}
return true;
} | java | {
"resource": ""
} |
q176314 | Interpreter.lookupImplicitAction | test | List<Action> lookupImplicitAction(ElementPath elementPath, Attributes attributes,
InterpretationContext ec) {
int len = implicitActions.size();
for (int i = 0; i < len; i++) {
ImplicitAction ia = (ImplicitAction) implicitActions.get(i);
if (ia.isApplicable(elementPath, attributes, ec)) {
List<Action> actionList = new ArrayList<Action>(1);
actionList.add(ia);
return actionList;
}
}
return null;
} | java | {
"resource": ""
} |
q176315 | Interpreter.getApplicableActionList | test | List<Action> getApplicableActionList(ElementPath elementPath, Attributes attributes) {
List<Action> applicableActionList = ruleStore.matchActions(elementPath);
// logger.debug("set of applicable patterns: " + applicableActionList);
if (applicableActionList == null) {
applicableActionList = lookupImplicitAction(elementPath, attributes,
interpretationContext);
}
return applicableActionList;
} | java | {
"resource": ""
} |
q176316 | SystemPropertiesProxy.setClassLoader | test | public void setClassLoader(ClassLoader cl)
throws ClassNotFoundException, SecurityException, NoSuchMethodException {
if (cl == null) cl = this.getClass().getClassLoader();
SystemProperties = cl.loadClass("android.os.SystemProperties");
getString = SystemProperties.getMethod("get", new Class[]{ String.class, String.class });
getBoolean = SystemProperties.getMethod("getBoolean", new Class[]{ String.class, boolean.class });
} | java | {
"resource": ""
} |
q176317 | SystemPropertiesProxy.get | test | public String get(String key, String def)
throws IllegalArgumentException {
if (SystemProperties == null || getString == null) return null;
String ret = null;
try {
ret = (String) getString.invoke(SystemProperties, new Object[]{ key, def });
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
}
// if return value is null or empty, use the default
// since neither of those are valid values
if (ret == null || ret.length() == 0) {
ret = def;
}
return ret;
} | java | {
"resource": ""
} |
q176318 | SystemPropertiesProxy.getBoolean | test | public Boolean getBoolean(String key, boolean def)
throws IllegalArgumentException {
if (SystemProperties == null || getBoolean == null) return def;
Boolean ret = def;
try {
ret = (Boolean) getBoolean.invoke(SystemProperties, new Object[]{ key, def });
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
}
return ret;
} | java | {
"resource": ""
} |
q176319 | Introspector.decapitalize | test | static public String decapitalize(String name) {
if (name == null || name.length() == 0) {
return name;
} else {
String nm = name.substring(0, 1).toLowerCase(Locale.US);
if (name.length() > 1) {
nm += name.substring(1);
}
return nm;
}
} | java | {
"resource": ""
} |
q176320 | Introspector.getMethodDescriptors | test | static public MethodDescriptor[] getMethodDescriptors(Class<?> clazz) {
ArrayList<MethodDescriptor> methods = new ArrayList<MethodDescriptor>();
for (Method m : clazz.getMethods()) {
methods.add(new MethodDescriptor(m.getName(), m));
}
return methods.toArray(new MethodDescriptor[0]);
} | java | {
"resource": ""
} |
q176321 | Introspector.getPropertyDescriptors | test | static public PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) {
final String SETTER_PREFIX = "set";
final String GETTER_PREFIX = "get";
final int LEN_PREFIX = SETTER_PREFIX.length();
Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();
for (Method m : clazz.getMethods()) {
PropertyDescriptor pd = null;
String mName = m.getName();
boolean isGet = mName.startsWith(GETTER_PREFIX) && (mName.length() > LEN_PREFIX);
boolean isSet = mName.startsWith(SETTER_PREFIX) && (mName.length() > LEN_PREFIX);
if (isGet || isSet) {
String propName = decapitalize(mName.substring(LEN_PREFIX));
pd = map.get(propName);
if (pd == null) {
pd = new PropertyDescriptor(propName);
map.put(propName, pd);
}
Class<?>[] parmTypes = m.getParameterTypes();
if (isSet) {
if (parmTypes.length == 1) { // we only want the single-parm setter
pd.setWriteMethod(m);
pd.setPropertyType(parmTypes[0]);
}
} else if (isGet) {
if (parmTypes.length == 0) { // we only want the zero-parm getter
pd.setReadMethod(m);
// let setter's type take priority
if (pd.getPropertyType() == null) {
pd.setPropertyType(m.getReturnType());
}
}
}
}
}
return map.values().toArray(new PropertyDescriptor[0]);
} | java | {
"resource": ""
} |
q176322 | OutputStreamAppender.start | test | public void start() {
int errors = 0;
if (this.encoder == null) {
addStatus(new ErrorStatus("No encoder set for the appender named \""
+ name + "\".", this));
errors++;
}
if (this.outputStream == null) {
addStatus(new ErrorStatus(
"No output stream set for the appender named \"" + name + "\".", this));
errors++;
}
// only error free appenders should be activated
if (errors == 0) {
super.start();
}
} | java | {
"resource": ""
} |
q176323 | StatusListenerConfigHelper.addOnConsoleListenerInstance | test | static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) {
onConsoleStatusListener.setContext(context);
boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener);
if (effectivelyAdded) {
onConsoleStatusListener.start();
}
} | java | {
"resource": ""
} |
q176324 | DefinePropertyAction.end | test | public void end(InterpretationContext ec, String name) {
if (inError) {
return;
}
Object o = ec.peekObject();
if (o != definer) {
addWarn("The object at the of the stack is not the property definer for property named ["
+ propertyName + "] pushed earlier.");
} else {
addInfo("Popping property definer for property named [" + propertyName
+ "] from the object stack");
ec.popObject();
// let's put defined property and value to context but only if it is
// not null
String propertyValue = definer.getPropertyValue();
if(propertyValue != null) {
ActionUtil.setProperty(ec, propertyName, propertyValue, scope);
}
}
} | java | {
"resource": ""
} |
q176325 | ContextBasedDiscriminator.getDiscriminatingValue | test | public String getDiscriminatingValue(ILoggingEvent event) {
String contextName = event.getLoggerContextVO().getName();
if (contextName == null) {
return defaultValue;
} else {
return contextName;
}
} | java | {
"resource": ""
} |
q176326 | AsyncAppender.isDiscardable | test | protected boolean isDiscardable(ILoggingEvent event) {
Level level = event.getLevel();
return level.toInt() <= Level.INFO_INT;
} | java | {
"resource": ""
} |
q176327 | ShutdownHookAction.begin | test | @Override
public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException {
hook = null;
inError = false;
String className = attributes.getValue(CLASS_ATTRIBUTE);
if (OptionHelper.isEmpty(className)) {
className = DefaultShutdownHook.class.getName();
addInfo("Assuming className [" + className + "]");
}
try {
addInfo("About to instantiate shutdown hook of type [" + className + "]");
hook = (ShutdownHookBase) OptionHelper.instantiateByClassName(className,
ShutdownHookBase.class, context);
hook.setContext(context);
ic.pushObject(hook);
}catch (Exception e) {
inError = true;
addError("Could not create a shutdown hook of type [" + className + "].", e);
throw new ActionException(e);
}
} | java | {
"resource": ""
} |
q176328 | ShutdownHookAction.end | test | @Override
public void end(InterpretationContext ic, String name) throws ActionException {
if (inError) {
return;
}
Object o = ic.peekObject();
if (o != hook) {
addWarn("The object at the of the stack is not the hook pushed earlier.");
} else {
ic.popObject();
Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");
addInfo("Registering shutdown hook with JVM runtime");
context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread);
Runtime.getRuntime().addShutdownHook(hookThread);
}
} | java | {
"resource": ""
} |
q176329 | SSLParametersConfiguration.enabledProtocols | test | private String[] enabledProtocols(String[] supportedProtocols,
String[] defaultProtocols) {
if (enabledProtocols == null) {
// we're assuming that the same engine is used for all configurables
// so once we determine the enabled set, we won't do it again
if (OptionHelper.isEmpty(getIncludedProtocols())
&& OptionHelper.isEmpty(getExcludedProtocols())) {
enabledProtocols = Arrays.copyOf(defaultProtocols,
defaultProtocols.length);
}
else {
enabledProtocols = includedStrings(supportedProtocols,
getIncludedProtocols(), getExcludedProtocols());
}
for (String protocol : enabledProtocols) {
addInfo("enabled protocol: " + protocol);
}
}
return enabledProtocols;
} | java | {
"resource": ""
} |
q176330 | SSLParametersConfiguration.enabledCipherSuites | test | private String[] enabledCipherSuites(String[] supportedCipherSuites,
String[] defaultCipherSuites) {
if (enabledCipherSuites == null) {
// we're assuming that the same engine is used for all configurables
// so once we determine the enabled set, we won't do it again
if (OptionHelper.isEmpty(getIncludedCipherSuites())
&& OptionHelper.isEmpty(getExcludedCipherSuites())) {
enabledCipherSuites = Arrays.copyOf(defaultCipherSuites,
defaultCipherSuites.length);
}
else {
enabledCipherSuites = includedStrings(supportedCipherSuites,
getIncludedCipherSuites(), getExcludedCipherSuites());
}
for (String cipherSuite : enabledCipherSuites) {
addInfo("enabled cipher suite: " + cipherSuite);
}
}
return enabledCipherSuites;
} | java | {
"resource": ""
} |
q176331 | SSLParametersConfiguration.includedStrings | test | private String[] includedStrings(String[] defaults, String included,
String excluded) {
List<String> values = new ArrayList<String>(defaults.length);
values.addAll(Arrays.asList(defaults));
if (included != null) {
StringCollectionUtil.retainMatching(values, stringToArray(included));
}
if (excluded != null) {
StringCollectionUtil.removeMatching(values, stringToArray(excluded));
}
return values.toArray(new String[values.size()]);
} | java | {
"resource": ""
} |
q176332 | ActionUtil.stringToScope | test | static public Scope stringToScope(String scopeStr) {
if(Scope.SYSTEM.toString().equalsIgnoreCase(scopeStr))
return Scope.SYSTEM;
if(Scope.CONTEXT.toString().equalsIgnoreCase(scopeStr))
return Scope.CONTEXT;
return Scope.LOCAL;
} | java | {
"resource": ""
} |
q176333 | ActionUtil.setProperties | test | static public void setProperties(InterpretationContext ic, Properties props,
Scope scope) {
switch (scope) {
case LOCAL:
ic.addSubstitutionProperties(props);
break;
case CONTEXT:
ContextUtil cu = new ContextUtil(ic.getContext());
cu.addProperties(props);
break;
case SYSTEM:
OptionHelper.setSystemProperties(ic, props);
}
} | java | {
"resource": ""
} |
q176334 | AppenderAttachableImpl.addAppender | test | public void addAppender(Appender<E> newAppender) {
if (newAppender == null) {
throw new IllegalArgumentException("Null argument disallowed");
}
appenderList.addIfAbsent(newAppender);
} | java | {
"resource": ""
} |
q176335 | AppenderAttachableImpl.detachAppender | test | public boolean detachAppender(Appender<E> appender) {
if (appender == null) {
return false;
}
boolean result;
result = appenderList.remove(appender);
return result;
} | java | {
"resource": ""
} |
q176336 | AppenderAttachableImpl.detachAppender | test | public boolean detachAppender(String name) {
if (name == null) {
return false;
}
boolean removed = false;
for (Appender<E> a : appenderList) {
if (name.equals((a).getName())) {
removed = appenderList.remove(a);
break;
}
}
return removed;
} | java | {
"resource": ""
} |
q176337 | Logger.handleParentLevelChange | test | private synchronized void handleParentLevelChange(int newParentLevelInt) {
// changes in the parent levelInt affect children only if their levelInt is
// null
if (level == null) {
effectiveLevelInt = newParentLevelInt;
// propagate the parent levelInt change to this logger's children
if (childrenList != null) {
int len = childrenList.size();
for (int i = 0; i < len; i++) {
Logger child = (Logger) childrenList.get(i);
child.handleParentLevelChange(newParentLevelInt);
}
}
}
} | java | {
"resource": ""
} |
q176338 | Logger.callAppenders | test | public void callAppenders(ILoggingEvent event) {
int writes = 0;
for (Logger l = this; l != null; l = l.parent) {
writes += l.appendLoopOnAppenders(event);
if (!l.additive) {
break;
}
}
// No appenders in hierarchy
if (writes == 0) {
loggerContext.noAppenderDefinedWarning(this);
}
} | java | {
"resource": ""
} |
q176339 | Logger.detachAppender | test | public boolean detachAppender(Appender<ILoggingEvent> appender) {
if (aai == null) {
return false;
}
return aai.detachAppender(appender);
} | java | {
"resource": ""
} |
q176340 | Logger.createChildByLastNamePart | test | Logger createChildByLastNamePart(final String lastPart) {
int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart);
if (i_index != -1) {
throw new IllegalArgumentException("Child name [" + lastPart
+ " passed as parameter, may not include [" + CoreConstants.DOT + "]");
}
if (childrenList == null) {
childrenList = new CopyOnWriteArrayList<Logger>();
}
Logger childLogger;
if (this.isRootLogger()) {
childLogger = new Logger(lastPart, this, this.loggerContext);
} else {
childLogger = new Logger(name + CoreConstants.DOT + lastPart, this,
this.loggerContext);
}
childrenList.add(childLogger);
childLogger.effectiveLevelInt = this.effectiveLevelInt;
return childLogger;
} | java | {
"resource": ""
} |
q176341 | Logger.callTurboFilters | test | private FilterReply callTurboFilters(Marker marker, Level level) {
return loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this,
level, null, null, null);
} | java | {
"resource": ""
} |
q176342 | Logger.log | test | public void log(org.slf4j.event.LoggingEvent slf4jEvent) {
Level level = Level.fromLocationAwareLoggerInteger(slf4jEvent.getLevel().toInt());
filterAndLog_0_Or3Plus(FQCN, slf4jEvent.getMarker(), level, slf4jEvent.getMessage(), slf4jEvent.getArgumentArray(), slf4jEvent.getThrowable());
} | java | {
"resource": ""
} |
q176343 | DefaultSocketConnector.call | test | public Socket call() throws InterruptedException {
useDefaultsForMissingFields();
Socket socket = createSocket();
while (socket == null && !Thread.currentThread().isInterrupted()) {
Thread.sleep(delayStrategy.nextDelay());
socket = createSocket();
}
return socket;
} | java | {
"resource": ""
} |
q176344 | FileUtil.createMissingParentDirectories | test | static public boolean createMissingParentDirectories(File file) {
File parent = file.getParentFile();
if (parent == null) {
// Parent directory not specified, therefore it's a request to
// create nothing. Done! ;)
return true;
}
// File.mkdirs() creates the parent directories only if they don't
// already exist; and it's okay if they do.
parent.mkdirs();
return parent.exists();
} | java | {
"resource": ""
} |
q176345 | Level.toInteger | test | public Integer toInteger() {
switch (levelInt) {
case ALL_INT:
return ALL_INTEGER;
case TRACE_INT:
return TRACE_INTEGER;
case DEBUG_INT:
return DEBUG_INTEGER;
case INFO_INT:
return INFO_INTEGER;
case WARN_INT:
return WARN_INTEGER;
case ERROR_INT:
return ERROR_INTEGER;
case OFF_INT:
return OFF_INTEGER;
default:
throw new IllegalStateException("Level " + levelStr + ", " + levelInt
+ " is unknown.");
}
} | java | {
"resource": ""
} |
q176346 | Level.toLevel | test | public static Level toLevel(int val, Level defaultLevel) {
switch (val) {
case ALL_INT:
return ALL;
case TRACE_INT:
return TRACE;
case DEBUG_INT:
return DEBUG;
case INFO_INT:
return INFO;
case WARN_INT:
return WARN;
case ERROR_INT:
return ERROR;
case OFF_INT:
return OFF;
default:
return defaultLevel;
}
} | java | {
"resource": ""
} |
q176347 | Loader.getResourceOccurrenceCount | test | public static Set<URL> getResourceOccurrenceCount(String resource,
ClassLoader classLoader) throws IOException {
// See LBCLASSIC-159
Set<URL> urlSet = new HashSet<URL>();
Enumeration<URL> urlEnum = classLoader.getResources(resource);
while (urlEnum.hasMoreElements()) {
URL url = urlEnum.nextElement();
urlSet.add(url);
}
return urlSet;
} | java | {
"resource": ""
} |
q176348 | Loader.getResource | test | public static URL getResource(String resource, ClassLoader classLoader) {
try {
return classLoader.getResource(resource);
} catch (Throwable t) {
return null;
}
} | java | {
"resource": ""
} |
q176349 | Loader.getClassLoaderOfObject | test | public static ClassLoader getClassLoaderOfObject(Object o) {
if (o == null) {
throw new NullPointerException("Argument cannot be null");
}
return getClassLoaderOfClass(o.getClass());
} | java | {
"resource": ""
} |
q176350 | Loader.getClassLoaderAsPrivileged | test | public static ClassLoader getClassLoaderAsPrivileged(final Class<?> clazz) {
if (!HAS_GET_CLASS_LOADER_PERMISSION)
return null;
else
return AccessController.doPrivileged(
new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
return clazz.getClassLoader();
}
});
} | java | {
"resource": ""
} |
q176351 | Loader.getClassLoaderOfClass | test | public static ClassLoader getClassLoaderOfClass(final Class<?> clazz) {
ClassLoader cl = clazz.getClassLoader();
if (cl == null) {
return ClassLoader.getSystemClassLoader();
} else {
return cl;
}
} | java | {
"resource": ""
} |
q176352 | LogcatAppender.start | test | @Override
public void start() {
if ((this.encoder == null) || (this.encoder.getLayout() == null)) {
addError("No layout set for the appender named [" + name + "].");
return;
}
// tag encoder is optional but needs a layout
if (this.tagEncoder != null) {
final Layout<?> layout = this.tagEncoder.getLayout();
if (layout == null) {
addError("No tag layout set for the appender named [" + name + "].");
return;
}
// prevent stack traces from showing up in the tag
// (which could lead to very confusing error messages)
if (layout instanceof PatternLayout) {
String pattern = this.tagEncoder.getPattern();
if (!pattern.contains("%nopex")) {
this.tagEncoder.stop();
this.tagEncoder.setPattern(pattern + "%nopex");
this.tagEncoder.start();
}
PatternLayout tagLayout = (PatternLayout) layout;
tagLayout.setPostCompileProcessor(null);
}
}
super.start();
} | java | {
"resource": ""
} |
q176353 | LogcatAppender.getTag | test | protected String getTag(ILoggingEvent event) {
// format tag based on encoder layout; truncate if max length
// exceeded (only necessary for isLoggable(), which throws
// IllegalArgumentException)
String tag = (this.tagEncoder != null) ? this.tagEncoder.getLayout().doLayout(event) : event.getLoggerName();
if (checkLoggable && (tag.length() > MAX_TAG_LENGTH)) {
tag = tag.substring(0, MAX_TAG_LENGTH - 1) + "*";
}
return tag;
} | java | {
"resource": ""
} |
q176354 | PropertyAction.begin | test | public void begin(InterpretationContext ec, String localName,
Attributes attributes) {
if ("substitutionProperty".equals(localName)) {
addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead.");
}
String name = attributes.getValue(NAME_ATTRIBUTE);
String value = attributes.getValue(VALUE_ATTRIBUTE);
String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE);
Scope scope = ActionUtil.stringToScope(scopeStr);
if (checkFileAttributeSanity(attributes)) {
String file = attributes.getValue(FILE_ATTRIBUTE);
file = ec.subst(file);
try {
FileInputStream istream = new FileInputStream(file);
loadAndSetProperties(ec, istream, scope);
} catch (FileNotFoundException e) {
addError("Could not find properties file [" + file + "].");
} catch (IOException e1) {
addError("Could not read properties file [" + file + "].", e1);
}
} else if (checkResourceAttributeSanity(attributes)) {
String resource = attributes.getValue(RESOURCE_ATTRIBUTE);
resource = ec.subst(resource);
URL resourceURL = Loader.getResourceBySelfClassLoader(resource);
if (resourceURL == null) {
addError("Could not find resource [" + resource + "].");
} else {
try {
InputStream istream = resourceURL.openStream();
loadAndSetProperties(ec, istream, scope);
} catch (IOException e) {
addError("Could not read resource file [" + resource + "].", e);
}
}
} else if (checkValueNameAttributesSanity(attributes)) {
value = RegularEscapeUtil.basicEscape(value);
// now remove both leading and trailing spaces
value = value.trim();
value = ec.subst(value);
ActionUtil.setProperty(ec, name, value, scope);
} else {
addError(INVALID_ATTRIBUTES);
}
} | java | {
"resource": ""
} |
q176355 | LoggerNameUtil.getSeparatorIndexOf | test | public static int getSeparatorIndexOf(String name, int fromIndex) {
int dotIndex = name.indexOf(CoreConstants.DOT, fromIndex);
int dollarIndex = name.indexOf(CoreConstants.DOLLAR, fromIndex);
if (dotIndex == -1 && dollarIndex == -1) return -1;
if (dotIndex == -1) return dollarIndex;
if (dollarIndex == -1) return dotIndex;
return dotIndex < dollarIndex ? dotIndex : dollarIndex;
} | java | {
"resource": ""
} |
q176356 | OnMarkerEvaluator.evaluate | test | public boolean evaluate(ILoggingEvent event) throws NullPointerException,
EvaluationException {
Marker eventsMarker = event.getMarker();
if (eventsMarker == null) {
return false;
}
for (String markerStr : markerList) {
if (eventsMarker.contains(markerStr)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q176357 | SimpleSocketServer.getClientThreadName | test | protected String getClientThreadName(Socket socket) {
return String.format(Locale.US, "Logback SocketNode (client: %s)", socket.getRemoteSocketAddress());
} | java | {
"resource": ""
} |
q176358 | FileStoreUtil.areOnSameFileStore | test | static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure {
if (!a.exists()) {
throw new IllegalArgumentException("File [" + a + "] does not exist.");
}
if (!b.exists()) {
throw new IllegalArgumentException("File [" + b + "] does not exist.");
}
// Implements the following by reflection
// Path pathA = a.toPath();
// Path pathB = b.toPath();
//
// FileStore fileStoreA = Files.getFileStore(pathA);
// FileStore fileStoreB = Files.getFileStore(pathB);
//
// return fileStoreA.equals(fileStoreB);
try {
Class<?> pathClass = Class.forName(PATH_CLASS_STR);
Class<?> filesClass = Class.forName(FILES_CLASS_STR);
Method toPath = File.class.getMethod("toPath");
Method getFileStoreMethod = filesClass.getMethod("getFileStore", pathClass);
Object pathA = toPath.invoke(a);
Object pathB = toPath.invoke(b);
Object fileStoreA = getFileStoreMethod.invoke(null, pathA);
Object fileStoreB = getFileStoreMethod.invoke(null, pathB);
return fileStoreA.equals(fileStoreB);
} catch (Exception e) {
throw new RolloverFailure("Failed to check file store equality for [" + a + "] and [" + b + "]", e);
}
} | java | {
"resource": ""
} |
q176359 | SMTPAppenderBase.start | test | public void start() {
if (cbTracker == null) {
cbTracker = new CyclicBufferTracker<E>();
}
session = buildSessionFromProperties();
if (session == null) {
addError("Failed to obtain javax.mail.Session. Cannot start.");
return;
}
subjectLayout = makeSubjectLayout(subjectStr);
started = true;
} | java | {
"resource": ""
} |
q176360 | SMTPAppenderBase.append | test | protected void append(E eventObject) {
if (!checkEntryConditions()) {
return;
}
String key = discriminator.getDiscriminatingValue(eventObject);
long now = System.currentTimeMillis();
final CyclicBuffer<E> cb = cbTracker.getOrCreate(key, now);
subAppend(cb, eventObject);
try {
if (eventEvaluator.evaluate(eventObject)) {
// clone the CyclicBuffer before sending out asynchronously
CyclicBuffer<E> cbClone = new CyclicBuffer<E>(cb);
// see http://jira.qos.ch/browse/LBCLASSIC-221
cb.clear();
if (asynchronousSending) {
// perform actual sending asynchronously
SenderRunnable senderRunnable = new SenderRunnable(cbClone, eventObject);
context.getScheduledExecutorService().execute(senderRunnable);
} else {
// synchronous sending
sendBuffer(cbClone, eventObject);
}
}
} catch (EvaluationException ex) {
errorCount++;
if (errorCount < CoreConstants.MAX_ERROR_COUNT) {
addError("SMTPAppender's EventEvaluator threw an Exception-", ex);
}
}
// immediately remove the buffer if asked by the user
if (eventMarksEndOfLife(eventObject)) {
cbTracker.endOfLife(key);
}
cbTracker.removeStaleComponents(now);
if (lastTrackerStatusPrint + delayBetweenStatusMessages < now) {
addInfo("SMTPAppender [" + name + "] is tracking [" + cbTracker.getComponentCount() + "] buffers");
lastTrackerStatusPrint = now;
// quadruple 'delay' assuming less than max delay
if (delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES) {
delayBetweenStatusMessages *= 4;
}
}
} | java | {
"resource": ""
} |
q176361 | SMTPAppenderBase.sendBuffer | test | protected void sendBuffer(CyclicBuffer<E> cb, E lastEventObject) {
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize on 'cb'.
try {
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String header = layout.getFileHeader();
if (header != null) {
sbuf.append(header);
}
String presentationHeader = layout.getPresentationHeader();
if (presentationHeader != null) {
sbuf.append(presentationHeader);
}
fillBuffer(cb, sbuf);
String presentationFooter = layout.getPresentationFooter();
if (presentationFooter != null) {
sbuf.append(presentationFooter);
}
String footer = layout.getFileFooter();
if (footer != null) {
sbuf.append(footer);
}
String subjectStr = "Undefined subject";
if (subjectLayout != null) {
subjectStr = subjectLayout.doLayout(lastEventObject);
// The subject must not contain new-line characters, which cause
// an SMTP error (LOGBACK-865). Truncate the string at the first
// new-line character.
int newLinePos = (subjectStr != null) ? subjectStr.indexOf('\n') : -1;
if (newLinePos > -1) {
subjectStr = subjectStr.substring(0, newLinePos);
}
}
MimeMessage mimeMsg = new MimeMessage(session);
if (from != null) {
mimeMsg.setFrom(getAddress(from));
} else {
mimeMsg.setFrom();
}
mimeMsg.setSubject(subjectStr, charsetEncoding);
List<InternetAddress> destinationAddresses = parseAddress(lastEventObject);
if (destinationAddresses.isEmpty()) {
addInfo("Empty destination address. Aborting email transmission");
return;
}
InternetAddress[] toAddressArray = destinationAddresses.toArray(EMPTY_IA_ARRAY);
mimeMsg.setRecipients(Message.RecipientType.TO, toAddressArray);
String contentType = layout.getContentType();
if (ContentTypeUtil.isTextual(contentType)) {
part.setText(sbuf.toString(), charsetEncoding, ContentTypeUtil
.getSubType(contentType));
} else {
part.setContent(sbuf.toString(), layout.getContentType());
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
mimeMsg.setContent(mp);
updateMimeMsg(mimeMsg, cb, lastEventObject);
mimeMsg.setSentDate(new Date());
addInfo("About to send out SMTP message \"" + subjectStr + "\" to " + Arrays.toString(toAddressArray));
Transport.send(mimeMsg);
} catch (Exception e) {
addError("Error occurred while sending e-mail notification.", e);
}
} | java | {
"resource": ""
} |
q176362 | DynamicThresholdFilter.addMDCValueLevelPair | test | public void addMDCValueLevelPair(MDCValueLevelPair mdcValueLevelPair) {
if (valueLevelMap.containsKey(mdcValueLevelPair.getValue())) {
addError(mdcValueLevelPair.getValue() + " has been already set");
} else {
valueLevelMap.put(mdcValueLevelPair.getValue(), mdcValueLevelPair
.getLevel());
}
} | java | {
"resource": ""
} |
q176363 | Compiler.createConverter | test | @SuppressWarnings("unchecked")
DynamicConverter<E> createConverter(SimpleKeywordNode kn) {
String keyword = (String) kn.getValue();
String converterClassStr = (String) converterMap.get(keyword);
if (converterClassStr != null) {
try {
return (DynamicConverter<E>) OptionHelper.instantiateByClassName(
converterClassStr, DynamicConverter.class, context);
} catch (Exception e) {
addError("Failed to instantiate converter class [" + converterClassStr
+ "] for keyword ["+keyword+"]", e);
return null;
}
} else {
addError("There is no conversion class registered for conversion word ["
+ keyword + "]");
return null;
}
} | java | {
"resource": ""
} |
q176364 | Compiler.createCompositeConverter | test | @SuppressWarnings("unchecked")
CompositeConverter<E> createCompositeConverter(CompositeNode cn) {
String keyword = (String) cn.getValue();
String converterClassStr = (String) converterMap.get(keyword);
if (converterClassStr != null) {
try {
return (CompositeConverter<E>) OptionHelper.instantiateByClassName(
converterClassStr, CompositeConverter.class, context);
} catch (Exception e) {
addError("Failed to instantiate converter class [" + converterClassStr
+ "] as a composite converter for keyword ["+keyword+"]", e);
return null;
}
} else {
addError("There is no conversion class registered for composite conversion word ["
+ keyword + "]");
return null;
}
} | java | {
"resource": ""
} |
q176365 | RollingPolicyBase.determineCompressionMode | test | protected void determineCompressionMode() {
if (fileNamePatternStr.endsWith(".gz")) {
addInfo("Will use gz compression");
compressionMode = CompressionMode.GZ;
} else if (fileNamePatternStr.endsWith(".zip")) {
addInfo("Will use zip compression");
compressionMode = CompressionMode.ZIP;
} else {
addInfo("No compression will be used");
compressionMode = CompressionMode.NONE;
}
} | java | {
"resource": ""
} |
q176366 | GenericConfigurator.doConfigure | test | public final void doConfigure(URL url) throws JoranException {
InputStream in = null;
try {
informContextOfURLUsedForConfiguration(getContext(), url);
URLConnection urlConnection = url.openConnection();
// per http://jira.qos.ch/browse/LBCORE-105
// per http://jira.qos.ch/browse/LBCORE-127
urlConnection.setUseCaches(false);
// this closes the stream for us
in = urlConnection.getInputStream();
doConfigure(in, url.toExternalForm());
} catch (IOException ioe) {
String errMsg = "Could not open URL [" + url + "].";
addError(errMsg, ioe);
throw new JoranException(errMsg, ioe);
} finally {
CloseUtil.closeQuietly(in);
}
} | java | {
"resource": ""
} |
q176367 | GenericConfigurator.doConfigure | test | public final void doConfigure(File file) throws JoranException {
FileInputStream fis = null;
try {
URL url = file.toURI().toURL();
informContextOfURLUsedForConfiguration(getContext(), url);
fis = new FileInputStream(file);
// this closes the stream for us
doConfigure(fis, url.toExternalForm());
} catch (IOException ioe) {
String errMsg = "Could not open [" + file.getPath() + "].";
addError(errMsg, ioe);
throw new JoranException(errMsg, ioe);
} finally {
CloseUtil.closeQuietly(fis);
}
} | java | {
"resource": ""
} |
q176368 | GenericConfigurator.doConfigure | test | public final void doConfigure(InputStream inputStream) throws JoranException {
try {
doConfigure(new InputSource(inputStream));
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
String errMsg = "Could not close the stream";
addError(errMsg, ioe);
throw new JoranException(errMsg, ioe);
}
}
} | java | {
"resource": ""
} |
q176369 | GenericConfigurator.buildInterpreter | test | protected void buildInterpreter() {
RuleStore rs = new SimpleRuleStore(context);
addInstanceRules(rs);
this.interpreter = new Interpreter(context, rs, initialElementPath());
InterpretationContext interpretationContext = interpreter.getInterpretationContext();
interpretationContext.setContext(context);
addImplicitRules(interpreter);
addDefaultNestedComponentRegistryRules(interpretationContext.getDefaultNestedComponentRegistry());
} | java | {
"resource": ""
} |
q176370 | GenericConfigurator.doConfigure | test | private final void doConfigure(final InputSource inputSource)
throws JoranException {
long threshold = System.currentTimeMillis();
// if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) {
// informContextOfURLUsedForConfiguration(getContext(), null);
// }
SaxEventRecorder recorder = new SaxEventRecorder(context);
recorder.recordEvents(inputSource);
doConfigure(recorder.getSaxEventList());
// no exceptions a this level
StatusUtil statusUtil = new StatusUtil(context);
if (statusUtil.noXMLParsingErrorsOccurred(threshold)) {
addInfo("Registering current configuration as safe fallback point");
registerSafeConfiguration(recorder.getSaxEventList());
}
} | java | {
"resource": ""
} |
q176371 | GenericConfigurator.doConfigure | test | public void doConfigure(final List<SaxEvent> eventList)
throws JoranException {
buildInterpreter();
// disallow simultaneous configurations of the same context
synchronized (context.getConfigurationLock()) {
interpreter.getEventPlayer().play(eventList);
}
} | java | {
"resource": ""
} |
q176372 | ContextBase.getProperty | test | public String getProperty(String key) {
if (CONTEXT_NAME_KEY.equals(key))
return getName();
return (String) this.propertyMap.get(key);
} | java | {
"resource": ""
} |
q176373 | ContextBase.setName | test | public void setName(String name) throws IllegalStateException {
if (name != null && name.equals(this.name)) {
return; // idempotent naming
}
if (this.name == null
|| CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) {
this.name = name;
} else {
throw new IllegalStateException("Context has been already given a name");
}
} | java | {
"resource": ""
} |
q176374 | StatusUtil.contextHasStatusListener | test | static public boolean contextHasStatusListener(Context context) {
StatusManager sm = context.getStatusManager();
if(sm == null)
return false;
List<StatusListener> listeners = sm.getCopyOfStatusListenerList();
if(listeners == null || listeners.size() == 0)
return false;
else
return true;
} | java | {
"resource": ""
} |
q176375 | StatusUtil.timeOfLastReset | test | public long timeOfLastReset() {
List<Status> statusList = sm.getCopyOfStatusList();
if (statusList == null)
return -1;
int len = statusList.size();
for (int i = len - 1; i >= 0; i--) {
Status s = statusList.get(i);
if (CoreConstants.RESET_MSG_PREFIX.equals(s.getMessage())) {
return s.getDate();
}
}
return -1;
} | java | {
"resource": ""
} |
q176376 | HTMLLayoutBase.start | test | @Override
public void start() {
int errorCount = 0;
try {
Parser<E> p = new Parser<E>(pattern);
p.setContext(getContext());
Node t = p.parse();
this.head = p.compile(t, getEffectiveConverterMap());
ConverterUtil.startConverters(this.head);
} catch (ScanException ex) {
addError("Incorrect pattern found", ex);
errorCount++;
}
if (errorCount == 0) {
super.started = true;
}
} | java | {
"resource": ""
} |
q176377 | HTMLLayoutBase.getEffectiveConverterMap | test | public Map<String, String> getEffectiveConverterMap() {
Map<String, String> effectiveMap = new HashMap<String, String>();
// add the least specific map fist
Map<String, String> defaultMap = getDefaultConverterMap();
if (defaultMap != null) {
effectiveMap.putAll(defaultMap);
}
// contextMap is more specific than the default map
Context context = getContext();
if (context != null) {
@SuppressWarnings("unchecked")
Map<String, String> contextMap = (Map<String, String>) context
.getObject(CoreConstants.PATTERN_RULE_REGISTRY);
if (contextMap != null) {
effectiveMap.putAll(contextMap);
}
}
return effectiveMap;
} | java | {
"resource": ""
} |
q176378 | HTMLLayoutBase.getFileHeader | test | @Override
public String getFileHeader() {
StringBuilder sbuf = new StringBuilder();
sbuf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
sbuf.append(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
sbuf.append(LINE_SEPARATOR);
sbuf.append("<html>");
sbuf.append(LINE_SEPARATOR);
sbuf.append(" <head>");
sbuf.append(LINE_SEPARATOR);
sbuf.append(" <title>");
sbuf.append(title);
sbuf.append("</title>");
sbuf.append(LINE_SEPARATOR);
cssBuilder.addCss(sbuf);
sbuf.append(LINE_SEPARATOR);
sbuf.append(" </head>");
sbuf.append(LINE_SEPARATOR);
sbuf.append("<body>");
sbuf.append(LINE_SEPARATOR);
return sbuf.toString();
} | java | {
"resource": ""
} |
q176379 | HTMLLayoutBase.getFileFooter | test | @Override
public String getFileFooter() {
StringBuilder sbuf = new StringBuilder();
sbuf.append(LINE_SEPARATOR);
sbuf.append("</body></html>");
return sbuf.toString();
} | java | {
"resource": ""
} |
q176380 | AppenderAction.begin | test | @SuppressWarnings("unchecked")
public void begin(InterpretationContext ec, String localName,
Attributes attributes) throws ActionException {
// We are just beginning, reset variables
appender = null;
inError = false;
String className = attributes.getValue(CLASS_ATTRIBUTE);
if (OptionHelper.isEmpty(className)) {
addError("Missing class name for appender. Near [" + localName
+ "] line " + getLineNumber(ec));
inError = true;
return;
}
try {
addInfo("About to instantiate appender of type [" + className + "]");
warnDeprecated(className);
appender = (Appender<E>) OptionHelper.instantiateByClassName(className,
ch.qos.logback.core.Appender.class, context);
appender.setContext(context);
String appenderName = ec.subst(attributes.getValue(NAME_ATTRIBUTE));
if (OptionHelper.isEmpty(appenderName)) {
addWarn("No appender name given for appender of type " + className
+ "].");
} else {
appender.setName(appenderName);
addInfo("Naming appender as [" + appenderName + "]");
}
// The execution context contains a bag which contains the appenders
// created thus far.
HashMap<String, Appender<E>> appenderBag = (HashMap<String, Appender<E>>) ec.getObjectMap().get(
ActionConst.APPENDER_BAG);
// add the appender just created to the appender bag.
appenderBag.put(appenderName, appender);
ec.pushObject(appender);
} catch (Exception oops) {
inError = true;
addError("Could not create an Appender of type [" + className + "].",
oops);
throw new ActionException(oops);
}
} | java | {
"resource": ""
} |
q176381 | AppenderAction.end | test | public void end(InterpretationContext ec, String name) {
if (inError) {
return;
}
if (appender instanceof LifeCycle) {
((LifeCycle) appender).start();
}
Object o = ec.peekObject();
if (o != appender) {
addWarn("The object at the of the stack is not the appender named ["
+ appender.getName() + "] pushed earlier.");
} else {
ec.popObject();
}
} | java | {
"resource": ""
} |
q176382 | ConcurrentServerRunner.copyClients | test | private Collection<T> copyClients() {
clientsLock.lock();
try {
Collection<T> copy = new ArrayList<T>(clients);
return copy;
}
finally {
clientsLock.unlock();
}
} | java | {
"resource": ""
} |
q176383 | ConcurrentServerRunner.addClient | test | private void addClient(T client) {
clientsLock.lock();
try {
clients.add(client);
}
finally {
clientsLock.unlock();
}
} | java | {
"resource": ""
} |
q176384 | ConcurrentServerRunner.removeClient | test | private void removeClient(T client) {
clientsLock.lock();
try {
clients.remove(client);
}
finally {
clientsLock.unlock();
}
} | java | {
"resource": ""
} |
q176385 | LogbackMDCAdapter.getCopyOfContextMap | test | public Map<String, String> getCopyOfContextMap() {
Map<String, String> hashMap = copyOnThreadLocal.get();
if (hashMap == null) {
return null;
} else {
return new HashMap<String, String>(hashMap);
}
} | java | {
"resource": ""
} |
q176386 | StringToObjectConverter.getValueOfMethod | test | public static Method getValueOfMethod(Class<?> type) {
try {
return type.getMethod(CoreConstants.VALUE_OF, STING_CLASS_PARAMETER);
} catch (NoSuchMethodException e) {
return null;
} catch (SecurityException e) {
return null;
}
} | java | {
"resource": ""
} |
q176387 | TurboFilterList.getTurboFilterChainDecision | test | public FilterReply getTurboFilterChainDecision(final Marker marker,
final Logger logger, final Level level, final String format,
final Object[] params, final Throwable t) {
final int size = size();
// if (size == 0) {
// return FilterReply.NEUTRAL;
// }
if (size == 1) {
try {
TurboFilter tf = get(0);
return tf.decide(marker, logger, level, format, params, t);
} catch (IndexOutOfBoundsException iobe) {
return FilterReply.NEUTRAL;
}
}
Object[] tfa = toArray();
final int len = tfa.length;
for (int i = 0; i < len; i++) {
//for (TurboFilter tf : this) {
final TurboFilter tf = (TurboFilter) tfa[i];
final FilterReply r = tf.decide(marker, logger, level, format, params, t);
if (r == FilterReply.DENY || r == FilterReply.ACCEPT) {
return r;
}
}
return FilterReply.NEUTRAL;
} | java | {
"resource": ""
} |
q176388 | EnvUtil.isAndroidOS | test | static public boolean isAndroidOS() {
String osname = OptionHelper.getSystemProperty("os.name");
String root = OptionHelper.getEnv("ANDROID_ROOT");
String data = OptionHelper.getEnv("ANDROID_DATA");
return osname != null && osname.contains("Linux") &&
root != null && root.contains("/system") &&
data != null && data.contains("/data");
} | java | {
"resource": ""
} |
q176389 | StaticLoggerBinder.init | test | void init() {
try {
try {
new ContextInitializer(defaultLoggerContext).autoConfig();
} catch (JoranException je) {
Util.report("Failed to auto configure default logger context", je);
}
// logback-292
if(!StatusUtil.contextHasStatusListener(defaultLoggerContext)) {
StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
}
contextSelectorBinder.init(defaultLoggerContext, KEY);
initialized = true;
} catch (Exception t) { // see LOGBACK-1159
Util.report("Failed to instantiate [" + LoggerContext.class.getName()
+ "]", t);
}
} | java | {
"resource": ""
} |
q176390 | FileFilterUtil.filesInFolderMatchingStemRegex | test | public static File[] filesInFolderMatchingStemRegex(File file,
final String stemRegex) {
if (file == null) {
return new File[0];
}
if (!file.exists() || !file.isDirectory()) {
return new File[0];
}
return file.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches(stemRegex);
}
});
} | java | {
"resource": ""
} |
q176391 | OnPrintStreamStatusListenerBase.retrospectivePrint | test | private void retrospectivePrint() {
if(context == null)
return;
long now = System.currentTimeMillis();
StatusManager sm = context.getStatusManager();
List<Status> statusList = sm.getCopyOfStatusList();
for (Status status : statusList) {
long timestampOfStatusMesage = status.getDate();
if (isElapsedTimeLongerThanThreshold(now, timestampOfStatusMesage)) {
print(status);
}
}
} | java | {
"resource": ""
} |
q176392 | SyslogAppenderBase.facilityStringToint | test | static public int facilityStringToint(String facilityStr) {
if ("KERN".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_KERN;
} else if ("USER".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_USER;
} else if ("MAIL".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_MAIL;
} else if ("DAEMON".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_DAEMON;
} else if ("AUTH".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_AUTH;
} else if ("SYSLOG".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_SYSLOG;
} else if ("LPR".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LPR;
} else if ("NEWS".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_NEWS;
} else if ("UUCP".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_UUCP;
} else if ("CRON".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_CRON;
} else if ("AUTHPRIV".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_AUTHPRIV;
} else if ("FTP".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_FTP;
} else if ("NTP".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_NTP;
} else if ("AUDIT".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_AUDIT;
} else if ("ALERT".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_ALERT;
} else if ("CLOCK".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_CLOCK;
} else if ("LOCAL0".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL0;
} else if ("LOCAL1".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL1;
} else if ("LOCAL2".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL2;
} else if ("LOCAL3".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL3;
} else if ("LOCAL4".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL4;
} else if ("LOCAL5".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL5;
} else if ("LOCAL6".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL6;
} else if ("LOCAL7".equalsIgnoreCase(facilityStr)) {
return SyslogConstants.LOG_LOCAL7;
} else {
throw new IllegalArgumentException(facilityStr
+ " is not a valid syslog facility string");
}
} | java | {
"resource": ""
} |
q176393 | SQLiteAppender.getDatabaseFile | test | public File getDatabaseFile(String filename) {
File dbFile = null;
if (filename != null && filename.trim().length() > 0) {
dbFile = new File(filename);
}
if (dbFile == null || dbFile.isDirectory()) {
dbFile = new File(new AndroidContextUtil().getDatabasePath("logback.db"));
}
return dbFile;
} | java | {
"resource": ""
} |
q176394 | SQLiteAppender.clearExpiredLogs | test | private void clearExpiredLogs(SQLiteDatabase db) {
if (lastCheckExpired(this.maxHistory, this.lastCleanupTime)) {
this.lastCleanupTime = this.clock.currentTimeMillis();
this.getLogCleaner().performLogCleanup(db, this.maxHistory);
}
} | java | {
"resource": ""
} |
q176395 | SQLiteAppender.lastCheckExpired | test | private boolean lastCheckExpired(Duration expiry, long lastCleanupTime) {
boolean isExpired = false;
if (expiry != null && expiry.getMilliseconds() > 0) {
final long now = this.clock.currentTimeMillis();
final long timeDiff = now - lastCleanupTime;
isExpired = (lastCleanupTime <= 0) || (timeDiff >= expiry.getMilliseconds());
}
return isExpired;
} | java | {
"resource": ""
} |
q176396 | SQLiteAppender.subAppend | test | private long subAppend(ILoggingEvent event, SQLiteStatement insertStatement) throws SQLException {
bindLoggingEvent(insertStatement, event);
bindLoggingEventArguments(insertStatement, event.getArgumentArray());
// This is expensive... should we do it every time?
bindCallerData(insertStatement, event.getCallerData());
long insertId = -1;
try {
insertId = insertStatement.executeInsert();
} catch (SQLiteException e) {
addWarn("Failed to insert loggingEvent", e);
}
return insertId;
} | java | {
"resource": ""
} |
q176397 | SQLiteAppender.secondarySubAppend | test | private void secondarySubAppend(ILoggingEvent event, long eventId) throws SQLException {
Map<String, String> mergedMap = mergePropertyMaps(event);
insertProperties(mergedMap, eventId);
if (event.getThrowableProxy() != null) {
insertThrowable(event.getThrowableProxy(), eventId);
}
} | java | {
"resource": ""
} |
q176398 | SQLiteAppender.bindLoggingEvent | test | private void bindLoggingEvent(SQLiteStatement stmt, ILoggingEvent event) throws SQLException {
stmt.bindLong(TIMESTMP_INDEX, event.getTimeStamp());
stmt.bindString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage());
stmt.bindString(LOGGER_NAME_INDEX, event.getLoggerName());
stmt.bindString(LEVEL_STRING_INDEX, event.getLevel().toString());
stmt.bindString(THREAD_NAME_INDEX, event.getThreadName());
stmt.bindLong(REFERENCE_FLAG_INDEX, computeReferenceMask(event));
} | java | {
"resource": ""
} |
q176399 | SQLiteAppender.asStringTruncatedTo254 | test | private String asStringTruncatedTo254(Object o) {
String s = null;
if (o != null) {
s = o.toString();
}
if (s != null && s.length() > 254) {
s = s.substring(0, 254);
}
return s == null ? "" : s;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.