Compiling Java program with VBScripts? (NetBeans) - java

I have a Java program created that runs VBSscripts after button clicks.
examplescript.vbs
How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here
Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream#4e34904""
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("hello.vbs");
try {
Runtime.getRuntime().exec("wscript " + is);
}
catch( IOException e ) {
System.out.println(e);
System.exit(0);
}
System.out.print(is);

You can run your VBScript as below.
Runtime.getRuntime().exec( "wscript path/to/examplescript.vbs" );

As already mentioned, VBScript is a script and doesn't need compiling. If you want to run code written in VBScript then you can do it this way:
This example uses VBScript to get the Motherboard Serial Number of a computer that is running Microsoft Windows:
try {
// Create a temporary script file named MBSerialxxxxxxxx.vbs
File file = File.createTempFile("MBSerial",".vbs");
// Delete the temporary file when virtual machines terminates
file.deleteOnExit();
try (FileWriter fw = new java.io.FileWriter(file)) {
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
}
// Run the VBScript file....
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
// Read in any output to the command window.
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
// display the output...
System.out.println(line.trim());
}
input.close();
}
catch(IOException e){
e.printStackTrace();
}

Related

mysqldump creates a blank file using java

Goodmorning everyone.
I have a problem with my java program: i would like to create a directory to store a .sql file, which will be generated through mysqldump.exe. I've been trying to follow guides on Stack Overflow or others, but i still can't resolve my problem: directory and .sql file are generated, but the file is totally blank. The best part is that pasting the same command (ctrl+C, ctrl+V) on the command line, it works well and generates an ordinary .sql file for a dump operation.
Please help me. I'm using NetBeans 8.0.2 as IDE, there's my code (there are some variables, like SelectedTable, that allows me to get the current user, password etc. Don't care about them: those parts works and the command is correctly generated):
private void jMenuExternalBackupActionPerformed(java.awt.event.ActionEvent evt) {
LocalDate today = LocalDate.now();
GregorianCalendar now = new GregorianCalendar();
String BackupFolderName = SelectedTable.getMaster().getName()+" "+SelectedTable.getName()+" "+today.getYear()+"_"+today.getMonth().getValue()+"_"+today.getDayOfMonth()+" "+now.get(now.HOUR_OF_DAY)+"_"+now.get(now.MINUTE)+"_"+now.get(now.SECOND);
new File("/HyperSQL/Backups/").mkdirs();
new File("/HyperSQL/Backups/"+BackupFolderName+"/").mkdirs();
String command;
if (SelectedTable.getMasterApplication().getPassword().isEmpty())
command = "mysqldump -u" + SelectedTable.getMasterApplication().getUserLogged() + " " + SelectedTable.getMaster().getName() + ""
+ " > \"C:\\HyperSQL\\Backups\\"+BackupFolderName+"\\backup.sql\"";
else
command = "mysqldump -u" + SelectedTable.getMasterApplication().getUserLogged() + " -p" + SelectedTable.getMasterApplication().getPassword() + " " + SelectedTable.getMaster().getName() + ""
+ " > \"C:\\HyperSQL\\Backups\\"+BackupFolderName+"\\backup.sql\"";
try
{
Process exec = Runtime.getRuntime().exec(new String[]{"cmd.exe","/c", command});
}
catch (Exception e)
{
e.printStackTrace();
}
}

How to run application with parameters from within java application on mac osx

I am writing a small java application to load ZDoom with custom wad files on mac osx and am having trouble executing the command.
I have generated a string within the application that will run ZDoom and load the custom wad, I have tested this by copy-pasting the string from the netbeans breakline debugger and running it directly in terminal.
When I run the code through my application ZDoom does load up but it does so without the custom wad so I believe it is executing without it's arguments.
I have tried two different techniques to run the command:
private void loadZdoom() {
// get selected wad
String wad = (String) wadListComboBox.getSelectedItem();
ProcessBuilder builder = new ProcessBuilder(defaultZdoomInstallPath + "/Contents/MacOS/zdoom", "-file", defaultZdoomWadsPath.replace(" ", "\\ ") + "/" + wad);
builder.redirectErrorStream(true);
try {
Process p = builder.start();
} catch (IOException ex) {
}
}
And
private void loadZdoom() {
// get selected wad
String wad = (String) wadListComboBox.getSelectedItem();
String runCommand = defaultZdoomInstallPath + "/Contents/MacOS/zdoom " + "-file " + defaultZdoomWadsPath.replace(" ", "\\ ") + "/" + wad;
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(runCommand);
} catch (IOException e) {
}
}
What am I doing wrong here?
I figured out what the problem was, I was escaping the space in the path to the wad file as you need to do this in terminal but it seems this is unnecessary in JAVA. All is working as expected now :)

