I have this plugin that when installed, extracts some executables at some temporary location, and uses them. Here is my code:
public class StartCheck implements IStartup {
private BufferedReader buf=null;
public static String pathBandwidth;
public static String pathDeviceQuery;
public static String pathKernelLaunchOverhead;
public static String memoryLatency;
public void earlyStartup() {
// This method checks for presence of nvcc when Eclipse starts-up.
String command="nvcc --version";
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(command);
pr.waitFor();
buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
//print-out the nvcc version
System.out.println(buf.readLine());
Preparation.return_val=true;
//extract the executables
Bundle bundle = Platform.getBundle("PTXAnalysis");
URL url_bandwidth = FileLocator.find(bundle, new Path("/Executables/bandWidth.out"), null);
URL url_deviceQuery = FileLocator.find(bundle, new Path("/Executables/deviceQuery.out"), null);
URL url_kernelLaunchOverhead = FileLocator.find(bundle, new Path("/Executables/empty"), null);
URL url_memoryLatency = FileLocator.find(bundle, new Path("/Executables/memLatency.out"), null);
try {
url_bandwidth = FileLocator.toFileURL(url_bandwidth);
url_deviceQuery = FileLocator.toFileURL(url_deviceQuery);
url_kernelLaunchOverhead = FileLocator.toFileURL(url_kernelLaunchOverhead);
url_memoryLatency = FileLocator.toFileURL(url_memoryLatency);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pathBandwidth=url_bandwidth.toString();
pathDeviceQuery=url_deviceQuery.toString();
pathKernelLaunchOverhead=url_kernelLaunchOverhead.toString();
memoryLatency=url_memoryLatency.toString();
}catch (IOException e) {
//disable all commands since no further task can be done, prompt user to install nvcc.
System.out.println("nvcc was not found on this computer. You won't be able to use the energy estimation plug-in");
EnergyEstimator.return_val=false;
Preparation.return_val=false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When I install the plugin, it gives me this location (one of the many), where the executable has been extracted:
/home/limafoxtrottango/.eclipse/org.eclipse.platform_4.4.1_2069420271_linux_gtx_x86_64/configuration/org.eclipse.osgi/460/0/.cp/Executables/bandWidth.out
Now, the problems: I can't find any such directory. I understand that it is a temporary directory, but it does not show-up even if Eclipse is running. I am using one of these paths to run an executable using ProcessBuilder. Here is the code:
public static void runExecutable(){
initializeArray();
path_result="/home/"+System.getProperty("user.name")+"/kernelLaunchOverhead.txt";
String path_executable=StartCheck.pathKernelLaunchOverhead.substring(path_result.indexOf('/'),path_result.lastIndexOf('/')+1); //path to the directory in which the executable is extracted
try {
fw = new FileWriter(path_result);
for(int i=0;i<arr.length;i++){
ProcessBuilder builder=new ProcessBuilder("./empty",Integer.toString(arr[i]));
builder.directory(new File(path_executable));
int av=0;
float sum=0;
while(av<10){
Process pr=builder.start();
stdin = pr.getInputStream();
isr = new InputStreamReader(stdin);
br = new BufferedReader(isr);
sum=sum+Float.parseFloat(line=br.readLine());
av++;
}
fw.write(arr[i]+" "+Float.toString(sum/10));
fw.write("\n");
}
fw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FillArrays(path_result);
BestLineFit();
saveModel("/home/"+System.getProperty("user.name")+"/KernelLaunchOverheadModel.txt");
}
On invoking this function, nothing happens. It does not even throw any FileNotFound exceptions. Normally, it should have found the executable in the directory, and run it. But after installing the plugin, nothing happens.
To re-iterate, the class StartCheck is successfully showing to me the path to which the executables have been extracted. But those paths do not exist anywhere on my system.
Directories starting with . (such as the .eclipse in the path you show) are hidden on Linux and macOS systems.
You can see them from the command line using ls -a
Related
I'm trying to add a plugin system where people can install their own custom looks and feels. I'm not sure how I'd actually install it so it could be found by going through UIManager.getInstalledLookAndFeels()?
I've tried this:
public static void registerPlugins()
{
File[] files = pluginDir.listFiles();
for(int i = 0; i < files.length; i++)
{
if(files[i].getName().endsWith(".config"))
{
System.out.println("Found plugin");
File jarfile = new File(pluginDir,files[i].getName().substring(0,files[i].getName().length()-7)+".jar");
if(jarfile.exists())
{
System.out.println("Found jar");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(files[i]));
String name = reader.readLine(); //Unused for now
String classname = reader.readLine();
reader.close();
reader = null;
URL url = jarfile.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class<?> lafClass = cl.loadClass(classname);
final LookAndFeel laf = (LookAndFeel)lafClass.newInstance();
UIManager.getLookAndFeelDefaults().put("ClassLoader", cl);
UIManager.installLookAndFeel(laf.getName(), laf.getClass().getName());
} catch (Exception e) {
try {
if(reader != null)
reader.close();
} catch (Exception es) {
// TODO Auto-generated catch block
e.printStackTrace();
}
e.printStackTrace();
}
}
}
}
}
This gets the config files from the plugins folder that have contents like
Web look and feel
com.alee.laf.WebLookAndFeel
and loads the respective jar. So far, all it did was crash cause it could not load components, or list the look and feel while also not being able to find it, so like the list SHOWS "WebLookAndFeel" but trying to use com.alee.laf.WebLookAndFeel causes an exception.
Any advice?
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.
...
String path = null;
String filename;
//choose where to backup
private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"_"+date+".sql";
jTextField1.setText(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
jLabel1.setText("Backup Created Success!");
} else {
jLabel1.setText("Can't create backup.");
}
} catch (Exception e) {
}
}
You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!
java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
this will run any shell script on Linux server. Test it on windows ... shoud work too
public static int executeExternalScript(String path) throws InterruptedException, IOException {
ProcessBuilder procBuilder = new ProcessBuilder(path);
procBuilder.redirectErrorStream(true);
Process process = procBuilder.start();
BufferedReader brStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = brStdout.readLine()) != null) { logger.info(line); }
int exitVal = process.waitFor();
brStdout.close();
return exitVal;}
I have a java program to run export command. While executing the export, it tries to look for the export directory in my local machine instead of Hdfs. The same program works fine for import. I have checked the file exists on hdfs.
Please help.
Below is the code I am executing:
public void executeSqoopLoad() throws UnsupportedEncodingException{
SqoopOptions options = new SqoopOptions();
String driver = "oracle.jdbc.driver.OracleDriver";
//options.setDriverClassName(driver);
options.setUsername(“user");
options.setPassword(“pass");
options.setConnectString("jdbc:oracle:thin:#host:1522:rptdev");
Configuration configuration = new Configuration(false);
Resource configResource;
try {
configResource = FileUtils.getFileResource("/Users/Moiz/git/jef/hadoop/hdfs-site.xml");
configuration.addResource(configResource.getInputStream());
configResource = FileUtils.getFileResource("/Users/Moiz/git/jef/hadoop/core-site.xml");
configuration.addResource(configResource.getInputStream());
FileSystem dfs = FileSystem.get(configuration);
String[] uriSplit = dfs.getUri().toString().split(":");
String newUri = uriSplit[0]+":"+uriSplit[1];
dfs.setWorkingDirectory(new Path(newUri+"/tmp"));
System.out.println(dfs.getWorkingDirectory());
System.out.println("Exists = " + dfs.exists(dfs.getWorkingDirectory()));
DateTime dt = new DateTime();
options.setCodeOutputDir("/tmp");
options.setClassName("SqoopLoad_"+null+dt.getYear()+dt.getMonthOfYear()+dt.getDayOfMonth()+dt.getMillisOfDay());
options.setVerbose(true);
// HDFS options
options.setExportDir(dfs.getWorkingDirectory()+"/TestDirectory");
System.out.println("Exists = " + dfs.exists(new Path(options.getExportDir())));
options.setInputFieldsTerminatedBy('\u0005');
options.setTableName(“SCHEMA.TEST_SQP");
options.setNumMappers(1);
options.setDirectMode(true);
System.setProperty(Sqoop.SQOOP_RETHROW_PROPERTY, "rethrow");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int ret = 100;
try{
ret = new ExportTool().run(options);
}catch (Exception e) {
System.out.println("Debug");
e.printStackTrace();
}
System.out.println("return code "+ ret);
}
java.lang.RuntimeException: java.io.FileNotFoundException: File
/tmp/TestDirectory/part-m-00000 does not exist
I got it to work. Had to re-import the sqoop jars through maven.
Java is new to me.
I am executing a batch file using Runtime.getRuntime.exec(filename.bat) and this batch file executes a commandant encrypt.password -Dvalue=somevalue>log.txt and redirects its output to a log.txt file.
Problem that I am facing is batch file is working fine if I run it manually however when program executes it ,it just creates blank 'log.txt'
Content of mybat.bat batch file is as below:
cd/
c:
cd c:/ant_builds/thinclient
ant encrypt.password -Dvalue=someValue >C:/log.txt
Java code is as below:
Process p=Runtime.getRuntime.exec("C:\mybat.bat");
p.waitFor();
It seems that after creating the log file,meantime command is executing control comes out from process.
I have read almost 50 threads here however did not get the solution. Please help me out.
Use ProcessBuilder to create your process and call redirectOutput(File) to redirect and append output to a file.
Try this code:
public class Test {
ProcessBuilder builder;
Path log;
public Test() {
try
{
log = Paths.get("C:\\log.txt");
if (!Files.exists(log))
{
Files.createFile(log);
}
builder = new ProcessBuilder("ant", "encrypt.password", "-Dvalue=someValue");
builder.directory(Paths.get("C:\\ant_builds\\thinclient").toFile());
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(log.toFile()));
builder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
For jdk 1.6 or less, use the following code:
public class Test {
ProcessBuilder builder;
Path log;
Process process;
BufferedReader br;
PrintWriter pw;
Charset charset = Charset.forName("UTF-8");
public Test() {
try {
log = new File("C:\\log.txt");
if (!log.exists()) {
log.createNewFile();
}
builder = new ProcessBuilder("ant", "encrypt.password","-Dvalue=someValue");
builder.directory(new File("C:\\ant_builds\\thinclient"));
builder.redirectErrorStream(true);
process = builder.start();
br = new BufferedReader(new InputStreamReader(process.getInputStream(),charset));
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(log, true), charset));
(new Thread() {
public void run() {
try {
while (process.isAlive()) {
String s = null;
while ((s = br.readLine()) != null) {
pw.print(s);
pw.flush();
}
}
br.close();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
I'm not sure about the order and list of ProcessBuilder arguments so try to play with them to get your code working.
You can also read commands from a common file and redirect output and erros to a sepearate files. Redirect.appendTo is to avoid the process from overiting the existing logs.
Try this code:
try {
File commands = new File("D:/Sample/Commands.txt");
File output = new File("D:/Sample/Output.txt");
File errors = new File("D:/Sample/ErrorsLog.txt");
ProcessBuilder pb = new ProcessBuilder("cmd");
System.out.println(pb.redirectInput());
System.out.println(pb.redirectOutput());
System.out.println(pb.redirectError());
pb.redirectInput(commands);
pb.redirectError(Redirect.appendTo(errors));
pb.redirectOutput(Redirect.appendTo(output));
pb.redirectInput();
pb.redirectOutput();
pb.redirectError();
pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.