Skip to content

Commit

Permalink
test(java): Add PMD static code analysis for Java files (#4183)
Browse files Browse the repository at this point in the history
  • Loading branch information
krystofwoldrich authored Oct 16, 2024
1 parent 8ae23a7 commit fe13591
Show file tree
Hide file tree
Showing 19 changed files with 142 additions and 64 deletions.
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
"test": "lerna run test",
"fix": "run-s fix:lerna fix:android",
"fix:lerna": "lerna run fix",
"fix:android": "./scripts/google-java-format.sh fix",
"fix:android": "run-s 'java:format fix' java:pmd",
"lint": "run-s lint:lerna lint:android",
"lint:lerna": "lerna run lint",
"lint:android": "./scripts/google-java-format.sh lint",
"lint:android": "run-s 'java:format lint' java:pmd",
"java:format": "./scripts/google-java-format.sh",
"java:pmd": "./scripts/pmd.sh",
"run-ios": "cd samples/react-native && yarn react-native run-ios",
"run-android": "cd samples/react-native && yarn react-native run-android",
"set-version-samples": "lerna run set-version"
Expand All @@ -23,6 +25,7 @@
"google-java-format": "^1.4.0",
"lerna": "^8.1.8",
"npm-run-all2": "^6.2.2",
"pmd-bin": "^2.5.0",
"prettier": "^2.0.5",
"react-native-version": "^4.0.0",
"replace-in-file": "^7.0.1"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class RNSentryBreadcrumb {
public final class RNSentryBreadcrumb {

private RNSentryBreadcrumb() {
throw new AssertionError("Utility class should not be instantiated");
}

@Nullable
public static String getCurrentScreenFrom(ReadableMap from) {
final @Nullable String maybeCategory =
from.hasKey("category") ? from.getString("category") : null;
if (maybeCategory == null || !maybeCategory.equals("navigation")) {
if (maybeCategory == null || !"navigation".equals(maybeCategory)) {
return null;
}

Expand All @@ -26,7 +30,7 @@ public static String getCurrentScreenFrom(ReadableMap from) {
// getString might throw if cast to string fails (data.to is not enforced by TS to be a
// string)
return maybeData.hasKey("to") ? maybeData.getString("to") : null;
} catch (Throwable exception) {
} catch (Throwable exception) { // NOPMD - We don't want to crash in any case
return null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@
import java.util.Map;
import org.jetbrains.annotations.Nullable;

public class RNSentryMapConverter {
public final class RNSentryMapConverter {
public static final String NAME = "RNSentry.MapConverter";

private static final ILogger logger = new AndroidLogger(NAME);

private RNSentryMapConverter() {
throw new AssertionError("Utility class should not be instantiated");
}

public static Object convertToWritable(@Nullable Object serialized) {
if (serialized instanceof List) {
WritableArray writable = Arguments.createArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public class RNSentryModuleImpl {
private static final ILogger logger = new AndroidLogger(NAME);
private static final BuildInfoProvider buildInfo = new BuildInfoProvider(logger);
private static final String modulesPath = "modules.json";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8"); // NOPMD - Allow using UTF-8

private final ReactApplicationContext reactApplicationContext;
private final PackageInfo packageInfo;
Expand Down Expand Up @@ -270,7 +270,7 @@ public void initNativeSdk(final ReadableMap rnOptions, Promise promise) {
if (null != ex && ex.getType().contains("JavascriptException")) {
return null;
}
} catch (Throwable ignored) {
} catch (Throwable ignored) { // NOPMD - We don't want to crash in any case
// We do nothing
}

Expand Down Expand Up @@ -356,30 +356,29 @@ public void crash() {
throw new RuntimeException("TEST - Sentry Client Crash (only works in release mode)");
}

public void addListener(String _eventType) {
public void addListener(String eventType) {
// Is must be defined otherwise the generated interface from TS won't be fulfilled
logger.log(SentryLevel.ERROR, "addListener of NativeEventEmitter can't be used on Android!");
}

public void removeListeners(double _id) {
public void removeListeners(double id) {
// Is must be defined otherwise the generated interface from TS won't be fulfilled
logger.log(
SentryLevel.ERROR, "removeListeners of NativeEventEmitter can't be used on Android!");
}

public void fetchModules(Promise promise) {
final AssetManager assets = this.getReactApplicationContext().getResources().getAssets();
try (final InputStream stream =
new BufferedInputStream(assets.open(RNSentryModuleImpl.modulesPath))) {
try (InputStream stream = new BufferedInputStream(assets.open(modulesPath))) {
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
String modulesJson = new String(buffer, RNSentryModuleImpl.UTF_8);
String modulesJson = new String(buffer, UTF_8);
promise.resolve(modulesJson);
} catch (FileNotFoundException e) {
promise.resolve(null);
} catch (Throwable e) {
} catch (Throwable e) { // NOPMD - We don't want to crash in any case
logger.log(SentryLevel.WARNING, "Fetching JS Modules failed.");
promise.resolve(null);
}
Expand Down Expand Up @@ -462,7 +461,7 @@ public void fetchNativeFrames(Promise promise) {
map.putInt("frozenFrames", frozenFrames);

promise.resolve(map);
} catch (Throwable ignored) {
} catch (Throwable ignored) { // NOPMD - We don't want to crash in any case
logger.log(SentryLevel.WARNING, "Error fetching native frames.");
promise.resolve(null);
}
Expand Down Expand Up @@ -493,7 +492,7 @@ public void captureEnvelope(String rawBytes, ReadableMap options, Promise promis
try {
InternalSentrySdk.captureEnvelope(
bytes, !options.hasKey("hardCrashed") || !options.getBoolean("hardCrashed"));
} catch (Throwable e) {
} catch (Throwable e) { // NOPMD - We don't want to crash in any case
logger.log(SentryLevel.ERROR, "Error while capturing envelope");
promise.resolve(false);
}
Expand All @@ -511,7 +510,7 @@ public void captureScreenshot(Promise promise) {

final byte[] raw = takeScreenshotOnUiThread(activity);

if (raw == null) {
if (raw == null || raw.length == 0) {
logger.log(SentryLevel.WARNING, "Screenshot is null, screen was not captured.");
promise.resolve(null);
return;
Expand Down Expand Up @@ -550,7 +549,7 @@ private static byte[] takeScreenshotOnUiThread(Activity activity) {
doneSignal.await(SCREENSHOT_TIMEOUT_SECONDS, SECONDS);
} catch (InterruptedException e) {
logger.log(SentryLevel.ERROR, "Screenshot process was interrupted.");
return null;
return new byte[0];
}

return bytesWrapper[0];
Expand Down Expand Up @@ -627,7 +626,7 @@ public void setUser(final ReadableMap userKeys, final ReadableMap userDataKeys)
}

if (userDataKeys != null) {
HashMap<String, String> userDataMap = new HashMap<>();
Map<String, String> userDataMap = new HashMap<>();
ReadableMapKeySetIterator it = userDataKeys.keySetIterator();
while (it.hasNextKey()) {
String key = it.nextKey();
Expand Down Expand Up @@ -694,7 +693,7 @@ public void setContext(final String key, final ReadableMap context) {
return;
}

final HashMap<String, Object> contextHashMap = context.toHashMap();
final Map<String, Object> contextHashMap = context.toHashMap();
scope.setContexts(key, contextHashMap);
});
}
Expand Down Expand Up @@ -726,7 +725,7 @@ public void enableNativeFramesTracking() {
frameMetricsAggregator.add(currentActivity);

logger.log(SentryLevel.INFO, "FrameMetricsAggregator installed.");
} catch (Throwable ignored) {
} catch (Throwable ignored) { // NOPMD - We don't want to crash in any case
// throws ConcurrentModification when calling addOnFrameMetricsAvailableListener
// this is a best effort since we can't reproduce it
logger.log(SentryLevel.ERROR, "Error adding Activity to frameMetricsAggregator.");
Expand Down Expand Up @@ -785,7 +784,7 @@ public WritableMap startProfiling(boolean platformProfilers) {
}

result.putBoolean("started", true);
} catch (Throwable e) {
} catch (Throwable e) { // NOPMD - We don't want to crash in any case
result.putBoolean("started", false);
result.putString("error", e.toString());
}
Expand Down Expand Up @@ -825,7 +824,7 @@ public WritableMap stopProfiling() {
androidProfile.putString("build_id", getProguardUuid());
result.putMap("androidProfile", androidProfile);
}
} catch (Throwable e) {
} catch (Throwable e) { // NOPMD - We don't want to crash in any case
result.putString("error", e.toString());
} finally {
if (output != null) {
Expand All @@ -834,7 +833,7 @@ public WritableMap stopProfiling() {
if (!wasProfileSuccessfullyDeleted) {
logger.log(SentryLevel.WARNING, "Profile not deleted from:" + output.getAbsolutePath());
}
} catch (Throwable e) {
} catch (Throwable e) { // NOPMD - We don't want to crash in any case
logger.log(SentryLevel.WARNING, "Profile not deleted from:" + output.getAbsolutePath());
}
}
Expand All @@ -848,7 +847,7 @@ public WritableMap stopProfiling() {
}
isProguardDebugMetaLoaded = true;
final @Nullable List<Properties> debugMetaList =
(new AssetsDebugMetaLoader(this.getReactApplicationContext(), logger)).loadDebugMeta();
new AssetsDebugMetaLoader(this.getReactApplicationContext(), logger).loadDebugMeta();
if (debugMetaList == null) {
return null;
}
Expand All @@ -866,7 +865,7 @@ public WritableMap stopProfiling() {
}

private String readStringFromFile(File path) throws IOException {
try (final BufferedReader br = new BufferedReader(new FileReader(path)); ) {
try (BufferedReader br = new BufferedReader(new FileReader(path)); ) {

final StringBuilder text = new StringBuilder();
String line;
Expand Down Expand Up @@ -943,7 +942,7 @@ private void setEventEnvironmentTag(SentryEvent event, String environment) {
private void addPackages(SentryEvent event, SdkVersion sdk) {
SdkVersion eventSdk = event.getSdk();
if (eventSdk != null
&& eventSdk.getName().equals("sentry.javascript.react-native")
&& "sentry.javascript.react-native".equals(eventSdk.getName())
&& sdk != null) {
List<SentryPackage> sentryPackages = sdk.getPackages();
if (sentryPackages != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void onFragmentViewCreated(
@NotNull Fragment f,
@NotNull View v,
@Nullable Bundle savedInstanceState) {
if (!("com.swmansion.rnscreens.ScreenStackFragment".equals(f.getClass().getCanonicalName()))) {
if (!"com.swmansion.rnscreens.ScreenStackFragment".equals(f.getClass().getCanonicalName())) {
logger.log(
SentryLevel.DEBUG,
"Fragment is not a ScreenStackFragment, won't listen for the first draw.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,29 @@
import org.jetbrains.annotations.TestOnly;

public final class RNSentryReplayBreadcrumbConverter extends DefaultReplayBreadcrumbConverter {
public RNSentryReplayBreadcrumbConverter() {}

@Override
public @Nullable RRWebEvent convert(final @NotNull Breadcrumb breadcrumb) {
if (breadcrumb.getCategory() == null) {
return null;
}

// Do not add Sentry Event breadcrumbs to replay
if (breadcrumb.getCategory().equals("sentry.event")
|| breadcrumb.getCategory().equals("sentry.transaction")) {
if ("sentry.event".equals(breadcrumb.getCategory())
|| "sentry.transaction".equals(breadcrumb.getCategory())) {
return null;
}
if (breadcrumb.getCategory().equals("http")) {
if ("http".equals(breadcrumb.getCategory())) {
// Drop native http breadcrumbs to avoid duplicates
return null;
}

if (breadcrumb.getCategory().equals("touch")) {
if ("touch".equals(breadcrumb.getCategory())) {
return convertTouchBreadcrumb(breadcrumb);
}
if (breadcrumb.getCategory().equals("navigation")) {
if ("navigation".equals(breadcrumb.getCategory())) {
return convertNavigationBreadcrumb(breadcrumb);
}
if (breadcrumb.getCategory().equals("xhr")) {
if ("xhr".equals(breadcrumb.getCategory())) {
return convertNetworkBreadcrumb(breadcrumb);
}

Expand All @@ -46,8 +44,7 @@ public RNSentryReplayBreadcrumbConverter() {}
// ignore native navigation breadcrumbs
if (nativeBreadcrumb instanceof RRWebBreadcrumbEvent) {
final RRWebBreadcrumbEvent rrWebBreadcrumb = (RRWebBreadcrumbEvent) nativeBreadcrumb;
if (rrWebBreadcrumb.getCategory() != null
&& rrWebBreadcrumb.getCategory().equals("navigation")) {
if ("navigation".equals(rrWebBreadcrumb.getCategory())) {
return null;
}
}
Expand All @@ -69,8 +66,7 @@ public RNSentryReplayBreadcrumbConverter() {}

rrWebBreadcrumb.setCategory("ui.tap");

rrWebBreadcrumb.setMessage(
RNSentryReplayBreadcrumbConverter.getTouchPathMessage(breadcrumb.getData("path")));
rrWebBreadcrumb.setMessage(getTouchPathMessage(breadcrumb.getData("path")));

setRRWebEventDefaultsFrom(rrWebBreadcrumb, breadcrumb);
return rrWebBreadcrumb;
Expand All @@ -83,7 +79,7 @@ public RNSentryReplayBreadcrumbConverter() {}
}

final @NotNull List path = (List) maybePath;
if (path.size() == 0) {
if (path.isEmpty()) {
return null;
}

Expand Down Expand Up @@ -145,7 +141,7 @@ public RNSentryReplayBreadcrumbConverter() {}
return null;
}

final HashMap<String, Object> data = new HashMap<>();
final Map<String, Object> data = new HashMap<>();
if (breadcrumb.getData("method") instanceof String) {
data.put("method", breadcrumb.getData("method"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;

public class ReactNativeFlipper {
public class ReactNativeFlipper { // NOPMD - Default RN Template
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void onCreate() {
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
private static void initializeFlipper( // NOPMD - Default RN Template
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
Expand All @@ -79,11 +79,11 @@ private static void initializeFlipper(
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
} catch (NoSuchMethodException e) { // NOPMD - Default RN Template
e.printStackTrace();
} catch (IllegalAccessException e) {
} catch (IllegalAccessException e) { // NOPMD - Default RN Template
e.printStackTrace();
} catch (InvocationTargetException e) {
} catch (InvocationTargetException e) { // NOPMD - Default RN Template
e.printStackTrace();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ public boolean getUseDeveloperSupport() {

@Override
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
List<ReactPackage> packages = // NOPMD - Default RN Template
new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
// TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* `newArchEnabled` property). Is ignored otherwise.
*/
@DoNotStrip
public class MainComponentsRegistry {
public class MainComponentsRegistry { // NOPMD - Default RN Template
static {
SoLoader.loadLibrary("fabricjni");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
public class MainApplicationTurboModuleManagerDelegate
extends ReactPackageTurboModuleManagerDelegate {

private static volatile boolean sIsSoLibraryLoaded;
private static volatile boolean sIsSoLibraryLoaded; // NOPMD - Default RN Template

protected MainApplicationTurboModuleManagerDelegate(
ReactApplicationContext reactApplicationContext, List<ReactPackage> packages) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;

public class ReactNativeFlipper {
public class ReactNativeFlipper { // NOPMD - Default RN Template
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
Expand Down
Loading

0 comments on commit fe13591

Please sign in to comment.