Diff exiting with error code 1

I am trying to apply diff on two folders on the files which have same name.
I am checking name of files and then applying diff over them.
I am also calculating CKJM Metrics for them.
On running it is exiting with error code 1.
Kindly help in running CMD operations through java program .
Error : Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
Exited with error code 1
The common file names are [Inverse Trigono.doc, Limit _ Continuity & Differentia
bility.doc, Parabola.doc, Permutation and combination.doc, Probability.doc, Quad
ratic Equation and Expression.doc, Sequence and Series.doc, Solution of triangle
.doc, Straight Line.doc, TEST PAPER.rar, Vectors.doc]
p.s. I have gone through nearly all similar questions asked here but it seems like This is a bit different.
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListFiles111 {
public static void main(String[] args) {
// Path of Folder 1
String path1 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
// Path of Folder 2
String path2 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing"; 2
File folder1 = new File(path1);
File folder2 = new File(path2);
ArrayList<String> commonfiles = new ArrayList<>();
// Array list of files of folder 1 created.
List<File> filesList1 = Arrays.asList(folder1.listFiles());
// Array list of files of folder 1 created
List<File> filesList2 = Arrays.asList(folder2.listFiles());
for (File f1 : filesList1)
{
if (f1.isFile())
{
for (File f2 : filesList2)
{
if (f2.isFile() && f1.getName().equals(f2.getName()))
{
// Adding common name files in new Array list
commonfiles.add(f1.getName());
try
{
Runtime rt = Runtime.getRuntime();
String[] cmd = new String[5];
cmd[0] = "cmd.exe " ;
cmd[1] = "/C " ;
cmd[2] = "diff ";
cmd[3] = f1.getName() + " ";
cmd[4] = f2.getName();
Process pr = rt.exec( cmd );
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "
+ exitVal);
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
try
{
Runtime rt = Runtime.getRuntime();
String[] cmdd = new String[6];
cmdd[0] = "cmd.exe " ;
cmdd[1] = "/C " ;
cmdd[2] = "java ";
cmdd[3] = "-jar ";
cmdd[4] = "C:\\Users\\hi\\Desktop\\ckjm-1.9\\build\\ckjm-1.9.jar ";
cmdd[5] = "C:\\Users\\hi\\Desktop\\*.class";
Process pr = rt.exec( cmdd );
BufferedReader input = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null)
{
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "
+ exitVal);
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}
}
}
}
System.out.println("The common file names are " + commonfiles);
}
}
Consider using ProcessBuilder instead of Runtime.exec(), it allows you a lot more control than Runtime.exec(), and will allow you to read the stdout and stderr of the utility you are calling, which will help you find the cause of your problem.
Another thing is you pass your files to your utility using File.getName() which is only going to return the name of the file itself, not its complete path. Therefore, your diff utility will interpret those file names according to its working directory, which is probably different from the folder where your files are stored. To solve this, you can either use ProcessBuilder to set the working directory before invoking your utility, or you can use File.getAbsolutePath() or File.getCanonicalPath() to pass the full path.
I'm not sure if it is relevant on Windows, but have you tried removing the trailing spaces from the arguments you pass to Runtime.exec()? Remember that you are not actually building a command string. The arguments that you pass to Runtime.exec() will be passed "as-is" to your operating system, and will end up "as-is" in the created process. in your case, this means that your OS will be looking for a binary called "cmd.exe ", which I'm pretty sure doesn't exist. Same goes for all your other parameters.
Also, Don't call "cmd.exe", call your program directly. What's the point of calling the shell and telling it to open your program. Just open the program directly.
Answering this, even though it is old because I was just looking for something similar.
The return code '1' is from cmd.exe and indicates a "partial" issue according to this https://msdn.microsoft.com/en-us/library/ms194959(v=vs.100).aspx link. It may not be getting as far as running "diff" at all. Or perhaps, as suggested above, cmd.exe cannot find the files to pass as in/output to diff. Again, this would result in diff not actually being called and the return code coming from the shell; not the diff program.
Hth

Using php-cgi with webserver in android

