How to get dynamic path in java - java

String s = "cmd /c " + GeneralMethods.getFilesPath()
+ "mysql-5.6.26-winx64/bin/mysqldump -u root -password database_name>" + GeneralMethods.getFilesPath()
+ "backup/backup.sql";
I dont want static code
I want to choose dynamic path on java.

If you are running the code from main method, pass the variables as program arguments. Read these arguments in the method and create the path.
For example
class Test {
public static void main(String[] args) {
String s = "cmd /c " + GeneralMethods.getFilesPath() + args[0] + "-u root -password database_name>" + GeneralMethods.getFilesPath() + args[1];
}
}
For any application VM arguments can be used.
String s = "cmd /c " + GeneralMethods.getFilesPath() + System.getProperty("sysProp1") + "-u root -password database_name>" + GeneralMethods.getFilesPath() + System.getProperty("sysProp2");
These variables sysProp1 or sysProp2 can be set using -DsysProp1=value1 -DsysProp2=value2 when starting the server / application.
Or if they are required at multiple places in the application
Create a class to hold these values
public class HolderClass {
public static String value1 = null;
public static String value2 = null;
}
Now, in the method where these values are available (in main method for example), set the values,
HolderClass.value1 = "value received"
HolderClass.value2 = "Other value received"
At the point where this value is required, use as
String s = "cmd /c " + GeneralMethods.getFilesPath() + HolderClass.value1 + "-u root -password database_name>" + GeneralMethods.getFilesPath() + HolderClass.value2;

Related

My Profiler using Byte Buddy agent does not stop monitoring some tests

