commit c3460912039a28380a93ff50d561f1cf7a7f231b Author: ermisw Date: Thu Jun 20 11:32:09 2024 +0200 init diff --git a/agent_loader_test/.editorconfig b/agent_loader_test/.editorconfig new file mode 100644 index 0000000..1f494b0 --- /dev/null +++ b/agent_loader_test/.editorconfig @@ -0,0 +1,17 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true +max_line_length = 80 + +[*.sh] +end_of_line = lf + +[*.java] +indent_size = 4 +max_line_length = 120 diff --git a/agent_loader_test/.gitignore b/agent_loader_test/.gitignore new file mode 100644 index 0000000..9de0e37 --- /dev/null +++ b/agent_loader_test/.gitignore @@ -0,0 +1,90 @@ +############################## +## Java +############################## +.mtj.tmp/ +*.class +*.jar +*.war +*.ear +*.nar +hs_err_pid* +replay_pid* + +############################## +## Maven +############################## +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +pom.xml.bak +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +############################## +## Gradle +############################## +bin/ +build/ +.gradle +.gradletasknamecache +gradle-app.setting +!gradle-wrapper.jar + +############################## +## IntelliJ +############################## +out/ +.idea/ +.idea_modules/ +*.iml +*.ipr +*.iws + +############################## +## Eclipse +############################## +.settings/ +bin/ +tmp/ +.metadata +.classpath +.project +*.tmp +*.bak +*.swp +*~.nib +local.properties +.loadpath +.factorypath + +############################## +## NetBeans +############################## +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +nbactions.xml +nb-configuration.xml + +############################## +## Visual Studio Code +############################## +.vscode/ +.code-workspace + +############################## +## OS X +############################## +.DS_Store + +############################## +## Miscellaneous +############################## +*.log diff --git a/agent_loader_test/config/instrument.json b/agent_loader_test/config/instrument.json new file mode 100644 index 0000000..ac3cd05 --- /dev/null +++ b/agent_loader_test/config/instrument.json @@ -0,0 +1,8 @@ +{ + "instrument":[ + { + "class": "com.javadevelopersguide.jersey.resources", + "methods":["fetchAll", "create"] + } + ] +} \ No newline at end of file diff --git a/agent_loader_test/config/instrument_test_JBOSS copy.json b/agent_loader_test/config/instrument_test_JBOSS copy.json new file mode 100644 index 0000000..ed9272e --- /dev/null +++ b/agent_loader_test/config/instrument_test_JBOSS copy.json @@ -0,0 +1,16 @@ +{ + "instrument":[ + { + "class": "org.jboss.as.quickstarts.rshelloworld.HelloWorld", + "methods":["getHelloWorldJSON"] + }, + { + "class": "org.jboss.as.quickstarts.rshelloworld.HelloWorld", + "methods":["getHelloWorldXML"] + }, + { + "class": "org.jboss.as.quickstarts.rshelloworld.HelloService", + "methods":["createHelloMessage"] + } + ] +} \ No newline at end of file diff --git a/agent_loader_test/config/instrument_test_JBOSS.json b/agent_loader_test/config/instrument_test_JBOSS.json new file mode 100644 index 0000000..4cbcc7f --- /dev/null +++ b/agent_loader_test/config/instrument_test_JBOSS.json @@ -0,0 +1,14 @@ +{ + "instrument":[ + { + "class": "org.jboss.as.quickstarts.rshelloworld.HelloService", + "methods":["createHelloMessage"], + "adviceClass":"com.example.AdviceCommandExecuter" + }, + { + "class": "org.jboss.as.quickstarts.helloworld.HelloWorldServlet", + "methods":["doGet"], + "adviceClass":"com.example.AdviceRestServlet" + } + ] +} \ No newline at end of file diff --git a/agent_loader_test/pom.xml b/agent_loader_test/pom.xml new file mode 100644 index 0000000..e647bdd --- /dev/null +++ b/agent_loader_test/pom.xml @@ -0,0 +1,246 @@ + + 4.0.0 + com.example + agent_loader_test + 1.0-SNAPSHOT + + 1.8 + 1.8 + UTF-8 + 5.6.0 + 3.0.0-M3 + 3.1.2 + 8.45.1 + 3.0.0-M5 + 0.8.4 + 3.0.0 + + 0% + 0% + 20 + 5 + + + + commons-cli + commons-cli + 1.5.0 + + + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + com.sun + tools + 1.8 + system + C:\Program Files\Java\jdk1.8.0_291\lib\tools.jar + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + + compile + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + libs/ + com.example.App + + + libs/tools-1.8.jar + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + + enforce + + + + + 3.6.3 + + + true + + + + + + maven-assembly-plugin + 3.3.0 + + + src/assembly/dep.xml + + + + + create-archive + package + + single + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + pre-unit-test + + prepare-agent + + + + post-unit-test + test + + report + + + + check-unit-test + test + + check + + + ${project.build.directory}/jacoco.exec + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + ${jacoco.unit-tests.limit.instruction-ratio} + + + BRANCH + COVEREDRATIO + ${jacoco.unit-tests.limit.branch-ratio} + + + + + CLASS + + + COMPLEXITY + TOTALCOUNT + ${jacoco.unit-tests.limit.class-complexity} + + + + + METHOD + + + COMPLEXITY + TOTALCOUNT + ${jacoco.unit-tests.limit.method-complexity} + + + + + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + + + \ No newline at end of file diff --git a/agent_loader_test/src/assembly/dep.xml b/agent_loader_test/src/assembly/dep.xml new file mode 100644 index 0000000..5dac58e --- /dev/null +++ b/agent_loader_test/src/assembly/dep.xml @@ -0,0 +1,43 @@ + + bin + + zip + + + + ${project.basedir} + / + + README* + LICENSE* + NOTICE* + + + + ${project.build.directory} + / + + *.jar + + + + ${project.basedir}/config + / + + *.json + + + + C:\Users\wiegee\Documents\NetBeansProjects\JavaAgentTest\agent_test\target + libs + + agent_test-1.0-SNAPSHOT.jar + + + + ${project.build.directory}/libs + libs + + + \ No newline at end of file diff --git a/agent_loader_test/src/main/java/com/example/App.java b/agent_loader_test/src/main/java/com/example/App.java new file mode 100644 index 0000000..ca25c89 --- /dev/null +++ b/agent_loader_test/src/main/java/com/example/App.java @@ -0,0 +1,77 @@ +package com.example; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +/** + * Hello world! + */ +public final class App { + private App() { + } + + /** + * Says hello to the world. + * + * @param args The arguments of the program. + * @throws ParseException + */ + public static void main(String[] args) throws ParseException { + Options options = new Options(); + Option processId = Option.builder("p") + .longOpt("processId") + .required(true) + .hasArg() + .desc("process id java agent is attached to") + .build(); + + Option configFile = Option.builder("c") + .longOpt("configFile") + .required(true) + .hasArg() + .desc("config File pfad") + .build(); + + options.addOption(processId); + options.addOption(configFile); + CommandLineParser parser = new DefaultParser(); + CommandLine cmd = parser.parse(options, args); + + JSONParser jsonParser = new JSONParser(); + JSONObject jsonparams=null; + // cmd.getOptionValue("processId"); + try (FileReader reader = new FileReader(cmd.getOptionValue("configFile"))) { + jsonparams = (JSONObject) jsonParser.parse(reader); + // JSONObject instrumentation = (JSONObject) ((JSONArray) jsonparams.get("instrument")).get(0); + + // for (int i = 0; i < instrumentation.size(); i++) { + + // } + + MyJavaAgentLoader.loadAgent(cmd.getOptionValue("processId"), jsonparams.toString()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (org.json.simple.parser.ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + + + } +} diff --git a/agent_loader_test/src/main/java/com/example/MyJavaAgentLoader.java b/agent_loader_test/src/main/java/com/example/MyJavaAgentLoader.java new file mode 100644 index 0000000..93d3b4e --- /dev/null +++ b/agent_loader_test/src/main/java/com/example/MyJavaAgentLoader.java @@ -0,0 +1,33 @@ +package com.example; + +import java.io.File; +import java.lang.management.ManagementFactory; + +import com.sun.tools.attach.VirtualMachine; + +public class MyJavaAgentLoader { + + //static final Logger logger = LoggerFactory.getLogger(MyJavaAgentLoader.class); + + //private static final String jarFilePath = "C:\\Users\\wiegee\\Documents\\NetBeansProjects\\JavaAgentTest\\agent_test\\target\\agent_test-1.0-SNAPSHOT.jar"; + private static final String jarFilePath = new File("libs\\agent_test-1.0-SNAPSHOT.jar").getAbsolutePath(); + + public static void loadAgent(String processId, String jsonparams) { + + String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); + int p = nameOfRunningVM.indexOf('@'); + //String pid = nameOfRunningVM.substring(0, p); + + try { + System.out.println("test123"); + VirtualMachine vm = VirtualMachine.attach(processId); + + vm.loadAgent(jarFilePath, jsonparams); + + vm.detach(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/agent_loader_test/src/test/java/com/example/AppTest.java b/agent_loader_test/src/test/java/com/example/AppTest.java new file mode 100644 index 0000000..339ebcd --- /dev/null +++ b/agent_loader_test/src/test/java/com/example/AppTest.java @@ -0,0 +1,18 @@ +package com.example; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Unit test for simple App. + */ +class AppTest { + /** + * Rigorous Test. + */ + @Test + void testApp() { + assertEquals(1, 1); + } +} diff --git a/agent_test/.gitignore b/agent_test/.gitignore new file mode 100644 index 0000000..9de0e37 --- /dev/null +++ b/agent_test/.gitignore @@ -0,0 +1,90 @@ +############################## +## Java +############################## +.mtj.tmp/ +*.class +*.jar +*.war +*.ear +*.nar +hs_err_pid* +replay_pid* + +############################## +## Maven +############################## +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +pom.xml.bak +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +############################## +## Gradle +############################## +bin/ +build/ +.gradle +.gradletasknamecache +gradle-app.setting +!gradle-wrapper.jar + +############################## +## IntelliJ +############################## +out/ +.idea/ +.idea_modules/ +*.iml +*.ipr +*.iws + +############################## +## Eclipse +############################## +.settings/ +bin/ +tmp/ +.metadata +.classpath +.project +*.tmp +*.bak +*.swp +*~.nib +local.properties +.loadpath +.factorypath + +############################## +## NetBeans +############################## +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +nbactions.xml +nb-configuration.xml + +############################## +## Visual Studio Code +############################## +.vscode/ +.code-workspace + +############################## +## OS X +############################## +.DS_Store + +############################## +## Miscellaneous +############################## +*.log diff --git a/agent_test/pom.xml b/agent_test/pom.xml new file mode 100644 index 0000000..2275c53 --- /dev/null +++ b/agent_test/pom.xml @@ -0,0 +1,128 @@ + + + + 4.0.0 + + com.example + agent_test + 1.0-SNAPSHOT + + agent_test + + http://www.example.com + + + UTF-8 + 1.8 + 1.8 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + com.adobe + adobe-wkf + 1.0 + system + C:\Users\wiegee\Documents\adobe-AEMForms-libs\adobe-wkf.jar + + + com.adobe + adobe-dscf-client + 1.0 + system + C:\Users\wiegee\Documents\adobe-AEMForms-libs\adobe-dscf-client.jar + + + com.adobe + adobe-dscf + 1.0 + system + C:\Users\wiegee\Documents\adobe-AEMForms-libs\adobe-dscf.jar + + + junit + junit + 4.11 + test + + + net.bytebuddy + byte-buddy + 1.11.6 + + + com.dynatrace.oneagent.sdk.java + oneagent-sdk + 1.9.0 + compile + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + org.apache.httpcomponents + httpcore + 4.4.16 + + + org.apache.httpcomponents + httpasyncclient + 4.1.5 + + + org.apache.httpcomponents.client5 + httpclient5 + 5.3.1 + + + com.google.code.gson + gson + 2.10.1 + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.0 + + + package + + shade + + + + + + com.example.Agent + com.example.Agent + com.example.Agent + true + true + + + + + + + + + + + \ No newline at end of file diff --git a/agent_test/src/main/java/com/example/AdviceCommandExecuter.java b/agent_test/src/main/java/com/example/AdviceCommandExecuter.java new file mode 100644 index 0000000..0ad1e7d --- /dev/null +++ b/agent_test/src/main/java/com/example/AdviceCommandExecuter.java @@ -0,0 +1,160 @@ +package com.example; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +//import java.io.Console; +import java.util.UUID; + +import com.adobe.workflow.engine.PEInvokeProcessCommand; +import com.dynatrace.oneagent.sdk.OneAgentSDKFactory; +import com.dynatrace.oneagent.sdk.api.OneAgentSDK; +import net.bytebuddy.asm.*; +import net.bytebuddy.asm.Advice.FieldValue; +import net.bytebuddy.implementation.bytecode.assign.Assigner.Typing; + +public class AdviceCommandExecuter { + // @Advice.AllArguments Object[] args, + @Advice.OnMethodEnter + static AdviceResponse invokeBeforeEnterMethod(@Advice.AllArguments Object[] args, + @Advice.Origin String method, @FieldValue(value = "m_command", typing = Typing.DYNAMIC) Object m_command) { + + String uniqueID = UUID.randomUUID().toString(); + long currentTimeStamp = System.currentTimeMillis(); + String workflow = ""; + + Date date = new Date(currentTimeStamp); + DateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'"); + String dateTxT = f.format(date); + + try { + + if (m_command != null) { + workflow = ((PEInvokeProcessCommand) m_command).getInvocationInfo().getProcessTypeId(); + } + + workflow = workflow.replace(" ", "_"); + + System.out.println("Printing Methods args: "); + for (Object obj : args) { + System.out.println(obj.toString()); + } + + // Timestamp Start + + OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); + oneAgentSdk.addCustomRequestAttribute("method_start_time", currentTimeStamp); + + String thread_name = Thread.currentThread().getName().replace(" ", "_"); + oneAgentSdk.addCustomRequestAttribute("thread_name", thread_name); + + StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + StringBuilder m_starttime = new StringBuilder("nttdata.aemforms.workflow.starttime"); + + if (uniqueID != null) { + m_duration.append(",uuid="); + m_duration.append(uniqueID); + m_starttime.append(",uuid="); + m_starttime.append(uniqueID); + } + if (thread_name != null) { + m_duration.append(",threadname="); + m_duration.append(thread_name); + m_starttime.append(",threadname="); + m_starttime.append(thread_name); + } + if (method != null) { + m_duration.append(",method="); + m_duration.append(method.replace(" ", "_")); + m_starttime.append(",method="); + m_starttime.append(method.replace(" ", "_")); + } + if (dateTxT != null) { + m_duration.append(",startdate="); + m_duration.append(dateTxT); + m_starttime.append(",startdate="); + m_starttime.append(dateTxT); + } + if (workflow != null) { + m_duration.append(",workflow="); + m_duration.append(workflow); + m_starttime.append(",workflow="); + m_starttime.append(workflow); + } + m_duration.append(" 0"); + m_starttime.append(" "); + m_starttime.append(currentTimeStamp); + + System.out.println("Metric duration: " + m_duration.toString()); + System.out.println("Metric starttime: " + m_starttime.toString()); + + OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + OneAgentMetricWriter.getInstance().writeMetric(m_starttime.toString()); + + } catch (Exception ex) { + System.out.println("Exception occured during call Oneagent SDK" + + ex.getMessage()); + } + + return new AdviceResponse(currentTimeStamp, uniqueID, workflow, dateTxT); + + } + + @Advice.OnMethodExit(onThrowable=Throwable.class) + static void invokeAfterExitMethod( + @Advice.Origin String method, + @Advice.Enter AdviceResponse adviceResponse) { + + if (adviceResponse != null) { + long currentTimeStamp = System.currentTimeMillis(); + long duration = (currentTimeStamp - adviceResponse.startTime); + + // // WRITE METRIC + String thread_name = Thread.currentThread().getName().replace(" ", "_"); + + StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + StringBuilder m_endtime = new StringBuilder("nttdata.aemforms.workflow.endtime"); + + if (adviceResponse.uniqueID != null) { + m_duration.append(",uuid="); + m_duration.append(adviceResponse.uniqueID); + m_endtime.append(",uuid="); + m_endtime.append(adviceResponse.uniqueID); + } + if (thread_name != null) { + m_duration.append(",threadname="); + m_duration.append(thread_name); + m_endtime.append(",threadname="); + m_endtime.append(thread_name); + } + if (method != null) { + m_duration.append(",method="); + m_duration.append(method.replace(" ", "_")); + m_endtime.append(",method="); + m_endtime.append(method.replace(" ", "_")); + } + if (adviceResponse.startDate != null) { + m_duration.append(",startdate="); + m_duration.append(adviceResponse.startDate); + m_endtime.append(",startdate="); + m_endtime.append(adviceResponse.startDate); + } + if (adviceResponse.workflow != null) { + m_duration.append(",workflow="); + m_duration.append(adviceResponse.workflow); + m_endtime.append(",workflow="); + m_endtime.append(adviceResponse.workflow); + } + m_duration.append(" "); + m_duration.append(duration); + m_endtime.append(" "); + m_endtime.append(currentTimeStamp); + + System.out.println("Metric duration: " + m_duration.toString()); + System.out.println("Metric endtime: " + m_endtime.toString()); + + OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + OneAgentMetricWriter.getInstance().writeMetric(m_endtime.toString()); + } + } +} diff --git a/agent_test/src/main/java/com/example/AdviceResponse.java b/agent_test/src/main/java/com/example/AdviceResponse.java new file mode 100644 index 0000000..0842c84 --- /dev/null +++ b/agent_test/src/main/java/com/example/AdviceResponse.java @@ -0,0 +1,15 @@ +package com.example; + +public class AdviceResponse { + public long startTime; + public String uniqueID; + public String workflow; + public String startDate; + + public AdviceResponse(long startTime, String uniqueID, String workflow, String startDate) { + this.startTime=startTime; + this.uniqueID=uniqueID; + this.workflow=workflow; + this.startDate=startDate; + } +} diff --git a/agent_test/src/main/java/com/example/AdviceRestServlet.java b/agent_test/src/main/java/com/example/AdviceRestServlet.java new file mode 100644 index 0000000..43c3e2a --- /dev/null +++ b/agent_test/src/main/java/com/example/AdviceRestServlet.java @@ -0,0 +1,205 @@ +package com.example; + +import java.net.URLDecoder; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import net.bytebuddy.asm.*; + +public class AdviceRestServlet { + @Advice.OnMethodEnter + static AdviceResponse invokeBeforeEnterMethod(@Advice.AllArguments Object[] args, + @Advice.Origin String method) { + + String SYNC_INVOKE = "services/"; + try { + + HttpServletRequest req = (HttpServletRequest) args[0]; + String uri = req.getRequestURI(); + uri = URLDecoder.decode(uri); + + if (uri.endsWith(".xml")) + return null; + + if (uri.endsWith(".json")) + return null; + + if (!uri.startsWith("/rest/")) + return null; + + uri = uri.substring(6); + + if (!uri.startsWith(SYNC_INVOKE)) + return null; + + uri = uri.substring(SYNC_INVOKE.length()); + + int dotPos = uri.indexOf(46); + int suffixPos = uri.indexOf(47, dotPos); + if (dotPos >= 0 && suffixPos > dotPos) { + uri = uri.substring(0, suffixPos); + } + + int majorVersion = 0; + int minorVersion = 0; + String version = null; + int colonPos = uri.lastIndexOf(58); + if (colonPos >= 0) { + version = uri.substring(colonPos + 1); + uri = uri.substring(0, colonPos); + + try { + String[] nums = version.split("\\."); + if (nums.length != 2) { + throw new Error(); + } + + majorVersion = Integer.parseInt(nums[0]); + minorVersion = Integer.parseInt(nums[1]); + } catch (Throwable var25) { + throw new Exception("The version part of the URL should follow . format."); + } + } + + dotPos = uri.lastIndexOf(46); + String operationName; + if (dotPos >= 0) { + operationName = uri.substring(dotPos + 1); + uri = uri.substring(0, dotPos); + } else { + operationName = "invoke"; + } + + if (operationName != "invoke") + return null; + + String uniqueID = UUID.randomUUID().toString(); + long currentTimeStamp = System.currentTimeMillis(); + + Date date=new Date(currentTimeStamp); + DateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'"); + String dateTxT=f.format(date); + + + String workflow = uri.replace(" ", "_"); + String thread_name = Thread.currentThread().getName().replace(" ", "_"); + + StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + StringBuilder m_starttime = new StringBuilder("nttdata.aemforms.workflow.starttime"); + + if (uniqueID != null) { + m_duration.append(",uuid="); + m_duration.append(uniqueID); + m_starttime.append(",uuid="); + m_starttime.append(uniqueID); + } + if (thread_name != null) { + m_duration.append(",threadname="); + m_duration.append(thread_name); + m_starttime.append(",threadname="); + m_starttime.append(thread_name); + } + if (method != null) { + m_duration.append(",method="); + m_duration.append(method.replace(" ", "_").replace(",","_")); + m_starttime.append(",method="); + m_starttime.append(method.replace(" ", "_").replace(",","_")); + } + if (dateTxT != null) { + m_duration.append(",startdate="); + m_duration.append(dateTxT); + m_starttime.append(",startdate="); + m_starttime.append(dateTxT); + } + if (workflow != null) { + m_duration.append(",workflow="); + m_duration.append(workflow); + m_starttime.append(",workflow="); + m_starttime.append(workflow); + } + m_duration.append(" 0"); + m_starttime.append(" "); + m_starttime.append(currentTimeStamp); + + System.out.println(m_duration); + System.out.println(m_starttime); + + OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + OneAgentMetricWriter.getInstance().writeMetric(m_starttime.toString()); + + return new AdviceResponse(currentTimeStamp, uniqueID, workflow, dateTxT); + + } catch (Exception ex) { + System.out.println("Exception occured: " + ex.getMessage()); + } + + return null; + + } + + // (onThrowable=Throwable.class) + + @Advice.OnMethodExit(onThrowable=Throwable.class) + static void invokeAfterExitMethod( + @Advice.Origin String method, + @Advice.Enter AdviceResponse adviceResponse) { + + + if (adviceResponse != null) { + long currentTimeStamp = System.currentTimeMillis(); + long duration = (currentTimeStamp - adviceResponse.startTime); + + // // WRITE METRIC + String thread_name = Thread.currentThread().getName().replace(" ", "_"); + + StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + StringBuilder m_endtime = new StringBuilder("nttdata.aemforms.workflow.endtime"); + + if (adviceResponse.uniqueID != null) { + m_duration.append(",uuid="); + m_duration.append(adviceResponse.uniqueID); + m_endtime.append(",uuid="); + m_endtime.append(adviceResponse.uniqueID); + } + if (thread_name != null) { + m_duration.append(",threadname="); + m_duration.append(thread_name); + m_endtime.append(",threadname="); + m_endtime.append(thread_name); + } + if (method != null) { + m_duration.append(",method="); + m_duration.append(method.replace(" ", "_").replace(",","_")); + m_endtime.append(",method="); + m_endtime.append(method.replace(" ", "_").replace(",","_")); + } + if (adviceResponse.startDate != null) { + m_duration.append(",startdate="); + m_duration.append(adviceResponse.startDate); + m_endtime.append(",startdate="); + m_endtime.append(adviceResponse.startDate); + } + if (adviceResponse.workflow != null) { + m_duration.append(",workflow="); + m_duration.append(adviceResponse.workflow); + m_endtime.append(",workflow="); + m_endtime.append(adviceResponse.workflow); + } + + m_duration.append(" "); + m_duration.append(duration); + m_endtime.append(" "); + m_endtime.append(currentTimeStamp); + + System.out.println("Metric duration: " + m_duration.toString()); + System.out.println("Metric endtime: " + m_endtime.toString()); + + OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + OneAgentMetricWriter.getInstance().writeMetric(m_endtime.toString()); + } + } +} diff --git a/agent_test/src/main/java/com/example/AdviceRouter.java b/agent_test/src/main/java/com/example/AdviceRouter.java new file mode 100644 index 0000000..3a45259 --- /dev/null +++ b/agent_test/src/main/java/com/example/AdviceRouter.java @@ -0,0 +1,255 @@ +package com.example; + +import com.adobe.idp.dsc.InvocationRequest; +import com.adobe.idp.dsc.engine.impl.ServiceEngineImpl; +import com.adobe.idp.dsc.impl.InvocationRequestImpl; +import com.adobe.idp.dsc.registry.infomodel.Operation; +import com.adobe.idp.dsc.registry.infomodel.ServiceConfiguration; + +//import java.io.Console; +// import java.util.UUID; + +// import com.adobe.workflow.engine.PEInvokeProcessCommand; +// import com.dynatrace.oneagent.sdk.OneAgentSDKFactory; +// import com.dynatrace.oneagent.sdk.api.OneAgentSDK; +import net.bytebuddy.asm.*; +// import net.bytebuddy.asm.Advice.FieldValue; +// import net.bytebuddy.implementation.bytecode.assign.Assigner.Typing; + +public class AdviceRouter { + // @Advice.AllArguments Object[] args, + @Advice.OnMethodEnter + static void invokeBeforeEnterMethod(@Advice.AllArguments Object[] args, + @Advice.Origin String method) { + + try { + + System.out.println(""); + System.out.println(""); + System.out.println("################################## START router call #################################"); + InvocationRequest aRequest=(InvocationRequest)args[0]; + InvocationRequestImpl _request = (InvocationRequestImpl)aRequest; + + String _endpointId = (String)_request.getProperty("ENDPOINT_PUBLIC_ID"); + String _connectorId = (String)_request.getProperty("CONNECTOR_ID"); + + if(_endpointId!= null) + System.out.println("endpointId: "+_endpointId); + if(_connectorId!= null) + System.out.println("connectorId: "+_connectorId); + + + if(_request.getInvocationId()!=null) + System.out.println("_request.innvocationId: "+_request.getInvocationId()); + if(_request.getOperationName()!=null) + System.out.println("_request.operation.name: "+_request.getOperationName()); + if(_request.getServiceName()!=null) + System.out.println("_request.service.name: "+_request.getServiceName()); + if(_request.getEndPointURI()!=null) + System.out.println("_request.endpointURI: "+_request.getEndPointURI()); + + ServiceConfiguration _config = _request.getTargetServiceConfiguration(); + if (_config == null) { + _config = ServiceEngineImpl.resolveConfiguration(aRequest.getServiceName(), aRequest.getServiceExplicitVersion(), aRequest.getServiceOriginalVersion()); + _request.setTargetServiceConfiguration(_config); + } + + Operation _operation = _config.getOperation(aRequest.getOperationName()); + Boolean longLivedInvokeExists = (Boolean)aRequest.getProperty("long-lived-invoke"); + if (longLivedInvokeExists == null) { + longLivedInvokeExists = new Boolean(false); + } + + + if(_operation.getName()!=null) + System.out.println("operation.name: "+_operation.getName()); + + if(_operation.getServiceId()!=null) + System.out.println("operation.serviceId: "+_operation.getServiceId()); + + if(_operation.getTitle()!=null) + System.out.println("operation.title: "+_operation.getTitle()); + + + if(_config.getComponentId()!=null) + System.out.println("config.componentId: "+_config.getComponentId()); + if(_config.getServiceId()!=null) + System.out.println("config.serviceId: "+_config.getServiceId()); + if(_config.getType()!=null) + System.out.println("config.type: "+_config.getType()); + if(_config.getTitle()!=null) + System.out.println("config.type: "+_config.getTitle()); + + + System.out.println("################################## END router call #################################"); + System.out.println(""); + System.out.println(""); + + + }catch(Exception ex) { + System.out.println("Exception occured: "+ex.getMessage()); + } + // String uniqueID = UUID.randomUUID().toString(); + // long currentTimeStamp = System.currentTimeMillis(); + // String workflow = ""; + + // try { + + // if(m_command != null) { + // workflow =((PEInvokeProcessCommand)m_command).getInvocationInfo().getProcessTypeId(); + // //System.out.println("Workflow: "+ workflow); + // } + + // //workflow = "test-test123"; + // workflow=workflow.replace(" ", "_"); + + // // System.out.println("Test STR Private variable: "+ + // // ((JsonObject)testStr).get("name")); + // System.out.println("Printing Methods args: "); + // for (Object obj : args) { + // System.out.println(obj.toString()); + // } + + + // // Timestamp Start + + // OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); + // oneAgentSdk.addCustomRequestAttribute("method_start_time", currentTimeStamp); + + // // RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); + // // String jvmName = bean.getName(); + // // System.out.println("Name = " + jvmName); + + // // System.out.println("Method invoked before enter method by: " + method); + + // String thread_name = Thread.currentThread().getName().replace(" ", "_"); + // oneAgentSdk.addCustomRequestAttribute("thread_name", thread_name); + + // StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + // StringBuilder m_starttime = new StringBuilder("nttdata.aemforms.workflow.starttime"); + + // if (uniqueID!= null) { + // m_duration.append(",uuid="); + // m_duration.append(uniqueID); + // m_starttime.append(",uuid="); + // m_starttime.append(uniqueID); + // } + // if (thread_name != null) { + // m_duration.append(",threadname="); + // m_duration.append(thread_name); + // m_starttime.append(",threadname="); + // m_starttime.append(thread_name); + // } + // if (method != null) { + // m_duration.append(",method="); + // m_duration.append(method.replace(" ", "_")); + // m_starttime.append(",method="); + // m_starttime.append(method.replace(" ", "_")); + // } + // if (workflow != null) { + // m_duration.append(",workflow="); + // m_duration.append(workflow); + // m_starttime.append(",workflow="); + // m_starttime.append(workflow); + // } + // m_duration.append(" 0"); + // m_starttime.append(" "); + // m_starttime.append(currentTimeStamp); + + // // // SEND METRIC ############################ + // // // String m_duration = "nttdata.aemforms.workflow.duration,uuid=" + uniqueID + ",threadname=" + // // // + thread_name.replace(" ", "_") + ",methode=" + method.replace(" ", "_") + ",workflow=" + // // // + workflow.replace(" ", "_") + " 0"; + // // // String m_starttime = "nttdata.aemforms.workflow.starttime,uuid=" + uniqueID + ",threadname=" + // // // + thread_name.replace(" ", "_") + ",methode=" + method.replace(" ", "_") + ",workflow=" + // // // + workflow.replace(" ", "_") + " " + currentTimeStamp; + + // System.out.println("Metric duration: " + m_duration.toString()); + // System.out.println("Metric starttime: " + m_starttime.toString()); + + // OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + // OneAgentMetricWriter.getInstance().writeMetric(m_starttime.toString()); + + // } catch(Exception ex) { + // System.out.println("Exception occured during call Oneagent SDK"+ + // ex.getMessage()); + // } + + // return new AdviceResponse(currentTimeStamp, uniqueID, workflow); + + } + + // (onThrowable = Throwable.class) + // @Advice.OnMethodExit + // static void invokeAfterExitMethod( + // @Advice.Origin String method, + // @Advice.Enter AdviceResponse adviceResponse) { + + // // OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); + // // oneAgentSdk.addCustomRequestAttribute("method_end_time", + // // System.currentTimeMillis()); + + // if (adviceResponse != null) { + // long currentTimeStamp = System.currentTimeMillis(); + // long duration = (currentTimeStamp - adviceResponse.startTime); + // // System.out.println("Method " + method + " took " + duration + "ms"); + + // // // WRITE METRIC + // String thread_name = Thread.currentThread().getName().replace(" ", "_"); + // //System.out.println(method); + // //method = method.replace(" ", "_"); + + // StringBuilder m_duration = new StringBuilder("nttdata.aemforms.workflow.duration"); + // StringBuilder m_endtime = new StringBuilder("nttdata.aemforms.workflow.endtime"); + + // if (adviceResponse.uniqueID != null) { + // m_duration.append(",uuid="); + // m_duration.append(adviceResponse.uniqueID); + // m_endtime.append(",uuid="); + // m_endtime.append(adviceResponse.uniqueID); + // } + // if (thread_name != null) { + // m_duration.append(",threadname="); + // m_duration.append(thread_name); + // m_endtime.append(",threadname="); + // m_endtime.append(thread_name); + // } + // if (method != null) { + // m_duration.append(",method="); + // m_duration.append(method.replace(" ", "_")); + // m_endtime.append(",method="); + // m_endtime.append(method.replace(" ", "_")); + // } + // if (adviceResponse.workflow != null) { + // m_duration.append(",workflow="); + // m_duration.append(adviceResponse.workflow); + // m_endtime.append(",workflow="); + // m_endtime.append(adviceResponse.workflow); + // } + // m_duration.append(" "); + // m_duration.append(duration); + // m_endtime.append(" "); + // m_endtime.append(currentTimeStamp); + + // // String m_duration = "nttdata.aemforms.workflow.duration,uuid=" + + // // adviceResponse.uniqueID + ",threadname=" + // // + thread_name.replace(" ", "_") + ",method=" + method.replace(" ", "_") + + // // ",workflow=" + // // + adviceResponse.workflow.replace(" ", "_") + " " + duration; + + // // String m_endtime = "nttdata.aemforms.workflow.endtime,uuid=" + + // // adviceResponse.uniqueID + ",threadname=" + // // + thread_name.replace(" ", "_") + ",methode=" + method.replace(" ", "_") + + // // ",workflow=" + // // + adviceResponse.workflow.replace(" ", "_") + " " + currentTimeStamp; + + // System.out.println("Metric duration: " + m_duration.toString()); + // System.out.println("Metric endtime: " + m_endtime.toString()); + + // OneAgentMetricWriter.getInstance().writeMetric(m_duration.toString()); + // OneAgentMetricWriter.getInstance().writeMetric(m_endtime.toString()); + // } else { + // System.out.println("AdviceResponse AfterExit is null"); + // } + // } +} diff --git a/agent_test/src/main/java/com/example/Agent.java b/agent_test/src/main/java/com/example/Agent.java new file mode 100644 index 0000000..95d410e --- /dev/null +++ b/agent_test/src/main/java/com/example/Agent.java @@ -0,0 +1,151 @@ +package com.example; + +import java.lang.instrument.Instrumentation; +import java.util.Iterator; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.json.simple.JSONArray; + + + +import net.bytebuddy.agent.builder.AgentBuilder; +import net.bytebuddy.agent.builder.ResettableClassFileTransformer; +import net.bytebuddy.agent.builder.AgentBuilder.RedefinitionStrategy; +import net.bytebuddy.asm.Advice; +import net.bytebuddy.matcher.ElementMatcher; +import net.bytebuddy.matcher.ElementMatchers; + +class Agent { + // public static void premain(String arguments, Instrumentation instrumentation) { + // new AgentBuilder.Default() + // .type(ElementMatchers.any()) + // .transform((builder, typeDescription, classLoader, module) -> builder + // .method(ElementMatchers.nameContainsIgnoreCase("fetch")) + // .intercept(Advice.to(DTAdvice.class))) + // .installOn(instrumentation); + // } + +// public static void agentmain_BAK(String agentArgs, Instrumentation instrumentation) { + +// System.out.println("attached dynamically witth parameeters: "+agentArgs); + +// ElementMatcher.Junction matches = ElementMatchers.nameStartsWith("com.javadevelopersguide.jersey.resources"); + +// ResettableClassFileTransformer ab = new AgentBuilder.Default() +// .disableClassFormatChanges() +// .with(RedefinitionStrategy.RETRANSFORMATION) +// .type(matches) +// .transform((builder, typeDescription, classLoader, module) -> builder +// //.method(ElementMatchers.nameContainsIgnoreCase("fetch")) +// .visit(Advice.to(DTAdvice.class).on(ElementMatchers.nameContainsIgnoreCase("fetch")))) +// .installOn(instrumentation); + + + +// int x = 0; + +// } + + public static void agentmain(String agentArgs, Instrumentation instrumentation) { + + System.out.println("attached dynamically witth parameeters 2: "+agentArgs); + //String[] methods = {"fetchAll","create"}; + + JSONParser jsonParser = new JSONParser(); + JSONObject jsonparams=null; + + try { + jsonparams = (JSONObject) jsonParser.parse(agentArgs); + + JSONArray class_configs = (JSONArray) jsonparams.get("instrument"); + + Iterator it = class_configs.iterator(); + + while(it.hasNext()) { + + JSONObject config = (JSONObject) it.next(); + //JSONObject config = (JSONObject) ((JSONArray) jsonparams.get("instrument")).get(0); + JSONArray methods = (JSONArray) config.get("methods"); + //JSONjsonparams.get("instrument") + + + Class adviceCls = Class.forName((String) config.get("adviceClass")); + Advice advice = Advice.to(adviceCls); + + //Advice advice = Advice.withCustomMapping().bind(DTAdvice.class,""); //to(DTAdvice.class); + ElementMatcher.Junction matches = ElementMatchers.nameMatches(config.get("class").toString()); + + ResettableClassFileTransformer ab = new AgentBuilder.Default() + .disableClassFormatChanges() + .with(RedefinitionStrategy.RETRANSFORMATION) + .type(matches) + + .transform((builder, typeDescription, classLoader, module) -> { + for (int i = 0; i < methods.size(); i++) { + System.out.println(methods.get(i).toString()); + builder = builder.visit(advice.on(ElementMatchers.named(methods.get(i).toString()))); + } + + return builder; + }).installOn(instrumentation); + } + + + } catch (ParseException | ClassNotFoundException e) { + // TODO Auto-generated catch block + + System.out.println(e.getMessage()); + e.printStackTrace(); + } + + + + + } + +// public static void agentmain(String agentArgs, Instrumentation instrumentation) { + +// System.out.println("attached dynamically witth parameeters 2: "+agentArgs); +// //String[] methods = {"fetchAll","create"}; + +// JSONParser jsonParser = new JSONParser(); +// JSONObject jsonparams=null; + +// try { +// jsonparams = (JSONObject) jsonParser.parse(agentArgs); +// JSONObject config = (JSONObject) ((JSONArray) jsonparams.get("instrument")).get(0); +// JSONArray methods = (JSONArray) config.get("methods"); +// //JSONjsonparams.get("instrument") +// Advice advice = Advice.to(DTAdvice.class); +// ElementMatcher.Junction matches = ElementMatchers.nameMatches(config.get("class").toString()); + +// ResettableClassFileTransformer ab = new AgentBuilder.Default() +// .disableClassFormatChanges() +// .with(RedefinitionStrategy.RETRANSFORMATION) +// .type(matches) + +// .transform((builder, typeDescription, classLoader, module) -> { +// for (int i = 0; i < methods.size(); i++) { +// System.out.println(methods.get(i).toString()); +// builder = builder.visit(advice.on(ElementMatchers.named(methods.get(i).toString()))); +// } + +// return builder; +// }).installOn(instrumentation); + + +// } catch (ParseException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + + + + +// } + + public static void main(String[] args) { + } +} diff --git a/agent_test/src/main/java/com/example/DTAdvice.java b/agent_test/src/main/java/com/example/DTAdvice.java new file mode 100644 index 0000000..0ad0d0d --- /dev/null +++ b/agent_test/src/main/java/com/example/DTAdvice.java @@ -0,0 +1,98 @@ +// package com.example; +// import java.lang.management.ManagementFactory; +// import java.lang.management.RuntimeMXBean; + + +// import com.dynatrace.oneagent.sdk.OneAgentSDKFactory; +// import com.dynatrace.oneagent.sdk.api.OneAgentSDK; +// import com.google.gson.JsonObject; + +// import net.bytebuddy.asm.*; +// import net.bytebuddy.asm.Advice.FieldValue; +// import net.bytebuddy.implementation.bytecode.assign.Assigner.Typing; + +// public class DTAdvice { +// //@Advice.AllArguments Object[] args, +// @Advice.OnMethodEnter +// static long invokeBeforeEnterMethod(@Advice.AllArguments Object[] args, +// @Advice.Origin String method, @FieldValue(value = "jsonObject", typing = Typing.DYNAMIC) Object testStr) { + +// try { +// System.out.println("DTAdvice....."); +// System.out.println("Test STR Private variable: "+ ((JsonObject)testStr).get("name")); +// System.out.println("Printing Methods args: "); +// for(Object obj : args) { +// System.out.println(obj.toString()); +// } +// OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); +// oneAgentSdk.addCustomRequestAttribute("method_start_time", System.currentTimeMillis()); + +// RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); +// String jvmName = bean.getName(); +// System.out.println("Name = " + jvmName); + + +// System.out.println("Method invoked before enter method by: " + method); + + +// String thread_name = Thread.currentThread().getName(); +// oneAgentSdk.addCustomRequestAttribute("thread_name", thread_name); +// System.out.println("Current Thread Name: "+thread_name); + + +// //SEND METRIC ############################ +// String m = "aemforms.threads,threadname="+thread_name+",methode="+method+",action=start "+System.currentTimeMillis(); +// OneAgentMetricWriter.getInstance().writeMetric(m); + +// } catch(Exception ex) { +// System.out.println("Exception occured during call Oneagent SDK"+ ex.getMessage()); +// } + +// // final SimpleHttpRequest request = SimpleRequestBuilder.post("http://localhost:14499/metrics/ingest") +// // .setBody("cpu.temperature,cpu=1 55",ContentType.TEXT_HTML) +// // .build(); + + + + + +// //final HttpPost httpPost = new HttpPost("sadsad"); +// // HttpClient client = HttpClient.newHttpClient(); + +// // HttpRequest request = HttpRequest.newBuilder() +// // .uri(URI.create("http://localhost:14499/metrics/ingest")) +// // .POST(HttpRequest.BodyPublishers.ofString("cpu.temperature,cpu=1 55")) +// // .build(); + +// // client.sendAsync(request, BodyHandlers.ofString()) +// // .thenApply(response -> { System.out.println(response.statusCode()); +// // return response; } ) +// // .thenApply(HttpResponse::body) +// // .thenAccept(System.out::println); + + + + + +// return System.currentTimeMillis(); +// } + +// @Advice.OnMethodExit +// static void invokeAfterExitMethod( +// @Advice.Origin String method, +// @Advice.Enter long startTime +// ) { +// OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); +// oneAgentSdk.addCustomRequestAttribute("method_end_time", System.currentTimeMillis()); + +// long duration = (System.currentTimeMillis() - startTime); +// System.out.println("Method " + method + " took " + duration + "ms"); + + +// oneAgentSdk.addCustomRequestAttribute("method_duration", duration); +// System.out.println("End method"); +// } +// } + + + diff --git a/agent_test/src/main/java/com/example/MetricPostCallback.java b/agent_test/src/main/java/com/example/MetricPostCallback.java new file mode 100644 index 0000000..dbbaf51 --- /dev/null +++ b/agent_test/src/main/java/com/example/MetricPostCallback.java @@ -0,0 +1,19 @@ +package com.example; + +import org.apache.http.HttpResponse; +import org.apache.http.concurrent.FutureCallback; + +public class MetricPostCallback implements FutureCallback { + public void completed(final HttpResponse response2) { + System.out.println("metric ingest --> complete"); + } + + public void failed(final Exception ex) { + System.out.println("metric ingest --> failed "+ ex.getMessage()); + } + + public void cancelled() { + System.out.println("metric ingest --> cacelled"); + } + +} diff --git a/agent_test/src/main/java/com/example/OneAgentMetricWriter.java b/agent_test/src/main/java/com/example/OneAgentMetricWriter.java new file mode 100644 index 0000000..c268a74 --- /dev/null +++ b/agent_test/src/main/java/com/example/OneAgentMetricWriter.java @@ -0,0 +1,64 @@ +package com.example; +import java.io.UnsupportedEncodingException; +import java.util.concurrent.Future; + + import org.apache.http.HttpResponse; + import org.apache.http.client.methods.HttpPost; +//import org.apache.http.concurrent.FutureCallback; +import org.apache.http.entity.StringEntity; + import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; + +public class OneAgentMetricWriter { + + private static OneAgentMetricWriter instance; + CloseableHttpAsyncClient client = null; + HttpPost httpPost=null; + + private OneAgentMetricWriter() { + this.client = HttpAsyncClients.custom() + .build(); + client.start(); + + this.httpPost = new HttpPost("http://localhost:14499/metrics/ingest"); + } + + public void writeMetric(String request) { + // final CloseableHttpAsyncClient client = HttpAsyncClients.custom() + // .build(); + // client.start(); + + + //String request = "cpu.temperature,cpu=1 55"; + StringEntity entity; + try { + entity = new StringEntity(request); + httpPost.setEntity(entity); + httpPost.setHeader("Content-type", "text/plain"); + Future future = client.execute(httpPost, new MetricPostCallback()); + + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + + + } + + public static OneAgentMetricWriter getInstance() { + if (instance == null) { + // synchronized block to remove overhead + synchronized (OneAgentMetricWriter.class) { + if (instance == null) { + // if instance is null, initialize + instance = new OneAgentMetricWriter(); + } + + } + } + return instance; + } + +} diff --git a/agent_test/src/main/java/com/example/XMLDTAdvice.java b/agent_test/src/main/java/com/example/XMLDTAdvice.java new file mode 100644 index 0000000..dc783c5 --- /dev/null +++ b/agent_test/src/main/java/com/example/XMLDTAdvice.java @@ -0,0 +1,117 @@ +package com.example; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.util.concurrent.Future; + + import org.apache.http.HttpResponse; + import org.apache.http.client.methods.HttpPost; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.entity.StringEntity; + import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; + +import com.dynatrace.oneagent.sdk.OneAgentSDKFactory; +import com.dynatrace.oneagent.sdk.api.OneAgentSDK; +import com.google.gson.JsonObject; + +import net.bytebuddy.asm.*; +import net.bytebuddy.asm.Advice.FieldValue; +import net.bytebuddy.implementation.bytecode.assign.Assigner.Typing; + +public class XMLDTAdvice { + //@Advice.AllArguments Object[] args, + @Advice.OnMethodEnter + static long invokeBeforeEnterMethod(@Advice.AllArguments Object[] args, + @Advice.Origin String method) { + + try { + + System.out.println("XMLDTAdvice....."); + + // System.out.println("Test STR Private variable: "+ ((JsonObject)testStr).get("name")); + // System.out.println("Printing Methods args: "); + for(Object obj : args) { + System.out.println(obj.toString()); + } + OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); + oneAgentSdk.addCustomRequestAttribute("method_start_time", System.currentTimeMillis()); + + RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); + String jvmName = bean.getName(); + System.out.println("Name = " + jvmName); + + + System.out.println("Method invoked before enter method by: " + method); + + + String thread_name = Thread.currentThread().getName(); + oneAgentSdk.addCustomRequestAttribute("thread_name", thread_name); + System.out.println("Current Thread Name: "+thread_name); + + + //SEND METRIC ############################ + // final CloseableHttpAsyncClient client = HttpAsyncClients.custom() + // .build(); + // client.start(); + + // final HttpPost httpPost = new HttpPost("http://localhost:14499/metrics/ingest"); + // String request = "cpu.temperature,cpu=1 55"; + // StringEntity entity = new StringEntity(request); + // httpPost.setEntity(entity); + // httpPost.setHeader("Content-type", "text/plain"); + + // final Future future = client.execute(httpPost, new MetricPostCallback()); + OneAgentMetricWriter.getInstance().writeMetric("cpu.temperature,cpu=1 55"); + + } catch(Exception ex) { + System.out.println("Exception occured during call Oneagent SDK"+ ex.getMessage()); + } + + // final SimpleHttpRequest request = SimpleRequestBuilder.post("http://localhost:14499/metrics/ingest") + // .setBody("cpu.temperature,cpu=1 55",ContentType.TEXT_HTML) + // .build(); + + + + + + //final HttpPost httpPost = new HttpPost("sadsad"); + // HttpClient client = HttpClient.newHttpClient(); + + // HttpRequest request = HttpRequest.newBuilder() + // .uri(URI.create("http://localhost:14499/metrics/ingest")) + // .POST(HttpRequest.BodyPublishers.ofString("cpu.temperature,cpu=1 55")) + // .build(); + + // client.sendAsync(request, BodyHandlers.ofString()) + // .thenApply(response -> { System.out.println(response.statusCode()); + // return response; } ) + // .thenApply(HttpResponse::body) + // .thenAccept(System.out::println); + + + + + + return System.currentTimeMillis(); + } + + @Advice.OnMethodExit + static void invokeAfterExitMethod( + @Advice.Origin String method, + @Advice.Enter long startTime + ) { + OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance(); + oneAgentSdk.addCustomRequestAttribute("method_end_time", System.currentTimeMillis()); + + long duration = (System.currentTimeMillis() - startTime); + System.out.println("Method " + method + " took " + duration + "ms"); + + + oneAgentSdk.addCustomRequestAttribute("method_duration", duration); + System.out.println("End method"); + } +} + + + diff --git a/agent_test/src/test/java/com/example/AppTest.java b/agent_test/src/test/java/com/example/AppTest.java new file mode 100644 index 0000000..22a94ca --- /dev/null +++ b/agent_test/src/test/java/com/example/AppTest.java @@ -0,0 +1,20 @@ +package com.example; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest +{ + /** + * Rigorous Test :-) + */ + @Test + public void shouldAnswerWithTrue() + { + assertTrue( true ); + } +}