diff --git a/LICENSE b/LICENSE index 0aa8fac..0f30ea9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2024 CodeX +Copyright (c) 2026 CodeX Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index eae3345..9719ff5 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,7 @@ Now you can download(or clone repo) catcher and playground packeges to test it. In PlaygroundApp.Java you will see "import org.catcher.Hawk" that connect catcher. +## License + +This project is licensed under the **GNU Affero General Public License v3.0 (AGPL-3.0)**. +See the [LICENSE](./LICENSE) file for the full text. diff --git a/hawk-java/README.md b/hawk-java/README.md new file mode 100644 index 0000000..3144c94 --- /dev/null +++ b/hawk-java/README.md @@ -0,0 +1,69 @@ +# Hawk Java Catcher + +[Hawk](https://github.com/codex-team/hawk) allows to track Java errors in your applications. + +# Installation + +### Import through Maven Repository + +In your build.gradle file write: + +```declarative +dependencies { + implementation("so.hawk:hawkcatcher:1.0.1") + implementation("org.json:json:20250107") +} +``` + +Don't forget to import Maven Repository: + +```declarative +repositories { + mavenCentral() +} +``` + +## Usage + +### Get an Integration Token + +First of all, you should register an account on [hawk.so](https://garage.hawk.so/sign-up). + +Then create a Workspace and a Project in there. You'll get an Integration Token. + +### Initialize Catcher + +Create `Hawk` class instance when script will be ready and pass your Integration Token: + +```java +Hawk.init("PASTE_YOUR_TOKEN"); +``` + +## Manual sending + +You can send errors or other messages to the Hawk manually, for example at your catch blocks or any debug conditions. + +Use the .send(message) method for that. This method accepts the message of type Error or string as the first parameter. + +```java +Hawk.init("PASTE_YOUR_TOKEN"); + +Hawk.send("I love Hawk so much ^_^"); +``` + +## Initial config + +To config Hawk use `config` option: + +```java +Hawk.init(config -> { + config.setToken(integrationtoken) + .setContext("application", "PlaygroundApp") + .setContext("version", "1.0.0") + .setUser("id", "12345") + .setBeforeSend(payload -> { + payload.put("customField", "Custom Value"); + return payload; + }); + }); +``` \ No newline at end of file diff --git a/hawk-java/build.gradle b/hawk-java/build.gradle index 89783e0..2a99376 100644 --- a/hawk-java/build.gradle +++ b/hawk-java/build.gradle @@ -21,7 +21,7 @@ dependencies { } group = 'org' -version = '1.0-SNAPSHOT' +version = '1.0.1-SNAPSHOT' description = 'HawkCatcher' java.sourceCompatibility = JavaVersion.VERSION_1_8 diff --git a/hawk-java/src/main/java/so/hawk/catcher/BeforeSendCallback.java b/hawk-java/src/main/java/so/hawk/catcher/BeforeSendCallback.java new file mode 100644 index 0000000..9c6f2d3 --- /dev/null +++ b/hawk-java/src/main/java/so/hawk/catcher/BeforeSendCallback.java @@ -0,0 +1,17 @@ +package so.hawk.catcher; + +import org.json.JSONObject; + +/** + * Interface for beforeSend callback. + */ +@FunctionalInterface +public interface BeforeSendCallback { + /** + * Executes before sending an event. + * + * @param payload the event payload + * @return the modified payload or null to prevent sending + */ + JSONObject onBeforeSend(JSONObject payload); +} diff --git a/hawk-java/src/main/java/so/hawk/java/catcher/CustomUncaughtExceptionHandler.java b/hawk-java/src/main/java/so/hawk/catcher/CustomUncaughtExceptionHandler.java similarity index 93% rename from hawk-java/src/main/java/so/hawk/java/catcher/CustomUncaughtExceptionHandler.java rename to hawk-java/src/main/java/so/hawk/catcher/CustomUncaughtExceptionHandler.java index 81b690b..3765d74 100644 --- a/hawk-java/src/main/java/so/hawk/java/catcher/CustomUncaughtExceptionHandler.java +++ b/hawk-java/src/main/java/so/hawk/catcher/CustomUncaughtExceptionHandler.java @@ -1,4 +1,4 @@ -package so.hawk.java.catcher; +package so.hawk.catcher; /** * Custom handler for uncaught exceptions in threads. @@ -21,7 +21,7 @@ public CustomUncaughtExceptionHandler() { */ @Override public void uncaughtException(Thread t, Throwable e) { - Hawk.send((Exception) e); + Hawk.send(e); if (defaultHandler != null) { defaultHandler.uncaughtException(t, e); diff --git a/hawk-java/src/main/java/so/hawk/catcher/Hawk.java b/hawk-java/src/main/java/so/hawk/catcher/Hawk.java new file mode 100644 index 0000000..cc66e94 --- /dev/null +++ b/hawk-java/src/main/java/so/hawk/catcher/Hawk.java @@ -0,0 +1,342 @@ +package so.hawk.catcher; + +import java.util.Arrays; +import java.util.Base64; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * Manages uncaught exception handling in the application. + */ +public class Hawk { + /** + * Singleton instance of Hawk. + */ + private static volatile Hawk instance; + + /** + * Custom uncaught exception handler. + */ + private final CustomUncaughtExceptionHandler exceptionHandler; + + /** + * Authentication token used for error reporting. + */ + private final String token; + + /** + * Integration ID extracted from the token. + */ + private final String integrationId; + + /** + * Base endpoint for sending error reports. + */ + private final String endpointBase; + + /** + * String with catcher type. + */ + private static final String catcherType = "errors/java"; + + /** + * Context data provided by the user. + */ + private final JSONObject context; + + /** + * Callback to execute before sending an event. + */ + private final BeforeSendCallback beforeSend; + + /** + * User information. + */ + private final JSONObject user; + + /** + * Private constructor to initialize the Hawk instance with settings. + * + * @param settings the configuration settings + */ + private Hawk(HawkSettings settings) { + this.token = settings.getToken(); + this.integrationId = extractIntegrationIdFromToken(this.token); + this.endpointBase = String.format("https://%s.k1.hawk.so", integrationId); + this.exceptionHandler = new CustomUncaughtExceptionHandler(); + this.context = settings.getContext() != null ? settings.getContext() : new JSONObject(); + this.beforeSend = settings.getBeforeSend(); + this.user = settings.getUser(); + } + + /** + * Sends an error or a custom message to the server based on the type of input. + * + * @param messageOrException Either a custom message or an exception to send. + */ + public static void send(Object messageOrException) { + Hawk hawkInstance = getInstance(); + String payload = composeEvent(hawkInstance, messageOrException); + + if (hawkInstance.beforeSend != null) { + JSONObject jsonPayload = new JSONObject(payload); + JSONObject modifiedPayload = hawkInstance.beforeSend.onBeforeSend(jsonPayload); + if (modifiedPayload == null) { + System.out.println("Event was prevented from being sent."); + return; + } + payload = modifiedPayload.toString(); + } + + HawkHttpUtils.sendPostRequest(hawkInstance.getEndpointBase(), payload); + } + + /** + * Initializes the Hawk instance with a configuration lambda. + * + * @param configLambda the configuration lambda + */ + public static synchronized void init(HawkConfigurator configLambda) { + if (instance == null) { + HawkSettings settings = new HawkSettings("default_token"); + + configLambda.configure(settings); + + instance = new Hawk(settings); + getInstance().exceptionHandler.enable(); + } + } + + /** + * Overloaded method to initialize the Hawk instance with only the token. + * + * @param token the authentication token + */ + public static synchronized void init(String token) { + init(config -> config.setToken(token)); + } + + /** + * Retrieves the singleton Hawk instance. + * + * @return the Hawk instance + * @throws IllegalStateException if Hawk is not initialized + */ + private static Hawk getInstance() { + if (instance == null) { + throw new IllegalStateException("Hawk is not initialized. Please call Hawk.init() before using."); + } + return instance; + } + + /** + * Decodes the integration ID from a Base64-encoded token. + * + * @param token the encoded token + * @return the integration ID + */ + private static String extractIntegrationIdFromToken(String token) { + try { + String decodedJson = new String(Base64.getDecoder().decode(token)); + JSONObject json = new JSONObject(decodedJson); + return json.getString("integrationId"); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid token: Unable to decode Base64 JSON."); + } + } + + /** + * Builds the payload for the server request based on the input type. + * + * @param hawkInstance the current Hawk instance + * @param messageOrException the custom message or exception + * @return the JSON payload as a string + */ + private static String composeEvent(Hawk hawkInstance, Object messageOrException) { + JSONObject event = new JSONObject(); + event.put("token", hawkInstance.getToken()); + event.put("catcherType", catcherType); + JSONObject payloadDetails = new JSONObject(); + + if (messageOrException instanceof Exception) { + Exception e = (Exception) messageOrException; + payloadDetails.put("title", e.toString()); + + payloadDetails.putOpt("type", e.getClass().getSimpleName()); + payloadDetails.putOpt("description", e.getMessage()); + + payloadDetails.put("backtrace", getStackTraceWithSource(e)); + } else if (messageOrException instanceof String) { + String message = (String) messageOrException; + payloadDetails.put("title", message); + } else { + throw new IllegalArgumentException("Invalid argument type. Expected String or Exception."); + } + + payloadDetails.put("context", hawkInstance.context); + payloadDetails.put("user", hawkInstance.user); + payloadDetails.putOpt("release", hawkInstance.context.optString("version")); + payloadDetails.putOpt("addons", new JSONObject()); + + event.put("payload", payloadDetails); + + System.out.println("Composed event: " + event.toString(2)); + + return event.toString(); + } + + /** + * Creates a JSON array representing the stack trace (backtrace) based on the provided throwable. + * Each element in the array represents a single frame of the stack trace and includes information + * about the file, line number, method name, and a snippet of the source code. + * + * @param throwable The exception or error for which the backtrace is being generated. + * @return A JSONArray containing the backtrace details for each stack frame. + */ + private static JSONArray getStackTraceWithSource(Throwable throwable) { + JSONArray backtrace = new JSONArray(); + + for (StackTraceElement element : throwable.getStackTrace()) { + JSONObject frame = new JSONObject(); + + frame.put("file", element.getFileName() != null ? element.getFileName() : "Unknown file"); + frame.put("line", element.getLineNumber()); + frame.put("column", 0); // Column номер обычно недоступен в Java + frame.putOpt("function", element.getMethodName()); + + String sourceCode = getSourceCode(element); + if (sourceCode.equals("Source code unavailable")) { + frame.put("sourceCode", (Object) null); + } else { + JSONArray sourceCodeArray = new JSONArray(); + String[] lines = sourceCode.split("\n"); + for (String line : lines) { + String[] parts = line.split("\\|", 2); + if (parts.length == 2) { + try { + int lineNum = Integer.parseInt(parts[0].trim()); + String content = parts[1]; + JSONObject lineObj = new JSONObject(); + lineObj.put("line", lineNum); + lineObj.put("content", content); + sourceCodeArray.put(lineObj); + } catch (NumberFormatException ignored) { + } + } + } + frame.put("sourceCode", sourceCodeArray); + } + + backtrace.put(frame); + } + + return backtrace; + } + + /** + * Attempts to retrieve a snippet of the source code for the given stack trace element. + * Searches for the file in predefined directories and reads the lines around the specified line number. + * + * @param element The stack trace element for which the source code is being retrieved. + * @return A string representation of the source code snippet or "Source code unavailable" if the file cannot be found. + */ + private static String getSourceCode(StackTraceElement element) { + try { + String fileName = element.getFileName(); + if (fileName == null || fileName.isEmpty()) { + return "Source code unavailable"; + } + + List searchPaths = Arrays.asList( + "src/main/java", + "src" + ); + + for (String basePath : searchPaths) { + String fullFilePath = constructFullPath(basePath, element.getClassName(), fileName); + java.nio.file.Path fullPath = java.nio.file.Paths.get(fullFilePath); + + if (java.nio.file.Files.exists(fullPath)) { + System.out.println("File found: " + fullPath); + return readFileContent(fullPath, element.getLineNumber()); + } else { + System.out.println("File not found: " + fullPath); + } + } + + return "Source code unavailable"; + } catch (Exception e) { + System.err.println("Error while reading source code: " + e.getMessage()); + return "Source code unavailable"; + } + } + + /** + * Constructs the full path to the source file based on the base directory, class name, and file name. + * + * @param basePath The base directory where the source file is expected to be located. + * @param className The fully qualified name of the class associated with the stack trace element. + * @param fileName The name of the source file. + * @return The full path to the source file. + */ + private static String constructFullPath(String basePath, String className, String fileName) { + + String packagePath = className.replace('.', '/'); + return basePath + "/" + packagePath + "." + getExtension(fileName); + } + + /** + * Extracts the file extension from the given file name. + * + * @param fileName The name of the file. + * @return The file extension (e.g., "java") or an empty string if no extension is present. + */ + private static String getExtension(String fileName) { + if (fileName != null && fileName.contains(".")) { + return fileName.substring(fileName.lastIndexOf('.') + 1); + } + return ""; + } + + /** + * Reads the content of the source file and extracts a snippet around the specified line number. + * + * @param path The full path to the source file. + * @param lineNumber The line number around which the snippet is extracted. + * @return A formatted string containing the source code snippet with line numbers. + * @throws Exception If an error occurs while reading the file. + */ + private static String readFileContent(java.nio.file.Path path, int lineNumber) throws Exception { + List lines = java.nio.file.Files.readAllLines(path); + + int startLine = Math.max(0, lineNumber - 11); + int endLine = Math.min(lines.size(), lineNumber + 9); + + StringBuilder sourceCode = new StringBuilder(); + for (int i = startLine; i < endLine; i++) { + sourceCode.append(String.format("%4d | %s%n", i + 1, lines.get(i))); + } + + return sourceCode.toString(); + } + + /** + * Retrieves the token used by this Hawk instance. + * + * @return the authentication token + */ + private String getToken() { + return token; + } + + /** + * Retrieves the base endpoint URL for this Hawk instance. + * + * @return the endpoint base URL + */ + private String getEndpointBase() { + return endpointBase; + } +} \ No newline at end of file diff --git a/hawk-java/src/main/java/so/hawk/catcher/HawkConfigurator.java b/hawk-java/src/main/java/so/hawk/catcher/HawkConfigurator.java new file mode 100644 index 0000000..9da10a3 --- /dev/null +++ b/hawk-java/src/main/java/so/hawk/catcher/HawkConfigurator.java @@ -0,0 +1,14 @@ +package so.hawk.catcher; + +/** + * Functional interface for configuring Hawk settings. + */ +@FunctionalInterface +public interface HawkConfigurator { + /** + * Configures the given HawkSettings object. + * + * @param settings the settings to configure + */ + void configure(HawkSettings settings); +} diff --git a/hawk-java/src/main/java/so/hawk/java/catcher/HawkHttpUtils.java b/hawk-java/src/main/java/so/hawk/catcher/HawkHttpUtils.java similarity index 86% rename from hawk-java/src/main/java/so/hawk/java/catcher/HawkHttpUtils.java rename to hawk-java/src/main/java/so/hawk/catcher/HawkHttpUtils.java index 349e66d..98835ea 100644 --- a/hawk-java/src/main/java/so/hawk/java/catcher/HawkHttpUtils.java +++ b/hawk-java/src/main/java/so/hawk/catcher/HawkHttpUtils.java @@ -1,4 +1,4 @@ -package so.hawk.java.catcher; +package so.hawk.catcher; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -37,6 +37,8 @@ static void sendPostRequest(String endpointBase, String payload) { try { URL url = new URL(endpointBase); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(2000); + connection.setReadTimeout(2000); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); @@ -47,12 +49,14 @@ static void sendPostRequest(String endpointBase, String payload) { } int responseCode = connection.getResponseCode(); - if (responseCode != HttpURLConnection.HTTP_OK) { + if (responseCode == HttpURLConnection.HTTP_OK) { + System.out.println("Data sent successfully!"); + } else { System.err.println("Failed to log error. HTTP response code: " + responseCode); } - } catch (Exception ex) { System.err.println("Failed to send error: " + ex.getMessage()); + ex.printStackTrace(); } } } diff --git a/hawk-java/src/main/java/so/hawk/catcher/HawkSettings.java b/hawk-java/src/main/java/so/hawk/catcher/HawkSettings.java new file mode 100644 index 0000000..9ce6e58 --- /dev/null +++ b/hawk-java/src/main/java/so/hawk/catcher/HawkSettings.java @@ -0,0 +1,121 @@ +package so.hawk.catcher; + +import org.json.JSONObject; + +/** + * Represents the settings object for Hawk initialization. + */ +public class HawkSettings { + /** + * Authentication token for error reporting. + */ + private String token; + + /** + * Context data for additional information. + */ + private JSONObject context; + + /** + * Callback to modify payload before sending. + */ + private BeforeSendCallback beforeSend; + + /** + * User information related to errors. + */ + private JSONObject user; + + /** + * Constructor with mandatory token. + * + * @param defaultToken the default token + */ + public HawkSettings(String defaultToken) { + this.token = defaultToken; + this.context = new JSONObject(); + this.user = new JSONObject(); + } + + /** + * Sets the authentication token. + * + * @param token the authentication token + * @return the HawkSettings instance + */ + public HawkSettings setToken(String token) { + this.token = token; + return this; + } + + /** + * Sets a key-value pair in the context JSON object. + * + * @param key the key to set + * @param value the value to set + * @return the HawkSettings instance + */ + public HawkSettings setContext(String key, Object value) { + this.context.put(key, value); + return this; + } + + /** + * Sets the beforeSend callback. + * + * @param beforeSend the callback to execute before sending an event + * @return the HawkSettings instance + */ + public HawkSettings setBeforeSend(BeforeSendCallback beforeSend) { + this.beforeSend = beforeSend; + return this; + } + + /** + * Sets user information. + * + * @param key the key to set + * @param value the value to set + * @return the HawkSettings instance + */ + public HawkSettings setUser(String key, Object value) { + this.user.put(key, value); + return this; + } + + /** + * Gets the authentication token. + * + * @return the token + */ + public String getToken() { + return token; + } + + /** + * Gets the context data. + * + * @return the context + */ + public JSONObject getContext() { + return context; + } + + /** + * Gets the beforeSend callback. + * + * @return the beforeSend callback + */ + public BeforeSendCallback getBeforeSend() { + return beforeSend; + } + + /** + * Gets the user information. + * + * @return the user information + */ + public JSONObject getUser() { + return user; + } +} \ No newline at end of file diff --git a/hawk-java/src/main/java/so/hawk/java/catcher/Hawk.java b/hawk-java/src/main/java/so/hawk/java/catcher/Hawk.java deleted file mode 100644 index 1fc93fe..0000000 --- a/hawk-java/src/main/java/so/hawk/java/catcher/Hawk.java +++ /dev/null @@ -1,153 +0,0 @@ -package so.hawk.java.catcher; - -import java.util.Base64; -import org.json.JSONObject; - -/** - * Manages uncaught exception handling in the application. - */ -public class Hawk { - /** - * Singleton instance of Hawk. - */ - private static volatile Hawk instance; - - /** - * Custom uncaught exception handler. - */ - private final CustomUncaughtExceptionHandler exceptionHandler; - - /** - * Authentication token used for error reporting. - */ - private final String token; - - /** - * Integration ID extracted from the token. - */ - private final String integrationId; - - /** - * Base endpoint for sending error reports. - */ - private final String endpointBase; - - /** - * String with catcher type. - */ - private static final String catcherType = "errors/java"; - - /** - * Sends an error or a custom message to the server based on the type of input. - * - * @param messageOrException Either a custom message or an exception to send. - */ - public static void send(Object messageOrException) { - Hawk hawkInstance = getInstance(); - - String payload = composeEvent(hawkInstance, messageOrException); - - HawkHttpUtils.sendPostRequest(hawkInstance.getEndpointBase(), payload); - } - - /** - * Private constructor to initialize the Hawk instance. - * - * @param token the authentication token - */ - private Hawk(String token) { - this.token = token; - this.integrationId = extractIntegrationIdFromToken(token); - this.endpointBase = String.format("https://%s.k1.hawk.so", integrationId); - this.exceptionHandler = new CustomUncaughtExceptionHandler(); - } - - /** - * Initializes the Hawk instance with the given token. - * - * @param token the authentication token - */ - public static synchronized void init(String token) { - if (instance == null) { - instance = new Hawk(token); - } - getInstance().exceptionHandler.enable(); - } - - /** - * Retrieves the singleton Hawk instance. - * - * @return the Hawk instance - * @throws IllegalStateException if Hawk is not initialized - */ - private static Hawk getInstance() { - if (instance == null) { - throw new IllegalStateException("Hawk is not initialized. Please call Hawk.init(token) before using."); - } - return instance; - } - - - /** - * Decodes the integration ID from a Base64-encoded token. - * - * @param token the encoded token - * @return the integration ID - */ - private static String extractIntegrationIdFromToken(String token) { - try { - String decodedJson = new String(Base64.getDecoder().decode(token)); - JSONObject json = new JSONObject(decodedJson); - return json.getString("integrationId"); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid token: Unable to decode Base64 JSON."); - } - } - - /** - * Builds the payload for the server request based on the input type. - * - * @param hawkInstance the current Hawk instance - * @param messageOrException the custom message or exception - * @return the JSON payload as a string - */ - private static String composeEvent(Hawk hawkInstance, Object messageOrException) { - JSONObject event = new JSONObject(); - event.put("token", hawkInstance.getToken()); - event.put("catcherType", catcherType); - - JSONObject payloadDetails = new JSONObject(); - - if (messageOrException instanceof Exception) { - Exception e = (Exception) messageOrException; - payloadDetails.put("title", e.toString()); - } else if (messageOrException instanceof String) { - String message = (String) messageOrException; - payloadDetails.put("title", message); - } else { - throw new IllegalArgumentException("Invalid argument type. Expected String or Exception."); - } - - event.put("payload", payloadDetails); - return event.toString(); - } - - - /** - * Retrieves the token used by this Hawk instance. - * - * @return the authentication token - */ - private String getToken() { - return token; - } - - /** - * Retrieves the base endpoint URL for this Hawk instance. - * - * @return the endpoint base URL - */ - private String getEndpointBase() { - return endpointBase; - } -} diff --git a/hawk-java/src/main/java/so/hawk/java/playground/PlaygroundApp.java b/hawk-java/src/main/java/so/hawk/playground/PlaygroundApp.java similarity index 74% rename from hawk-java/src/main/java/so/hawk/java/playground/PlaygroundApp.java rename to hawk-java/src/main/java/so/hawk/playground/PlaygroundApp.java index 5cea984..64f2cdc 100644 --- a/hawk-java/src/main/java/so/hawk/java/playground/PlaygroundApp.java +++ b/hawk-java/src/main/java/so/hawk/playground/PlaygroundApp.java @@ -1,12 +1,12 @@ -package so.hawk.java.playground; +package so.hawk.playground; -import so.hawk.java.catcher.Hawk; +import so.hawk.catcher.Hawk; /** * PlaygroundApp demonstrates the use of HawkCatcher for handling uncaught exceptions. */ public class PlaygroundApp { - public static String integrationtoken = "PASTE_YOUR_TOKEN"; + public static String integrationtoken = "PASTE_YOUR_TOKEN" ; /** * The main method initializes the HawkCatcher, runs test scenarios and sends custom error. @@ -15,7 +15,16 @@ public class PlaygroundApp { */ public static void main(String[] args) { - Hawk.init(PlaygroundApp.integrationtoken); + Hawk.init(config -> { + config.setToken(integrationtoken) + .setContext("application", "PlaygroundApp") + .setContext("version", "1.0.0") + .setUser("id", "12345") + .setBeforeSend(payload -> { + payload.put("customField", "Custom Value"); + return payload; + }); + }); Hawk.send("I love Hawk so much"); diff --git a/hawk-spring/build.gradle b/hawk-spring/build.gradle new file mode 100644 index 0000000..7338924 --- /dev/null +++ b/hawk-spring/build.gradle @@ -0,0 +1,29 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.4.0' + id 'io.spring.dependency-management' version '1.1.6' +} + +group = 'so.java.hawk' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-logging' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} \ No newline at end of file diff --git a/hawk-spring/src/main/java/so/hawk/java/SpringPlaygroundApp.java b/hawk-spring/src/main/java/so/hawk/java/SpringPlaygroundApp.java new file mode 100644 index 0000000..e94523f --- /dev/null +++ b/hawk-spring/src/main/java/so/hawk/java/SpringPlaygroundApp.java @@ -0,0 +1,89 @@ +package so.hawk.java; + +import so.hawk.java.catcher.Hawk; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * SpringPlaygroundApp demonstrates the use of SpringHawk for handling uncaught exceptions in a Spring Boot application. + */ +@SpringBootApplication +public class SpringPlaygroundApp { + + /** + * The main method initializes SpringHawk and starts the Spring Boot application. + * + * @param args command line arguments + */ + public static void main(String[] args) { + Hawk.init(); + SpringApplication.run(SpringPlaygroundApp.class, args); + } +} + +/** + * Controller that defines endpoints to trigger various exceptions for testing purposes. + */ +@RestController +@RequestMapping("/test") +class ExceptionTestController { + + /** + * Triggers a RuntimeException. + * + * @return a message indicating the exception type + */ + @GetMapping("/runtime") + public String triggerRuntimeException() { + throw new RuntimeException("Test RuntimeException"); + } + + /** + * Triggers an ArrayIndexOutOfBoundsException. + * + * @return a message indicating the exception type + */ + @GetMapping("/array") + public String triggerArrayIndexOutOfBoundsException() { + int[] arr = new int[5]; + return String.valueOf(arr[10]); // This will throw ArrayIndexOutOfBoundsException + } + + /** + * Triggers a NullPointerException. + * + * @return a message indicating the exception type + */ + @GetMapping("/null") + public String triggerNullPointerException() { + String str = null; + return str.toString(); // This will throw NullPointerException + } + + /** + * Triggers an IllegalArgumentException. + * + * @return a message indicating the exception type + */ + @GetMapping("/illegal-argument") + public String triggerIllegalArgumentException() { + throw new IllegalArgumentException("Test IllegalArgumentException"); + } + + /** + * Triggers a checked Exception wrapped in a RuntimeException. + * + * @return a message indicating the exception type + */ + @GetMapping("/checked") + public String triggerCheckedException() { + try { + throw new Exception("Test Checked Exception"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/hawk-spring/src/main/java/so/hawk/java/catcher/Hawk.java b/hawk-spring/src/main/java/so/hawk/java/catcher/Hawk.java new file mode 100644 index 0000000..4914bfa --- /dev/null +++ b/hawk-spring/src/main/java/so/hawk/java/catcher/Hawk.java @@ -0,0 +1,80 @@ +package so.hawk.java.catcher; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +/** + * Singleton class for managing uncaught exceptions and integrating with Spring Boot. + */ +public class Hawk implements ApplicationContextAware { + + /** + * Singleton instance of Hawk. + * It ensures only one instance of this class exists throughout the application lifecycle. + */ + private static volatile Hawk instance; + + /** + * Spring application context, used for accessing Spring-specific beans and resources. + */ + private ApplicationContext applicationContext; + + /** + * Initializes a new Hawk instance. + * The constructor is private to enforce the singleton pattern. + */ + private Hawk() { + } + + /** + * Returns the singleton instance of Hawk. + * This ensures thread-safe lazy initialization. + * + * @return the singleton instance + */ + private static Hawk getInstance() { + if (instance == null) { + synchronized (Hawk.class) { + if (instance == null) { + instance = new Hawk(); + } + } + } + return instance; + } + + /** + * Sets the global exception handler for the application. + * Should be called during application startup to enable custom exception management. + */ + public static void init() { + getInstance(); // Singleton instance creation + } + + /** + * Sets the Spring Application Context. + * This allows Hawk to access Spring beans and integrate with Spring Boot. + * + * @param applicationContext the application context provided by Spring + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + /** + * Logs an exception with context-specific details. + * If the Spring ApplicationContext is available, it logs within the Spring environment. + * + * @param exception the exception to log + */ + public void logException(Throwable exception) { + if (applicationContext != null) { + System.out.println("Logging exception within Spring context: " + exception.getMessage()); + exception.printStackTrace(); + } else { + System.out.println("ApplicationContext is not set. Logging exception to standard output."); + exception.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/hawk-spring/src/main/java/so/hawk/java/handler/GlobalExceptionHandler.java b/hawk-spring/src/main/java/so/hawk/java/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..3c3c78a --- /dev/null +++ b/hawk-spring/src/main/java/so/hawk/java/handler/GlobalExceptionHandler.java @@ -0,0 +1,75 @@ +package so.hawk.java.handler; + +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Handles exceptions globally for a Spring Boot application. + */ +@ControllerAdvice +public class GlobalExceptionHandler { + + private final ExceptionCallback callback; + + /** + * Constructs a GlobalExceptionHandler with the given callback. + * + * @param callback the callback to invoke on exceptions + */ + public GlobalExceptionHandler(ExceptionCallback callback) { + this.callback = callback; + } + + /** + * Handles general exceptions and invokes the callback. + * + * @param exception the exception to handle + */ + @ExceptionHandler(Exception.class) + public void handleException(Exception exception) { + System.err.printf( + "Handling exception of type: %s%nMessage: %s%n", + exception.getClass().getSimpleName(), + exception.getMessage() + ); + callback.onException(exception); + } + + /** + * Interface for custom exception handling. + *

+ * Implement this interface to define how exceptions should be processed. + */ + public interface ExceptionCallback { + + /** + * Handles the given exception. + * + * @param exception the exception to handle + */ + void onException(Throwable exception); + } +} + +/** + * Default implementation of {@link GlobalExceptionHandler.ExceptionCallback} for logging exceptions. + * Logs the exception's type and message to the standard error output. + */ +@Component +class DefaultExceptionCallback implements GlobalExceptionHandler.ExceptionCallback { + + /** + * Logs the details of the caught exception. + * + * @param exception the exception to log, including its type and message + */ + @Override + public void onException(Throwable exception) { + System.err.printf( + "Caught exception of type: %s%nDetails: %s%n", + exception.getClass().getSimpleName(), + exception.getMessage() + ); + } +}