I'm trying to collect execution time from all methods of an application called by their tests using Byte Buddy. However, sometimes, it takes much longer than expected. For example, when I run the test described below without the Byte Buddy agent, it takes a few milliseconds to run. When I start with the agent it runs without ending and I need to force stop. It occurs in several test cases from different projects. What could I be doing wrong and how can I fix it?
Agent:
class PerfrtProfilerAgent {
public static void premain(String arguments, Instrumentation instrumentation) {
String[] agentArgs = arguments.trim().split("\\s*,\\s*");
final String packName = agentArgs[0];
new AgentBuilder.Default()
.with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
.type((ElementMatchers.nameStartsWith(packName)))
.transform((builder, typeDescription, classLoader, module) -> builder
.method(ElementMatchers.any())
.intercept(Advice.withCustomMapping().bind(AgentArguments.class, arguments).to(TimerAdvice.class))
).installOn(instrumentation);
}
}
TimerAdvice.java
package perfrt.profiler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.bytebuddy.asm.Advice;
public class TimerAdvice {
#Advice.OnMethodEnter
public static OnMethodEnterReturn enter(#Advice.Origin String method, #AgentArguments String agentArguments) {
String[] agentArgs = agentArguments.trim().split("\\s*,\\s*");
OnMethodEnterReturn onEnterValues = new OnMethodEnterReturn();
onEnterValues.setPackageName(agentArgs[0]);
onEnterValues.setCommitHash(agentArgs[1]);
onEnterValues.setIdRun(Integer.parseInt(agentArgs[2]));
onEnterValues.setStartTime(System.currentTimeMillis());
String className = parseClassName(method);
System.out.println("onEnter - Class: " + className + " method: " + method);
onEnterValues.setIdMethod(1);
return onEnterValues;
}
#Advice.OnMethodExit(onThrowable = Throwable.class)
public static void exit(#Advice.Origin String method
, #Advice.Enter OnMethodEnterReturn onEnterValues
){
String packName = onEnterValues.getPackageName();
String className = parseClassName(method).replace(packName, "") + ".java";
long start = onEnterValues.getStartTime();
long end = System.currentTimeMillis();
long duration = end - start;
String returnedType = "teste";
System.out.println("onExit - Class: " + className + " method: " + method + " start: " + start + " end: " + end + " duration: " + duration + "retValue:" );
}
public static String parseClassName(String method) {
String className = null;
Pattern p = Pattern.compile("[^\\s]*\\(");
Matcher m = p.matcher(method);
if (m.find()) {
String methodName = (String)m.group(0).toString();
String[] methodAux = methodName.split("\\.");
if(methodAux.length > 0) {
className = methodAux[0];
for(int i = 1; i < methodAux.length-1; i++) {
className += "." + methodAux[i];
}
}else {
className = methodName;
}
}
String last = className.substring(className.lastIndexOf('.') + 1);
className = last + ".java";
return className;
}
}
The complete code of the agent is at perfrt-profiler2.
The steps to reproduce one example of the situation are:
git clone https://github.com/apache/commons-bcel
cd commons-bcel
mvn -Drat.skip=true install (requires maven)
wget -O junit-platform-console-standalone-1.9.0-M1.jar https://search.maven.org/remotecontent?filepath=org/junit/platform/junit-platform-console-standalone/1.9.0-M1/junit-platform-console-standalone-1.9.0-M1.jar
wget https://github.com/paulorfarah/perfrt-profiler2/raw/master/perfrt-profiler2-0.0.1-SNAPSHOT.jar
java -javaagent:perfrt-profiler2-0.0.1-SNAPSHOT.jar=org.apache.bcel.,cbbed9ec41c70469cab42a584e205b96c0f964fc,483 -jar junit-platform-console-standalone-1.9.0-M1.jar -cp .:target/test-classes/:target/classes:/home/user/.m2/repository/org/junit/jupiter/junit-jupiter/5.8.2/junit-jupiter-5.8.2.jar:/home/user/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.8.2/junit-jupiter-api-5.8.2.jar:/home/user/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar:/home/user/.m2/repository/org/junit/platform/junit-platform-commons/1.8.2/junit-platform-commons-1.8.2.jar:/home/user/.m2/repository/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar:/home/user/.m2/repository/org/junit/jupiter/junit-jupiter-params/5.8.2/junit-jupiter-params-5.8.2.jar:/home/user/.m2/repository/org/junit/jupiter/junit-jupiter-engine/5.8.2/junit-jupiter-engine-5.8.2.jar:/home/user/.m2/repository/org/junit/platform/junit-platform-engine/1.8.2/junit-platform-engine-1.8.2.jar:/home/user/.m2/repository/net/java/dev/jna/jna/5.12.1/jna-5.12.1.jar:/home/user/.m2/repository/net/java/dev/jna/jna-platform/5.12.1/jna-platform-5.12.1.jar:/home/user/.m2/repository/org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar:/home/user/.m2/repository/javax/javaee-api/6.0/javaee-api-6.0.jar:/home/user/.m2/repository/org/apache/commons/commons-exec/1.3/commons-exec-1.3.jar -m org.apache.bcel.HandleTestCase#testBranchHandle
In the last step, you need to replace "/home/user/.m2" for the correct maven cache folder of your computer.

Including function code snippet form a groovy file in JMeter groovy script

I have a big Groovy script in JMeter and I want few methods to be re-used in different places of my script. Below is what I tried.
This is a groovy script where I have written a function that I want to call from Jmeter.
Tools.groovy
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage){
if(Expected==Actual){
log.info("****Assertion Successful****");
log.info("Actual: "+Actual+" Expected: "+Expected +"\n");
log.info(PassMessage);
}
else{
vars.put("AssertionFailure","true");
AssertionResult.setFailure(true);
vars.put("FailureMsg",vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n"+FailureMessage + " || EXPECTED: "+ Expected + " || ACTUAL: "+Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: "+Actual+"Expected: "+Expected);
}
}
Below is my JMeter Groovy code where I am calling the function.
File sourceFile = new File("D://TestScript//Tools.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
myObject.AssertValues("s","s","asdf","asdf");
The output gives this error, javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: log for class: Tools
This is probably because of 'log' object not available from Groovy. How can I solve this issue?
log shorthand is available only for JSR223 Elements, in order to be able to use it you need to define it manually like it's done in JSR223TestElement class
So amend your code to look like:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage) {
final Logger log = LoggerFactory.getLogger(getClass());
if (Expected == Actual) {
log.info("****Assertion Successful****");
log.info("Actual: " + Actual + " Expected: " + Expected + "\n");
log.info(PassMessage);
} else {
vars.put("AssertionFailure", "true");
AssertionResult.setFailure(true);
vars.put("FailureMsg", vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n" + FailureMessage + " || EXPECTED: " + Expected + " || ACTUAL: " + Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: " + Actual + "Expected: " + Expected);
}
}
And you will be able to use it from Groovy scripts your way:
Also be aware that there is groovy.utilities property which can be used to re-use your custom scripts in __groovy() function, you will need either add the next line to user.properties file:
groovy.utilities=D:/TestScript/Tools.groovy
or pass it via -J command-line argument like:
jmeter -Jgroovy.utilities=D:/TestScript/Tools.groovy -n -t test.jmx -l result.jtl
References:
Configuring JMeter
Overriding Properties Via The Command Line
Apache JMeter Properties Customization Guide