I found that we can run Phpcgi on android by going to this site.I have created a web server in android it works fine and i have installed Php cgi and want to ask that how can i link both so that i can run php scripts as well as HTML pages.Any help will be appreciated.
Update:
In my Request Processor the out is sent like this:
contentType = guessContentTypeFromName(filename);
Date now = new Date( );
out.write("Date: " + now + "\r\n");
out.write("Server: JHTTP/1.0\r\n");
out.write("Content-length: " + theData.length + "\r\n");
out.write("Content-type: " + contentType + "\r\n\r\n");
out.flush( );
guessConte....()
if (name.endsWith(".php")) {
String pathToPhpExecutable = Environment.getExternalStorageDirectory() + "/data" + "/php-cgi";
String phpFile ="" + "/php/myPhpFile.php";
Process process = null;
try {
process = new ProcessBuilder()
.command(pathToPhpExecutable, phpFile)
.redirectErrorStream(true)
.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} finally {
process.destroy();
}
You can use the Process and ProcessBuilder classes to create and execute an command. Keep in mind that depending on the process you want to execute, you may require root permissions and it won't work on non-rooted Android devices.
String pathToPhpExecutable = getFileDir() + "/php-cgi";
String phpFile = getFileDir() + "/php/myPhpFile.php";
Process process = new ProcessBuilder()
.command(pathToPhpExecutable, phpFile)
.redirectErrorStream(true)
.start();
try {
InputStream in = process.getInputStream();
// Read the input stream and i.e. display the results in a WebView
} finally {
process.destroy();
}
Don't be confused by the naming. According to the Process documentation getInputStream() returns the output of the stream connected to the std::out. This will return Code (Json, HTML, plain text) generated by the PHP.
However, chances are you will need root for it to work. Or that the files won't have execution permission (x in Linux) when you unpack them from your APK. But calling chmod or chown (if it's assigned to the wrong user name) will most likely require an rooted Android devices.
Process | Android Developers

Java execute process on linux

I've been struggling for a while now with this problem and i can't seem to fix it.
i already have tried different approaches (Runtime.exec(), ProcessBuiler) but none seem to work.
This is my issue.
I have a laptop which is always on. This laptop runs a java tool connected to an arduino via usb to turn on and off the lights in the house. i have created this program myself, therefore i'm also doing some regular maintenance work on it. Recently i have added a button to restart the program from my html interface (in case i have an update, or if for some other reason i might need to restart the program or i decide to implement auto updating in the near future).
This idea behind this is to start a second instance of the application from the first instance and then System.exit(0) the first instance.
For some reason i'm not able to start a second instance of the application.
Here's some code.
public void shutdown(boolean restart) {
if (this.serial != null) {
this.serial.disconnect();
}
if (restart) {
System.out.println(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
String startupCommand = "java -jar \"" + this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " ") + "\"";
ProcessBuilder builder = new ProcessBuilder();
// String[] command = new String[1];
// command[0] = "-jar \"" + (System.getProperty("user.dir") + "/Home_Automation_Executor.jar") + "\"";
try {
// //System.out.println("Restarting Home Automation with command: " + command[0]);
// System.out.println("Restarting Home Automation with command: " + startupCommand);
// Runtime.getRuntime().exec("bash");
// Process proc = Runtime.getRuntime().exec(startupCommand);
Process proc = builder.command(startupCommand).start();
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("</ERROR>");
int exitVal = 0;
try {
exitVal = proc.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Process exitValue: " + exitVal);
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("Terminating Home Automation");
System.exit(0);
}
java.io.IOException: Cannot run program "java -jar "/Users/NightWalker/Dropbox/Development/Source Code/Java/NightWare Tools/Home Automation/Home Automation Executor/dist/Home_Automation_Executor.jar"": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
at home.automation.executor.Engine.shutdown(Engine.java:186)
at home.automation.executor.webserver.HTTPGenerator._handleActionCommand(HTTPGenerator.java:190)
at home.automation.executor.webserver.HTTPGenerator._generateHTTPPage(HTTPGenerator.java:165)
at home.automation.executor.webserver.HTTPGenerator.getHTTPPage(HTTPGenerator.java:58)
at home.automation.executor.webserver.HTTPRequestHandler.run(HTTPRequestHandler.java:160)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.(UNIXProcess.java:53)
at java.lang.ProcessImpl.start(ProcessImpl.java:91)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
... 5 more
The problem is this:
String startupCommand = "java -jar \"" + this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " ") + "\"";
/* more stuff */ builder.command(startupCommand);
This means Jav will look for a command named java -jar ...stuff with spaces.... But what you want is, that Java looks for a command named java and give that command several parameters.
You should use
/*...*/ builder.command("java", "-jar", jarLocation) /*...*/
Since it is another Java program you might want to consider running it in the same process because it's much easier to communicate between the two programs if they live in the same process. Have you tried running the command outside your program? Does it work? What does the meta-inf.mf file in the jar hold? It might be that the classpath in the meta-inf.mf file isn't relative so any dependent jars can't be found.

Categories

Resources