Skip to content

Commit

Permalink
[FEATURE] Implement Safe Casting in getPermissions Method (#13143)
Browse files Browse the repository at this point in the history
* [FEATURE] Implement Safe Casting in getPermissions Method

This commit addresses a potential ClassCastException issue in the getPermissions method. Previously, the method executed a type cast from Object to Map<String, Object> without checking if this cast was safe, leading to a potential risk of runtime exceptions.

Changes made:
1. Added a type check using 'instanceof' to ensure that the result from executeMethod.execute is indeed a Map<?, ?> before proceeding with the cast.
2. Iterated over the entries of the resultMap, and performed a safe cast for each key-value pair, ensuring they are of types String and Boolean, respectively.
3. In case the resultObject is not an instance of Map, the method now throws an IllegalStateException with a descriptive error message, including the unexpected object's class name.

These changes enhance the robustness and reliability of the getPermissions method by preventing unsafe type casts and providing clearer error handling for unexpected types.

* Run ./scripts/format.sh

---------

Co-authored-by: Diego Molina <[email protected]>
  • Loading branch information
manuelsblanco and diemol authored Nov 14, 2023
1 parent 3ae7ae2 commit b27523b
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions java/src/org/openqa/selenium/safari/AddHasPermissions.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package org.openqa.selenium.safari;

import com.google.auto.service.AutoService;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.openqa.selenium.Capabilities;
Expand Down Expand Up @@ -66,9 +67,21 @@ public void setPermissions(String permission, boolean value) {

@Override
public Map<String, Boolean> getPermissions() {
Map<String, Object> results =
(Map<String, Object>) executeMethod.execute(GET_PERMISSIONS, null);
return (Map<String, Boolean>) results.get("permissions");
Object resultObject = executeMethod.execute(GET_PERMISSIONS, null);

if (resultObject instanceof Map<?, ?>) {
Map<?, ?> resultMap = (Map<?, ?>) resultObject;
Map<String, Boolean> permissionMap = new HashMap<>();
for (Map.Entry<?, ?> entry : resultMap.entrySet()) {
if (entry.getKey() instanceof String && entry.getValue() instanceof Boolean) {
permissionMap.put((String) entry.getKey(), (Boolean) entry.getValue());
}
}
return permissionMap;
} else {
throw new IllegalStateException(
"Unexpected result type: " + resultObject.getClass().getName());
}
}
};
}
Expand Down

0 comments on commit b27523b

Please sign in to comment.