Replace blank spaces from arguments to run command

I'm using Runtime.getRuntime.exec(String) to cut some songs with ffmpeg.
But when my song has a name with a blankspace it doesn't work ...
So before I cut the song, I want to replace every blank space of my songs by "\ ".
I did that :
String in = directory+songs.get(i);
String out = directory+"trimed_"+songs.get(i);
in.replaceAll(" "," \\ ");
out.replaceAll(" ", "\\ ");
String str = "ffmpeg -t 1 -i "+in+" -vcodec copy "+out;
Runtime.getRuntime().exec(str);
But it doesn't replace anything at all when I print str, am I missing something ?
Update : I tried every ideas given bellow and I didn't find a way to fix the problem. Hence, I replaced the blankspaces by "_" and it's working great.
Try
String in = directory+songs.get(i);
String out = directory+"trimed_"+songs.get(i);
/* in = in.replaceAll("\\s","\\\\ ");
out = out.replaceAll("\\s","\\\\ ");
*/
in = "\"" + in + "\"";
out = "\"" + out + "\"";
String str = "ffmpeg -t 1 -i " + in + " -vcodec copy " + out;
Runtime.getRuntime().exec(str);
System.out.println("Command executed " + str);
Note: I tested this code myself its working fine.
If it still not working then execute the command manually by copying the str from log and trace the error

vb.net how to launch Minecraft?

