_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q165300 | ShadowPackageManager.addReceiverIfNotPresent | validation | public ActivityInfo addReceiverIfNotPresent(ComponentName componentName) {
return addComponent(
receiverFilters,
p -> p.receivers,
(p, a) -> p.receivers = a,
updateName(componentName, new ActivityInfo()),
false);
} | java | {
"resource": ""
} |
q165301 | ShadowPackageManager.addProviderIfNotPresent | validation | public ProviderInfo addProviderIfNotPresent(ComponentName componentName) {
return addComponent(
providerFilters,
p -> p.providers,
(p, a) -> p.providers = a,
updateName(componentName, new ProviderInfo()),
false);
} | java | {
"resource": ""
} |
q165302 | ShadowPackageManager.addOrUpdateActivity | validation | public void addOrUpdateActivity(ActivityInfo activityInfo) {
addComponent(
activityFilters,
p -> p.activities,
(p, a) -> p.activities = a,
new ActivityInfo(activityInfo),
true);
} | java | {
"resource": ""
} |
q165303 | ShadowPackageManager.addOrUpdateService | validation | public void addOrUpdateService(ServiceInfo serviceInfo) {
addComponent(
serviceFilters,
p -> p.services,
(p, a) -> p.services = a,
new ServiceInfo(serviceInfo),
true);
} | java | {
"resource": ""
} |
q165304 | ShadowPackageManager.addOrUpdateReceiver | validation | public void addOrUpdateReceiver(ActivityInfo receiverInfo) {
addComponent(
receiverFilters,
p -> p.receivers,
(p, a) -> p.receivers = a,
new ActivityInfo(receiverInfo),
true);
} | java | {
"resource": ""
} |
q165305 | ShadowPackageManager.addOrUpdateProvider | validation | public void addOrUpdateProvider(ProviderInfo providerInfo) {
addComponent(
providerFilters,
p -> p.providers,
(p, a) -> p.providers = a,
new ProviderInfo(providerInfo),
true);
} | java | {
"resource": ""
} |
q165306 | ShadowPackageManager.removeActivity | validation | @Nullable
public ActivityInfo removeActivity(ComponentName componentName) {
return removeComponent(
componentName, activityFilters, p -> p.activities, (p, a) -> p.activities = a);
} | java | {
"resource": ""
} |
q165307 | ShadowPackageManager.removeService | validation | @Nullable
public ServiceInfo removeService(ComponentName componentName) {
return removeComponent(
componentName, serviceFilters, p -> p.services, (p, a) -> p.services = a);
} | java | {
"resource": ""
} |
q165308 | ShadowPackageManager.removeProvider | validation | @Nullable
public ProviderInfo removeProvider(ComponentName componentName) {
return removeComponent(
componentName, providerFilters, p -> p.providers, (p, a) -> p.providers = a);
} | java | {
"resource": ""
} |
q165309 | ShadowPackageManager.removeReceiver | validation | @Nullable
public ActivityInfo removeReceiver(ComponentName componentName) {
return removeComponent(
componentName, receiverFilters, p -> p.receivers, (p, a) -> p.receivers = a);
} | java | {
"resource": ""
} |
q165310 | ShadowPackageManager.setResolveInfosForIntent | validation | @Deprecated
public void setResolveInfosForIntent(Intent intent, List<ResolveInfo> info) {
resolveInfoForIntent.remove(intent);
for (ResolveInfo resolveInfo : info) {
addResolveInfoForIntent(intent, resolveInfo);
}
} | java | {
"resource": ""
} |
q165311 | ShadowPackageManager.addResolveInfoForIntent | validation | @Deprecated
public void addResolveInfoForIntent(Intent intent, ResolveInfo info) {
info.isDefault = true;
ComponentInfo[] componentInfos =
new ComponentInfo[] {
info.activityInfo,
info.serviceInfo,
Build.VERSION.SDK_INT >= KITKAT ? info.providerInfo : null
};
for (ComponentInfo component : componentInfos) {
if (component != null && component.applicationInfo != null) {
component.applicationInfo.flags |= ApplicationInfo.FLAG_INSTALLED;
if (component.applicationInfo.processName == null) {
component.applicationInfo.processName = component.applicationInfo.packageName;
}
}
}
if (info.match == 0) {
info.match = Integer.MAX_VALUE; // make sure, that this is as good match as possible.
}
addResolveInfoForIntentNoDefaults(intent, info);
} | java | {
"resource": ""
} |
q165312 | ShadowPackageManager.addPackageInternal | validation | public void addPackageInternal(Package appPackage) {
int flags =
GET_ACTIVITIES
| GET_RECEIVERS
| GET_SERVICES
| GET_PROVIDERS
| GET_INSTRUMENTATION
| GET_INTENT_FILTERS
| GET_SIGNATURES
| GET_RESOLVED_FILTER
| GET_META_DATA
| GET_GIDS
| MATCH_DISABLED_COMPONENTS
| GET_SHARED_LIBRARY_FILES
| GET_URI_PERMISSION_PATTERNS
| GET_PERMISSIONS
| MATCH_UNINSTALLED_PACKAGES
| GET_CONFIGURATIONS
| MATCH_DISABLED_UNTIL_USED_COMPONENTS
| MATCH_DIRECT_BOOT_UNAWARE
| MATCH_DIRECT_BOOT_AWARE;
for (PermissionGroup permissionGroup : appPackage.permissionGroups) {
PermissionGroupInfo permissionGroupInfo =
PackageParser.generatePermissionGroupInfo(permissionGroup, flags);
addPermissionGroupInfo(permissionGroupInfo);
}
PackageInfo packageInfo =
reflector(_PackageParser_.class)
.generatePackageInfo(appPackage, new int[] {0}, flags, 0, 0);
packageInfo.applicationInfo.uid = Process.myUid();
packageInfo.applicationInfo.dataDir = createTempDir(packageInfo.packageName + "-dataDir");
installPackage(packageInfo);
addFilters(activityFilters, appPackage.activities);
addFilters(serviceFilters, appPackage.services);
addFilters(providerFilters, appPackage.providers);
addFilters(receiverFilters, appPackage.receivers);
} | java | {
"resource": ""
} |
q165313 | ShadowPackageManager.addIntentFilterForActivity | validation | public void addIntentFilterForActivity(ComponentName componentName, IntentFilter filter)
throws NameNotFoundException {
addIntentFilterForComponent(componentName, filter, activityFilters);
} | java | {
"resource": ""
} |
q165314 | ShadowPackageManager.addIntentFilterForService | validation | public void addIntentFilterForService(ComponentName componentName, IntentFilter filter)
throws NameNotFoundException {
addIntentFilterForComponent(componentName, filter, serviceFilters);
} | java | {
"resource": ""
} |
q165315 | ShadowPackageManager.addIntentFilterForReceiver | validation | public void addIntentFilterForReceiver(ComponentName componentName, IntentFilter filter)
throws NameNotFoundException {
addIntentFilterForComponent(componentName, filter, receiverFilters);
} | java | {
"resource": ""
} |
q165316 | ShadowPackageManager.addIntentFilterForProvider | validation | public void addIntentFilterForProvider(ComponentName componentName, IntentFilter filter)
throws NameNotFoundException {
addIntentFilterForComponent(componentName, filter, providerFilters);
} | java | {
"resource": ""
} |
q165317 | LocaleData.findParent | validation | private static int findParent(int packed_locale, final String script) {
if (hasRegion(packed_locale)) {
for (Map.Entry<String, Map<Integer, Integer>> entry : SCRIPT_PARENTS.entrySet()) {
if (script.equals(entry.getKey())) {
Map<Integer, Integer> map = entry.getValue();
Integer lookup_result = map.get(packed_locale);
if (lookup_result != null) {
return lookup_result;
}
break;
}
}
return dropRegion(packed_locale);
}
return PACKED_ROOT;
} | java | {
"resource": ""
} |
q165318 | LocaleData.findAncestors | validation | static int findAncestors(int[] out, Ref<Long> stop_list_index,
int packed_locale, final String script,
final int[] stop_list, int stop_set_length) {
int ancestor = packed_locale;
int count = 0;
do {
if (out != null) {
out[count] = ancestor;
}
count++;
for (int i = 0; i < stop_set_length; i++) {
if (stop_list[i] == ancestor) {
stop_list_index.set((long) i);
return count;
}
}
ancestor = findParent(ancestor, script);
} while (ancestor != PACKED_ROOT);
stop_list_index.set((long) -1);
return count;
} | java | {
"resource": ""
} |
q165319 | ShadowPackageParser.callParsePackage | validation | public static Package callParsePackage(Path apkFile) {
PackageParser packageParser = new PackageParser();
int flags = PackageParser.PARSE_IGNORE_PROCESSES;
try {
Package thePackage;
if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.LOLLIPOP) {
// TODO(christianw/brettchabot): workaround for NPE from probable bug in Q.
// Can be removed when upstream properly handles a null callback
// PackageParser#setMinAspectRatio(Package)
if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) {
QHelper.setCallback(packageParser);
}
thePackage = packageParser.parsePackage(apkFile.toFile(), flags);
} else { // JB -> KK
thePackage =
reflector(_PackageParser_.class, packageParser)
.parsePackage(
apkFile.toFile(), Fs.externalize(apkFile), new DisplayMetrics(), flags);
}
if (thePackage == null) {
List<LogItem> logItems = ShadowLog.getLogsForTag("PackageParser");
if (logItems.isEmpty()) {
throw new RuntimeException(
"Failed to parse package " + apkFile);
} else {
LogItem logItem = logItems.get(0);
throw new RuntimeException(
"Failed to parse package " + apkFile + ": " + logItem.msg, logItem.throwable);
}
}
return thePackage;
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165320 | LocalActivityInvoker.getIntentForActivity | validation | @Override
public Intent getIntentForActivity(Class<? extends Activity> activityClass) {
PackageManager packageManager = getTargetContext().getPackageManager();
ComponentName componentName = new ComponentName(getTargetContext(), activityClass);
Intent intent = Intent.makeMainActivity(componentName);
if (packageManager.resolveActivity(intent, 0) != null) {
return intent;
}
return Intent.makeMainActivity(new ComponentName(getContext(), activityClass));
} | java | {
"resource": ""
} |
q165321 | LoadedArsc.VerifyResTableType | validation | static boolean VerifyResTableType(ResTable_type header) {
if (header.id == 0) {
logError("RES_TABLE_TYPE_TYPE has invalid ID 0.");
return false;
}
int entry_count = dtohl(header.entryCount);
// if (entry_count > std.numeric_limits<uint16_t>.max()) {
if (entry_count > 0xffff) {
logError("RES_TABLE_TYPE_TYPE has too many entries (" + entry_count + ").");
return false;
}
// Make sure that there is enough room for the entry offsets.
int offsets_offset = dtohs(header.header.headerSize);
int entries_offset = dtohl(header.entriesStart);
int offsets_length = 4 * entry_count;
if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) {
logError("RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data.");
return false;
}
if (entries_offset > dtohl(header.header.size)) {
logError("RES_TABLE_TYPE_TYPE entry offsets extend beyond chunk.");
return false;
}
if (isTruthy(entries_offset & 0x03)) {
logError("RES_TABLE_TYPE_TYPE entries start at unaligned address.");
return false;
}
return true;
} | java | {
"resource": ""
} |
q165322 | MavenManifestFactory.findLibraries | validation | private static List<ManifestIdentifier> findLibraries(Path resDirectory) throws IOException {
List<ManifestIdentifier> libraryBaseDirs = new ArrayList<>();
if (resDirectory != null) {
Path baseDir = resDirectory.getParent();
final Properties properties = getProperties(baseDir.resolve("project.properties"));
Properties overrideProperties = getProperties(baseDir.resolve("test-project.properties"));
properties.putAll(overrideProperties);
int libRef = 1;
String lib;
while ((lib = properties.getProperty("android.library.reference." + libRef)) != null) {
Path libraryDir = baseDir.resolve(lib);
if (Files.isDirectory(libraryDir)) {
// Ignore directories without any files
Path[] libraryBaseDirFiles = Fs.listFiles(libraryDir);
if (libraryBaseDirFiles != null && libraryBaseDirFiles.length > 0) {
List<ManifestIdentifier> libraries =
findLibraries(libraryDir.resolve(Config.DEFAULT_RES_FOLDER));
libraryBaseDirs.add(
new ManifestIdentifier(
null,
libraryDir.resolve(Config.DEFAULT_MANIFEST_NAME),
libraryDir.resolve(Config.DEFAULT_RES_FOLDER),
libraryDir.resolve(Config.DEFAULT_ASSET_FOLDER),
libraries));
}
}
libRef++;
}
}
return libraryBaseDirs;
} | java | {
"resource": ""
} |
q165323 | ShadowDevicePolicyManager.getOrganizationName | validation | @Implementation(minSdk = N)
@Nullable
protected CharSequence getOrganizationName(ComponentName admin) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
enforceDeviceOwnerOrProfileOwner(admin);
} else {
enforceProfileOwner(admin);
}
return organizationName;
} | java | {
"resource": ""
} |
q165324 | ShadowDevicePolicyManager.setPermittedAccessibilityServices | validation | @Implementation(minSdk = LOLLIPOP)
protected boolean setPermittedAccessibilityServices(
ComponentName admin, List<String> packageNames) {
enforceDeviceOwnerOrProfileOwner(admin);
permittedAccessibilityServices = packageNames;
return true;
} | java | {
"resource": ""
} |
q165325 | ShadowDevicePolicyManager.setPermittedInputMethods | validation | @Implementation(minSdk = LOLLIPOP)
protected boolean setPermittedInputMethods(ComponentName admin, List<String> packageNames) {
enforceDeviceOwnerOrProfileOwner(admin);
permittedInputMethods = packageNames;
return true;
} | java | {
"resource": ""
} |
q165326 | ShadowDevicePolicyManager.activateResetToken | validation | public boolean activateResetToken(ComponentName admin) {
if (!passwordResetTokens.containsKey(admin)) {
throw new IllegalArgumentException("No token set for comopnent: " + admin);
}
return componentsWithActivatedTokens.add(admin);
} | java | {
"resource": ""
} |
q165327 | CppAssetManager2.GetResourceConfigurations | validation | public Set<ResTable_config> GetResourceConfigurations(boolean exclude_system,
boolean exclude_mipmap) {
// ATRACE_NAME("AssetManager::GetResourceConfigurations");
Set<ResTable_config> configurations = new HashSet<>();
for (final PackageGroup package_group : package_groups_) {
for (final ConfiguredPackage package_ : package_group.packages_) {
if (exclude_system && package_.loaded_package_.IsSystem()) {
continue;
}
package_.loaded_package_.CollectConfigurations(exclude_mipmap, configurations);
}
}
return configurations;
} | java | {
"resource": ""
} |
q165328 | CppAssetManager2.GetResourceLocales | validation | public Set<String> GetResourceLocales(boolean exclude_system,
boolean merge_equivalent_languages) {
ATRACE_CALL();
Set<String> locales = new HashSet<>();
for (final PackageGroup package_group : package_groups_) {
for (final ConfiguredPackage package_ : package_group.packages_) {
if (exclude_system && package_.loaded_package_.IsSystem()) {
continue;
}
package_.loaded_package_.CollectLocales(merge_equivalent_languages, locales);
}
}
return locales;
} | java | {
"resource": ""
} |
q165329 | CppAssetManager2.OpenNonAsset | validation | public Asset OpenNonAsset(final String filename,
Asset.AccessMode mode,
Ref<ApkAssetsCookie> out_cookie) {
ATRACE_CALL();
for (int i = apk_assets_.size() - 1; i >= 0; i--) {
Asset asset = apk_assets_.get(i).Open(filename, mode);
if (isTruthy(asset)) {
if (out_cookie != null) {
out_cookie.set(ApkAssetsCookie.forInt(i));
}
return asset;
}
}
if (out_cookie != null) {
out_cookie.set(K_INVALID_COOKIE);
}
return null;
} | java | {
"resource": ""
} |
q165330 | ShadowBackupManager.addAvailableRestoreSets | validation | public void addAvailableRestoreSets(long restoreToken, List<String> packages) {
serviceState.restoreData.put(restoreToken, packages);
} | java | {
"resource": ""
} |
q165331 | ShadowPausedLooper.runPaused | validation | @Override
public void runPaused(Runnable runnable) {
if (isPaused && Thread.currentThread() == realLooper.getThread()) {
// just run
runnable.run();
} else {
throw new UnsupportedOperationException();
}
} | java | {
"resource": ""
} |
q165332 | ShadowPausedLooper.executeOnLooper | validation | private void executeOnLooper(ControlRunnable runnable) {
if (Thread.currentThread() == realLooper.getThread()) {
runnable.run();
} else {
if (realLooper.equals(Looper.getMainLooper())) {
throw new UnsupportedOperationException(
"main looper can only be controlled from main thread");
}
looperExecutor.execute(runnable);
runnable.waitTillComplete();
}
} | java | {
"resource": ""
} |
q165333 | ShadowParcel.readParcelable | validation | @Implementation(maxSdk = JELLY_BEAN_MR1)
@SuppressWarnings("TypeParameterUnusedInFormals")
protected <T extends Parcelable> T readParcelable(ClassLoader loader) {
// prior to JB MR2, readParcelableCreator() is inlined here.
Parcelable.Creator<?> creator = readParcelableCreator(loader);
if (creator == null) {
return null;
}
if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
Parcelable.ClassLoaderCreator<?> classLoaderCreator =
(Parcelable.ClassLoaderCreator<?>) creator;
return (T) classLoaderCreator.createFromParcel(realObject, loader);
}
return (T) creator.createFromParcel(realObject);
} | java | {
"resource": ""
} |
q165334 | ShadowParcel.writeBlob | validation | @Implementation(minSdk = M)
protected void writeBlob(byte[] b, int offset, int len) {
if (b == null) {
realObject.writeInt(-1);
return;
}
throwsIfOutOfBounds(b.length, offset, len);
long nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr");
nativeWriteBlob(nativePtr, b, offset, len);
} | java | {
"resource": ""
} |
q165335 | ShadowParcel.nativeWriteBlob | validation | @Implementation(minSdk = LOLLIPOP)
protected static void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len) {
nativeWriteByteArray(nativePtr, b, offset, len);
} | java | {
"resource": ""
} |
q165336 | ShadowParcel.toByteArray | validation | public byte[] toByteArray() {
int oldDataPosition = dataPosition;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
// NOTE: Serializing the data array would be simpler, and serialization would actually
// preserve reference equality between entries. However, the length-encoded format here
// preserves the previous format, which some tests appear to rely on.
List<FakeEncodedItem> entries = new ArrayList<>();
// NOTE: Use readNextItem to scan so the contents can be proactively validated.
dataPosition = 0;
while (dataPosition < dataSize) {
entries.add(readNextItem(Object.class));
}
oos.writeInt(entries.size());
for (FakeEncodedItem item : entries) {
oos.writeInt(item.sizeBytes);
oos.writeObject(item.value);
}
oos.flush();
return bos.toByteArray();
} catch (IOException e) {
throw new UnreliableBehaviorError("ErrorProne unable to serialize its custom format", e);
} finally {
dataPosition = oldDataPosition;
}
} | java | {
"resource": ""
} |
q165337 | ShadowParcel.setDataPosition | validation | public void setDataPosition(int pos) {
if (pos > dataSize) {
// NOTE: Real parcel ignores this until a write occurs.
throw new UnreliableBehaviorError(pos + " greater than dataSize " + dataSize);
}
dataPosition = pos;
failNextReadIfPastEnd = false;
} | java | {
"resource": ""
} |
q165338 | ShadowParcel.checkConsistentReadAndIncrementPosition | validation | private void checkConsistentReadAndIncrementPosition(Class<?> clazz, FakeEncodedItem item) {
int endPosition = dataPosition + item.sizeBytes;
for (int i = dataPosition; i < endPosition; i++) {
FakeEncodedItem foundItemItem = i < dataSize ? data[i] : null;
if (foundItemItem != item) {
throw new UnreliableBehaviorError(
clazz,
dataPosition,
item,
String.format(
Locale.US,
"but [%s] interrupts it at position %d",
foundItemItem == null
? "uninitialized data or the end of the buffer"
: foundItemItem.value,
i));
}
}
dataPosition = Math.min(dataSize, dataPosition + item.sizeBytes);
} | java | {
"resource": ""
} |
q165339 | ShadowParcel.peek | validation | private Object peek() {
return dataPosition < dataSize && data[dataPosition] != null
? data[dataPosition].value
: null;
} | java | {
"resource": ""
} |
q165340 | ShadowParcel.readNextItem | validation | private <T> FakeEncodedItem readNextItem(Class<T> clazz) {
FakeEncodedItem item = data[dataPosition];
if (item == null) {
// While Parcel will treat these as zeros, in tests, this is almost always an error.
throw new UnreliableBehaviorError("Reading uninitialized data at position " + dataPosition);
}
checkConsistentReadAndIncrementPosition(clazz, item);
return item;
} | java | {
"resource": ""
} |
q165341 | ShadowParcel.readValue | validation | private <T> T readValue(T pastEndValue, Class<T> clazz, boolean allowNull) {
if (dataPosition >= dataSize) {
// Normally, reading past the end is permitted, and returns the default values. However,
// writing to a parcel then reading without setting the position back to 0 is an incredibly
// common error to make in tests, and should never really happen in production code, so
// this shadow will fail in this condition.
if (failNextReadIfPastEnd) {
throw new UnreliableBehaviorError(
"Did you forget to setDataPosition(0) before reading the parcel?");
}
return pastEndValue;
}
int startPosition = dataPosition;
FakeEncodedItem item = readNextItem(clazz);
if (item == null) {
return pastEndValue;
} else if (item.value == null && allowNull) {
return null;
} else if (clazz.isInstance(item.value)) {
return clazz.cast(item.value);
} else {
// Numerous existing tests rely on ShadowParcel throwing RuntimeException and catching
// them. Many of these tests are trying to test what happens when an invalid Parcel is
// provided. However, Android has no concept of an "invalid parcel" because Parcel will
// happily return garbage if you ask for it. The only runtime exceptions are thrown on
// array length mismatches, or higher-level APIs like Parcelable (which has its own safety
// checks). Tests trying to test error-handling behavior should instead craft a Parcel
// that specifically triggers a BadParcelableException.
throw new RuntimeException(
new UnreliableBehaviorError(
clazz, startPosition, item, "and it is non-portable to reinterpret it"));
}
} | java | {
"resource": ""
} |
q165342 | ShadowParcel.readZeroes | validation | private boolean readZeroes(int bytes) {
int endPosition = dataPosition + bytes;
if (endPosition > dataSize) {
return false;
}
for (int i = dataPosition; i < endPosition; i++) {
if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) {
return false;
}
}
// Note in this case we short-circuit other verification -- even if we are reading weirdly
// clobbered zeroes, they're still zeroes. Future reads might fail, though.
dataPosition = endPosition;
return true;
} | java | {
"resource": ""
} |
q165343 | ShadowParcel.readPrimitive | validation | private <T> T readPrimitive(int defaultSizeBytes, T defaultValue, Class<T> clazz) {
// Check for zeroes first, since partially-overwritten values are not an error for zeroes.
if (readZeroes(defaultSizeBytes)) {
return defaultValue;
}
return readValue(defaultValue, clazz, /* allowNull= */ false);
} | java | {
"resource": ""
} |
q165344 | ShadowParcel.writeItem | validation | private void writeItem(FakeEncodedItem item) {
int endPosition = dataPosition + item.sizeBytes;
if (endPosition > data.length) {
// Parcel grows by 3/2 of the new size.
setDataCapacityAtLeast(endPosition * 3 / 2);
}
if (endPosition > dataSize) {
failNextReadIfPastEnd = true;
dataSize = endPosition;
}
Arrays.fill(data, dataPosition, endPosition, item);
dataPosition = endPosition;
} | java | {
"resource": ""
} |
q165345 | Util.readBytes | validation | public static byte[] readBytes(InputStream is) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available())) {
copy(is, bos);
return bos.toByteArray();
}
} | java | {
"resource": ""
} |
q165346 | NativeObjRegistry.getNativeObjectId | validation | @Deprecated
public synchronized long getNativeObjectId(T o) {
checkNotNull(o);
Long nativeId = nativeObjToIdMap.inverse().get(o);
if (nativeId == null) {
nativeId = nextId;
if (debug) {
System.out.printf("NativeObjRegistry %s: register %d -> %s%n", name, nativeId, o);
}
nativeObjToIdMap.put(nativeId, o);
nextId++;
}
return nativeId;
} | java | {
"resource": ""
} |
q165347 | NativeObjRegistry.getNativeObject | validation | public synchronized T getNativeObject(long nativeId) {
T object = nativeObjToIdMap.get(nativeId);
if (object != null) {
return object;
} else {
throw new NullPointerException(
String.format(
"Could not find object with nativeId: %d. Currently registered ids: %s",
nativeId, nativeObjToIdMap.keySet()));
}
} | java | {
"resource": ""
} |
q165348 | ShadowApplication.callAttach | validation | public void callAttach(Context context) {
ReflectionHelpers.callInstanceMethod(Application.class, realApplication, "attach",
ReflectionHelpers.ClassParameter.from(Context.class, context));
} | java | {
"resource": ""
} |
q165349 | ShadowConnectivityManager.setDefaultNetworkActive | validation | public void setDefaultNetworkActive(boolean isActive) {
defaultNetworkActive = isActive;
if (defaultNetworkActive) {
for (ConnectivityManager.OnNetworkActiveListener l : onNetworkActiveListeners) {
if (l != null) {
l.onNetworkActive();
}
}
}
} | java | {
"resource": ""
} |
q165350 | ShadowSoundPool.play | validation | @Implementation(maxSdk = LOLLIPOP_MR1)
protected int play(
int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) {
playedSounds.add(new Playback(soundID, leftVolume, rightVolume, priority, loop, rate));
return 1;
} | java | {
"resource": ""
} |
q165351 | ShadowSoundPool.load | validation | @Implementation
protected int load(String path, int priority) {
int soundId = soundIds.getAndIncrement();
idToPaths.put(soundId, path);
return soundId;
} | java | {
"resource": ""
} |
q165352 | ShadowAppWidgetManager.reconstructWidgetViewAsIfPhoneWasRotated | validation | public void reconstructWidgetViewAsIfPhoneWasRotated(int appWidgetId) {
WidgetInfo widgetInfo = widgetInfos.get(appWidgetId);
widgetInfo.view = createWidgetView(widgetInfo.layoutId);
widgetInfo.lastRemoteViews.reapply(context, widgetInfo.view);
} | java | {
"resource": ""
} |
q165353 | ShadowAppWidgetManager.createWidgets | validation | public int[] createWidgets(Class<? extends AppWidgetProvider> appWidgetProviderClass, int widgetLayoutId, int howManyToCreate) {
AppWidgetProvider appWidgetProvider = ReflectionHelpers.callConstructor(appWidgetProviderClass);
int[] newWidgetIds = new int[howManyToCreate];
for (int i = 0; i < howManyToCreate; i++) {
View widgetView = createWidgetView(widgetLayoutId);
int myWidgetId = nextWidgetId++;
widgetInfos.put(myWidgetId, new WidgetInfo(widgetView, widgetLayoutId, appWidgetProvider));
newWidgetIds[i] = myWidgetId;
}
appWidgetProvider.onUpdate(context, realAppWidgetManager, newWidgetIds);
return newWidgetIds;
} | java | {
"resource": ""
} |
q165354 | ShadowMediaPlayer.invokeSeekCompleteListener | validation | public void invokeSeekCompleteListener() {
int duration = getMediaInfo().duration;
setCurrentPosition(pendingSeek > duration ? duration
: pendingSeek < 0 ? 0 : pendingSeek);
pendingSeek = -1;
if (state == STARTED) {
doStart();
}
if (seekCompleteListener == null) {
return;
}
seekCompleteListener.onSeekComplete(player);
} | java | {
"resource": ""
} |
q165355 | ShadowMediaPlayer.invokeInfoListener | validation | public void invokeInfoListener(int what, int extra) {
if (infoListener != null) {
infoListener.onInfo(player, what, extra);
}
} | java | {
"resource": ""
} |
q165356 | ShadowMediaPlayer.invokeErrorListener | validation | public void invokeErrorListener(int what, int extra) {
// Calling doStop() un-schedules the next event and
// stops normal event flow from continuing.
doStop();
state = ERROR;
boolean handled = errorListener != null
&& errorListener.onError(player, what, extra);
if (!handled) {
// The documentation isn't very clear if onCompletion is
// supposed to be called from non-playing states
// (ie, states other than STARTED or PAUSED). Testing
// revealed that onCompletion is invoked even if playback
// hasn't started or is not in progress.
invokeCompletionListener();
// Need to set this again because
// invokeCompletionListener() will set the state
// to PLAYBACK_COMPLETED
state = ERROR;
}
} | java | {
"resource": ""
} |
q165357 | ShadowDisplay.getDefaultDisplay | validation | public static Display getDefaultDisplay() {
WindowManager windowManager =
(WindowManager) RuntimeEnvironment.application.getSystemService(Context.WINDOW_SERVICE);
return windowManager.getDefaultDisplay();
} | java | {
"resource": ""
} |
q165358 | ShadowDisplay.setDensityDpi | validation | public void setDensityDpi(int densityDpi) {
if (isJB()) {
this.densityDpi = densityDpi;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.logicalDensityDpi = densityDpi);
}
} | java | {
"resource": ""
} |
q165359 | ShadowDisplay.setXdpi | validation | public void setXdpi(float xdpi) {
if (isJB()) {
this.xdpi = xdpi;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.physicalXDpi = xdpi);
}
} | java | {
"resource": ""
} |
q165360 | ShadowDisplay.setYdpi | validation | public void setYdpi(float ydpi) {
if (isJB()) {
this.ydpi = ydpi;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.physicalYDpi = ydpi);
}
} | java | {
"resource": ""
} |
q165361 | ShadowDisplay.setName | validation | public void setName(String name) {
if (isJB()) {
this.name = name;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.name = name);
}
} | java | {
"resource": ""
} |
q165362 | ShadowDisplay.setFlags | validation | public void setFlags(int flags) {
reflector(_Display_.class, realObject).setFlags(flags);
if (!isJB()) {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.flags = flags);
}
} | java | {
"resource": ""
} |
q165363 | ShadowDisplay.setWidth | validation | public void setWidth(int width) {
if (isJB()) {
this.width = width;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.appWidth = width);
}
} | java | {
"resource": ""
} |
q165364 | ShadowDisplay.setHeight | validation | public void setHeight(int height) {
if (isJB()) {
this.height = height;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.appHeight = height);
}
} | java | {
"resource": ""
} |
q165365 | ShadowDisplay.setRealWidth | validation | public void setRealWidth(int width) {
if (isJB()) {
this.realWidth = width;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.logicalWidth = width);
}
} | java | {
"resource": ""
} |
q165366 | ShadowDisplay.setRealHeight | validation | public void setRealHeight(int height) {
if (isJB()) {
this.realHeight = height;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.logicalHeight = height);
}
} | java | {
"resource": ""
} |
q165367 | ShadowDisplay.setRotation | validation | public void setRotation(int rotation) {
if (isJB()) {
this.rotation = rotation;
} else {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.rotation = rotation);
}
} | java | {
"resource": ""
} |
q165368 | ShadowDisplay.setState | validation | public void setState(int state) {
if (!isJB()) {
ShadowDisplayManager.changeDisplay(realObject.getDisplayId(),
di -> di.state = state);
}
} | java | {
"resource": ""
} |
q165369 | DefaultRequestDirector.releaseConnection | validation | protected void releaseConnection() {
// Release the connection through the ManagedConnection instead of the
// ConnectionManager directly. This lets the connection control how
// it is released.
try {
managedConn.releaseConnection();
} catch(IOException ignored) {
this.log.debug("IOException releasing connection", ignored);
}
managedConn = null;
} | java | {
"resource": ""
} |
q165370 | DefaultRequestDirector.establishRoute | validation | protected void establishRoute(HttpRoute route, HttpContext context)
throws HttpException, IOException {
HttpRouteDirector rowdy = new BasicRouteDirector();
int step;
do {
HttpRoute fact = managedConn.getRoute();
step = rowdy.nextStep(route, fact);
switch (step) {
case HttpRouteDirector.CONNECT_TARGET:
case HttpRouteDirector.CONNECT_PROXY:
managedConn.open(route, context, this.params);
break;
case HttpRouteDirector.TUNNEL_TARGET: {
boolean secure = createTunnelToTarget(route, context);
this.log.debug("Tunnel to target created.");
managedConn.tunnelTarget(secure, this.params);
} break;
case HttpRouteDirector.TUNNEL_PROXY: {
// The most simple example for this case is a proxy chain
// of two proxies, where P1 must be tunnelled to P2.
// route: Source -> P1 -> P2 -> Target (3 hops)
// fact: Source -> P1 -> Target (2 hops)
final int hop = fact.getHopCount()-1; // the hop to establish
boolean secure = createTunnelToProxy(route, hop, context);
this.log.debug("Tunnel to proxy created.");
managedConn.tunnelProxy(route.getHopTarget(hop),
secure, this.params);
} break;
case HttpRouteDirector.LAYER_PROTOCOL:
managedConn.layerProtocol(context, this.params);
break;
case HttpRouteDirector.UNREACHABLE:
throw new IllegalStateException
("Unable to establish route." +
"\nplanned = " + route +
"\ncurrent = " + fact);
case HttpRouteDirector.COMPLETE:
// do nothing
break;
default:
throw new IllegalStateException
("Unknown step indicator "+step+" from RouteDirector.");
} // switch
} while (step > HttpRouteDirector.COMPLETE);
} | java | {
"resource": ""
} |
q165371 | InstrumentingClassWriter.getCommonSuperClass | validation | @Override
protected String getCommonSuperClass(final String type1, final String type2) {
try {
ClassNode info1 = typeInfo(type1);
ClassNode info2 = typeInfo(type2);
if ((info1.access & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type2, info2, type1)) {
return type1;
}
if ((info2.access & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
}
}
return "java/lang/Object";
}
if ((info2.access & Opcodes.ACC_INTERFACE) != 0) {
if (typeImplements(type1, info1, type2)) {
return type2;
} else {
return "java/lang/Object";
}
}
String b1 = typeAncestors(type1, info1);
String b2 = typeAncestors(type2, info2);
String result = "java/lang/Object";
int end1 = b1.length();
int end2 = b2.length();
while (true) {
int start1 = b1.lastIndexOf(';', end1 - 1);
int start2 = b2.lastIndexOf(';', end2 - 1);
if (start1 != -1 && start2 != -1
&& end1 - start1 == end2 - start2) {
String p1 = b1.substring(start1 + 1, end1);
String p2 = b2.substring(start2 + 1, end2);
if (p1.equals(p2)) {
result = p1;
end1 = start1;
end2 = start2;
} else {
return result;
}
} else {
return result;
}
}
} catch (ClassNotFoundException e) {
return "java/lang/Object"; // Handle classes that may be obfuscated
}
} | java | {
"resource": ""
} |
q165372 | XmlResourceParserImpl.qualify | validation | public String qualify(String value) {
if (value == null) return null;
if (AttributeResource.isResourceReference(value)) {
return "@" + ResName.qualifyResourceName(value.trim().substring(1).replace("+", ""), packageName, "attr");
} else if (AttributeResource.isStyleReference(value)) {
return "?" + ResName.qualifyResourceName(value.trim().substring(1), packageName, "attr");
} else {
return StringResources.processStringResources(value);
}
} | java | {
"resource": ""
} |
q165373 | XmlResourceParserImpl.navigateToNextNode | validation | int navigateToNextNode(Node node)
throws XmlPullParserException {
Node nextNode = node.getNextSibling();
if (nextNode != null) {
// Move to the next siblings
return processNextNodeType(nextNode);
} else {
// Goes back to the parent
if (document.getDocumentElement().equals(node)) {
currentNode = null;
return END_DOCUMENT;
}
currentNode = node.getParentNode();
return END_TAG;
}
} | java | {
"resource": ""
} |
q165374 | XmlResourceParserImpl.isAndroidSupportedFeature | validation | private static boolean isAndroidSupportedFeature(String name) {
if (name == null) {
return false;
}
for (String feature : AVAILABLE_FEATURES) {
if (feature.equals(name)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q165375 | ResTable.add | validation | int add(
Asset asset, Asset idmapAsset, final int cookie, boolean copyData,
boolean appAsLib, boolean isSystemAsset) {
final byte[] data = asset.getBuffer(true);
if (data == NULL) {
ALOGW("Unable to get buffer of resource asset file");
return UNKNOWN_ERROR;
}
int idmapSize = 0;
Object idmapData = NULL;
if (idmapAsset != NULL) {
idmapData = idmapAsset.getBuffer(true);
if (idmapData == NULL) {
ALOGW("Unable to get buffer of idmap asset file");
return UNKNOWN_ERROR;
}
idmapSize = (int) idmapAsset.getLength();
}
return addInternal(data, (int) asset.getLength(),
idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset);
} | java | {
"resource": ""
} |
q165376 | RuntimeEnvironment.getQualifiers | validation | public static String getQualifiers(Configuration configuration, DisplayMetrics displayMetrics) {
return ConfigurationV25.resourceQualifierString(configuration, displayMetrics);
} | java | {
"resource": ""
} |
q165377 | RuntimeEnvironment.setQualifiers | validation | public static void setQualifiers(String newQualifiers) {
Configuration configuration;
DisplayMetrics displayMetrics = new DisplayMetrics();
if (newQualifiers.startsWith("+")) {
configuration = new Configuration(Resources.getSystem().getConfiguration());
displayMetrics.setTo(Resources.getSystem().getDisplayMetrics());
} else {
configuration = new Configuration();
}
Bootstrap.applyQualifiers(newQualifiers, getApiLevel(), configuration, displayMetrics);
Resources systemResources = Resources.getSystem();
systemResources.updateConfiguration(configuration, displayMetrics);
if (application != null) {
application.getResources().updateConfiguration(configuration, displayMetrics);
}
} | java | {
"resource": ""
} |
q165378 | ResourceString.buildString | validation | public static String buildString(char[] data) {
int count = 0;
for (count=0; count < data.length; count++) {
if (data[count] == 0) {
break;
}
}
return new String(data, 0, count);
} | java | {
"resource": ""
} |
q165379 | ServiceFinder.load | validation | public static <S> ServiceFinder<S> load(Class<S> service,
ClassLoader loader)
{
return new ServiceFinder<>(service, loader);
} | java | {
"resource": ""
} |
q165380 | ServiceFinder.loadInstalled | validation | public static <S> ServiceFinder<S> loadInstalled(Class<S> service) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
ClassLoader prev = null;
while (cl != null) {
prev = cl;
cl = cl.getParent();
}
return load(service, prev);
} | java | {
"resource": ""
} |
q165381 | ServiceFinder.loadFromSystemProperty | validation | public static <S> S loadFromSystemProperty(final Class<S> service) {
try {
final String className = System.getProperty(service.getName());
if (className != null) {
Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className);
return (S) c.newInstance();
}
return null;
} catch (Exception e) {
throw new Error(e);
}
} | java | {
"resource": ""
} |
q165382 | ShadowUsbManager.hasPermissionForPackage | validation | public boolean hasPermissionForPackage(UsbDevice device, String packageName) {
List<UsbDevice> usbDevices = grantedPermissions.get(packageName);
return usbDevices != null && usbDevices.contains(device);
} | java | {
"resource": ""
} |
q165383 | ShadowUsbManager.revokePermission | validation | public void revokePermission(UsbDevice device, String packageName) {
List<UsbDevice> usbDevices = grantedPermissions.get(packageName);
if (usbDevices != null) {
usbDevices.remove(device);
}
} | java | {
"resource": ""
} |
q165384 | ShadowUsbManager.addOrUpdateUsbDevice | validation | public void addOrUpdateUsbDevice(UsbDevice usbDevice, boolean hasPermission) {
Preconditions.checkNotNull(usbDevice);
Preconditions.checkNotNull(usbDevice.getDeviceName());
usbDevices.put(usbDevice.getDeviceName(), usbDevice);
if (hasPermission) {
grantPermission(usbDevice);
} else {
revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName());
}
} | java | {
"resource": ""
} |
q165385 | ShadowUsbManager.removeUsbDevice | validation | public void removeUsbDevice(UsbDevice usbDevice) {
Preconditions.checkNotNull(usbDevice);
usbDevices.remove(usbDevice.getDeviceName());
revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName());
} | java | {
"resource": ""
} |
q165386 | ShadowUsbManager.addPort | validation | public void addPort(String portId) {
if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) {
usbPorts.put(
(UsbPort) createUsbPort(realUsbManager, portId, UsbPortStatus.MODE_DUAL),
(UsbPortStatus) createUsbPortStatus(
UsbPortStatus.MODE_DUAL,
UsbPortStatus.POWER_ROLE_SINK,
UsbPortStatus.DATA_ROLE_DEVICE,
0));
return;
}
usbPorts.put(
callConstructor(UsbPort.class,
from(String.class, portId),
from(int.class, getStaticField(UsbPort.class, "MODE_DUAL"))),
(UsbPortStatus) createUsbPortStatus(
getStaticField(UsbPort.class, "MODE_DUAL"),
getStaticField(UsbPort.class, "POWER_ROLE_SINK"),
getStaticField(UsbPort.class, "DATA_ROLE_DEVICE"),
0));
} | java | {
"resource": ""
} |
q165387 | ShadowUsbManager.openAccessory | validation | @Implementation
protected ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
try {
File tmpUsbDir =
RuntimeEnvironment.getTempDirectory().createIfNotExists("usb-accessory").toFile();
return ParcelFileDescriptor.open(
new File(tmpUsbDir, "usb-accessory-file"), ParcelFileDescriptor.MODE_READ_WRITE);
} catch (FileNotFoundException error) {
throw new RuntimeException("Error shadowing openAccessory", error);
}
} | java | {
"resource": ""
} |
q165388 | ShadowDropBoxManager.addData | validation | void addData(String tag, long timestamp, byte[] data) {
entries.put(timestamp, new DropBoxManager.Entry(tag, timestamp, data, DropBoxManager.IS_TEXT));
} | java | {
"resource": ""
} |
q165389 | ShadowMediaBrowserCompat.createMediaItem | validation | public MediaItem createMediaItem(String parentId, String mediaId, String title, int flag) {
final MediaMetadataCompat metadataCompat =
new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, mediaId)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, Uri.parse(mediaId).toString())
.build();
final MediaItem mediaItem = new MediaItem(metadataCompat.getDescription(), flag);
mediaItems.put(mediaId, mediaItem);
// If this MediaItem is the child of a MediaItem that has already been created. This applies to
// all MediaItems except the root.
if (parentId != null) {
final MediaItem parentItem = mediaItems.get(parentId);
List<MediaItem> children = mediaItemChildren.get(parentItem);
if (children == null) {
children = new ArrayList<>();
mediaItemChildren.put(parentItem, children);
}
children.add(mediaItem);
}
return mediaItem;
} | java | {
"resource": ""
} |
q165390 | ReflectionHelpers.createDeepProxy | validation | public static <T> T createDeepProxy(Class<T> clazz) {
return (T)
Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[] {clazz},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (PRIMITIVE_RETURN_VALUES.containsKey(method.getReturnType().getName())) {
return PRIMITIVE_RETURN_VALUES.get(method.getReturnType().getName());
} else if (method.getReturnType().isInterface()) {
return createDeepProxy(method.getReturnType());
} else {
return null;
}
}
});
} | java | {
"resource": ""
} |
q165391 | ReflectionHelpers.getField | validation | @SuppressWarnings("unchecked")
public static <R> R getField(final Object object, final String fieldName) {
try {
return traverseClassHierarchy(object.getClass(), NoSuchFieldException.class, new InsideTraversal<R>() {
@Override
public R run(Class<?> traversalClass) throws Exception {
Field field = traversalClass.getDeclaredField(fieldName);
field.setAccessible(true);
return (R) field.get(object);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165392 | ReflectionHelpers.callInstanceMethod | validation | public static <R> R callInstanceMethod(final Object instance, final String methodName, ClassParameter<?>... classParameters) {
try {
final Class<?>[] classes = ClassParameter.getClasses(classParameters);
final Object[] values = ClassParameter.getValues(classParameters);
return traverseClassHierarchy(instance.getClass(), NoSuchMethodException.class, new InsideTraversal<R>() {
@Override
@SuppressWarnings("unchecked")
public R run(Class<?> traversalClass) throws Exception {
Method declaredMethod = traversalClass.getDeclaredMethod(methodName, classes);
declaredMethod.setAccessible(true);
return (R) declaredMethod.invoke(instance, values);
}
});
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165393 | ReflectionHelpers.callInstanceMethod | validation | public static <R> R callInstanceMethod(Class<?> cl, final Object instance, final String methodName, ClassParameter<?>... classParameters) {
try {
final Class<?>[] classes = ClassParameter.getClasses(classParameters);
final Object[] values = ClassParameter.getValues(classParameters);
Method method = cl.getDeclaredMethod(methodName, classes);
method.setAccessible(true);
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalArgumentException(method + " is static");
}
return (R) method.invoke(instance, values);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165394 | ReflectionHelpers.callStaticMethod | validation | public static <R> R callStaticMethod(
ClassLoader classLoader,
String fullyQualifiedClassName,
String methodName,
ClassParameter<?>... classParameters) {
Class<?> clazz = loadClass(classLoader, fullyQualifiedClassName);
return callStaticMethod(clazz, methodName, classParameters);
} | java | {
"resource": ""
} |
q165395 | ReflectionHelpers.callStaticMethod | validation | @SuppressWarnings("unchecked")
public static <R> R callStaticMethod(Class<?> clazz, String methodName, ClassParameter<?>... classParameters) {
try {
Class<?>[] classes = ClassParameter.getClasses(classParameters);
Object[] values = ClassParameter.getValues(classParameters);
Method method = clazz.getDeclaredMethod(methodName, classes);
method.setAccessible(true);
if (!Modifier.isStatic(method.getModifiers())) {
throw new IllegalArgumentException(method + " is not static");
}
return (R) method.invoke(null, values);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new RuntimeException(e.getTargetException());
} catch (NoSuchMethodException e) {
throw new RuntimeException("no such method " + clazz + "." + methodName, e);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165396 | ReflectionHelpers.newInstance | validation | public static <T> T newInstance(Class<T> cl) {
try {
return cl.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165397 | ReflectionHelpers.callConstructor | validation | public static <R> R callConstructor(Class<? extends R> clazz, ClassParameter<?>... classParameters) {
try {
final Class<?>[] classes = ClassParameter.getClasses(classParameters);
final Object[] values = ClassParameter.getValues(classParameters);
Constructor<? extends R> constructor = clazz.getDeclaredConstructor(classes);
constructor.setAccessible(true);
return constructor.newInstance(values);
} catch (InstantiationException e) {
throw new RuntimeException("error instantiating " + clazz.getName(), e);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof RuntimeException) {
throw (RuntimeException) e.getTargetException();
}
if (e.getTargetException() instanceof Error) {
throw (Error) e.getTargetException();
}
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q165398 | ShadowWifiRttManager.startRanging | validation | @Implementation(minSdk = P)
protected void startRanging(
RangingRequest request, Executor executor, RangingResultCallback callback) {
if (!rangingResults.isEmpty()) {
executor.execute(() -> callback.onRangingResults(this.rangingResults));
} else {
executor.execute(() -> callback.onRangingFailure(RangingResultCallback.STATUS_CODE_FAIL));
}
} | java | {
"resource": ""
} |
q165399 | ShadowFontsContract.getFontSync | validation | @Implementation
public static Typeface getFontSync(FontRequest request) {
return Typeface.create(request.getQuery(), Typeface.NORMAL);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.