Okay, I have a problem, I'm creating a launcher for Minecraft. My problem: I get this error messege, when I try launch Minecraft: Error: Could not find or load main class net.minecraft.client.main.Main
My code, I writted this, but not works:
The Detail of code:
Logger as module, my program using this to write information to console.
JavaPaht as string, the Java path is stored in this.
GameLibraries as string too, the libraries stored in this.
MinMemAlloc as string, the minimal allocated memory for java.
MaxMemAlloc as string, the maximal allocated memory for java.
Root as string, this is the root directory of Minecraft.
Here is the full sub to launch game:
Private Sub LaunchGame()
If Not File.Exists(Root + "\versions\" + SelectedGameVersion + "\" + SelectedGameVersion + ".jar") Then
MsgBox("File not found: " + SelectedGameVersion + ".jar")
Else
Logger.Write("Launching Game...")
Logger.SetScrollDown()
Dim Gamelibraries As String = Nothing
For i = 0 To FileList.Count - 1
Gamelibraries += FileList.Item(i) + ";" +
Environment.NewLine()
Next
Logger.WriteWithJumpDown("Libraries loaded: " & Gamelibraries.ToString())
Logger.SetScrollDown()
Logger.Write("Building Process...")
Logger.Write("Received data: ")
Logger.SetScrollDown()
Dim p As New Process()
p.StartInfo.FileName = JavaPath
p.StartInfo.Arguments = " -Xms" + MinMemAlloc + "M -Xmx" + MaxMemAlloc + "M " +
"-Djava.library.path=" + Root + "\versions\" + SelectedGameVersion + "\" + SelectedGameVersion + "-natives -cp " +
Gamelibraries.ToString() +
Root + "\versions\" + SelectedGameVersion + "\" + SelectedGameVersion + ".jar " + mainClass +
" --username=" + UserID +
" --version " + SelectedGameVersion +
" --gameDir " + Root +
" --assetsDir " + Root + "\assets" +
" --assetIndex " + assets +
" --accessToken null" +
" --userProperties {}" +
" --userType mojang" +
" --uuid (Default)"
p.StartInfo.WorkingDirectory = Root
p.StartInfo.CreateNoWindow = False
p.StartInfo.UseShellExecute = False
p.EnableRaisingEvents = True
Application.DoEvents()
p.StartInfo.RedirectStandardError = True
p.StartInfo.RedirectStandardOutput = True
AddHandler p.ErrorDataReceived, AddressOf p_OutputDataReceived
AddHandler p.OutputDataReceived, AddressOf p_OutputDataReceived
p.Start()
p.BeginErrorReadLine()
p.BeginOutputReadLine()
Logger.SetScrollDown()
Button1.Text = "Play"
Button1.Enabled = True
Button2.Enabled = True
Button3.Enabled = True
Button4.Enabled = True
Button5.Enabled = True
End If
End Sub
And my program writing the output into my console, so I write here the output:
[14:34:41 INFO ] Libraries loaded: C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\java3d\vecmath\1.5.2\vecmath-1.5.2.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\net\sf\trove4j\trove4j\3.0.3\trove4j-3.0.3.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\io\netty\netty-all\4.0.15.Final\netty-all-4.0.15.Final.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\google\guava\guava\17.0\guava-17.0.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\mojang\authlib\1.5.16\authlib-1.5.16.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\com\mojang\realms\1.5\realms-1.5.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\lwjgl\lwjgl\lwjgl\2.9.1\lwjgl-2.9.1.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.1\lwjgl_util-2.9.1.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\org\lwjgl\lwjgl\lwjgl-platform\2.9.1\lwjgl-platform-2.9.1-natives-windows.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\net\java\jinput\jinput-platform\2.0.5\jinput-platform-2.0.5-natives-windows.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\tv\twitch\twitch\6.5\twitch-6.5.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\tv\twitch\twitch-platform\6.5\twitch-platform-6.5-natives-windows-64.jar;
C:\Users\ProGamer\AppData\Roaming\.elcplatform\libraries\tv\twitch\twitch-external-platform\4.5\twitch-external-platform-4.5-natives-windows-64.jar;
[14:34:41 INFO ] Building Process...
[14:34:41 INFO ] Received data:
[14:34:41 INFO ]
[14:34:41 INFO ] Error: Could not find or load main class net.minecraft.client.main.Main
[14:34:41 INFO ]
Thanks for help!
You need to have the main class on the path after the jars are included "net.minecraft.client.main.Main" unless mainClass means that already, then I don't know.

Is Runtime.getRuntime().Exec() environment diffrent from cmd env?

I tried to run a jar from my code with the runtime command.The jar connects to another host through RMI.It throughs an exception and exits.
But when I open the jar from cmd it works fine.
The jar gets 5 arguments.
Code :
String runCommand = "java -jar WhiteboardStudent.jar "
+ "192.168.0.3" + " "
+ "2000" + " "
+ "2001" + " "
+ "test" + " 0" ;
final Process proc = Runtime
.getRuntime()
.exec(runCommand,null,new File("util/"));
Command Prompt :
java -jar WhiteboardStudent.jar 192.168.0.3 2000 2001 test 0
The code where the exception is thrown is here :
Object proxy = registry.lookup("RWD");
Whiteboard whiteboard = (Whiteboard)proxy;
I'm just stumped.any ideas?
The function that throws the exception :
Registry registry = LocateRegistry.getRegistry(
hostname, Integer.parseInt(whiteboardPort)
);
String serviceName = "RemoteWhiteboard" + sessionID;
Object proxy = registry.lookup(serviceName);
Whiteboard whiteboard = (Whiteboard)proxy;
int userid = whiteboard.userRegistry(userName, "");
Main mainFrame = new Main(sessions, sessionID,
whiteboard,userid,"");
My suggestion is try the absolute path in your code:
String runCommand = "java -jar /c/users/xxx/WhiteboardStudent.jar "
+ "192.168.0.3" + " "
+ "2000" + " "
+ "2001" + " "
+ "test" + " 0" ;

Categories

Resources