how to give optarg value b* in getopt class - java

friends, in
gnu.getopt.Getopt.jar
there is some problem i am getting some problem when i am giving b* as option argument then it is taking as bin
Getopt g = new Getopt("cm_log_parser", args, "i:s"); //-D to enable debug log
while((opt = g.getopt()) != -1)
{
switch (opt)
{
case 'f'://To set file name(if above is not specified)
fileNameWithPath = getAndCheckOptArg(fFlag, opt, g);
fFlag = true;
break;
case 'p'://To set the pattern
String pattern = g.getOptarg();
hFlag = true;
break;
case '?':
usage("Invalid option" + opt + " option");
break;
}
}
When I specify -p "b*" it is returns bin , why this is happening?

The shell (I suspect you use Linux, right?) resolves the b* literal to bin (there must be a directory named bin in the current working directory), because it is treated as a wildcard.
Depending on the shell you use, you have to escape the asterisk... For example in bash, use
-p b\*
To escape it to be an asterisk instead of getting resolved by the shell

Related

Process does not exit when launched from Java

I am launching WebTorrent-CLI from within my Java application as a separate process. I am using zt-exec for managing the process. When WebTorrent is launched with the following command, it is supposed to exit after the file at given index (value of --select) has been downloaded.
"D:\downloadmanager\node\webtorrent.cmd" download "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel" --select 0 --out "D://nf/"
As expected, webtorrent-cli does exit after downloading 0th file when the command above is used to launch it from command line. But when I try the same from within my Java app, it completely ignores the --select option and continues downloading other files in the torrent.
Basically, when launched as a process from Java, webtorrent ignores all the options set (--select, --out or whatever). I should mention that there is nothing wrong with the library because recently I've tried replacing it with commons-exec and that solved nothing. Also, to make sure that the right command is passed while starting the process, I'm printing the command right before calling executor.start(). The command above is copied from the output retrieved from printing the command before the process starts.
This is how the process is started:
#Override
public synchronized void start() throws IOException {
if (mWasDownloadStarted || mWasDownloadFinished) return;
mExec.getCommand().listIterator().forEachRemaining(s -> {
System.out.print(s + " ");
});
mExec.start();
setProcessId();
mWasDownloadStarted = true;
mWasDownloadStopped = false;
}
This is how the command is prepared:
private String buildCommand() {
List <String> command = new ArrayList<>();
command.add("\"" + mManager.mWTLocation + "\"");
command.add("download");
command.add("\"" + mManager.mMagnetUrl + "\"");
if (mManager.mFileIndex >= 0) {
command.add("--select " + mManager.mFileIndex);
}
if (mManager.mSaveTo != null) {
command.add("--out \"" + mManager.mSaveTo + "\"");
}
mManager.mExec.command(command);
String cmdStr = "";
for (String s : command) {
cmdStr = cmdStr.concat(s + " ");
}
return cmdStr.trim();
}
What might be wrong?
Okay, so I was able to fix this issue.
The / character following the path specified as value of --out was causing the problem. In order to fix this, I added a line in node_modules/webtorrent-cli/bin/cmd.js to print the arguments passed to webtorrent:
console.log(process.argv)
With the /, output of this line was something like the following:
[ 'D:\\downloadmanager\\node\\node.exe',
'D:\\downloadmanager\\node\\node_modules\\webtorrent-cli\\bin\\cmd.js',
'download',
'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel',
'--select',
'0',
'--out',
'D:\\nf"' ]
Note the " that is included in the path after D:\\nf. When / is removed from the path, the quote disappears and webtorrent behaves as expected.
I doubt that this is a bug in webtorrent. I think zt-exec (or maybe I) was doing something stupid.
Somewhat unrelated, but I think I should also mention that I had to enclose every value for each option with quotes, even the index, to get rid of other nasty errors (e.g.: Error 87, the parameter is incorrect)

Using wildcard in to install a server printer

In java, I am trying to use a cmd command to install a printer from a printer server. Knowing the 3 first letters of the printer name, I would like to use wildcards. I have tried the following command but it doesn't do anything.
Process p3 = Runtime.getRuntime().exec( "CSCRIPT c:\\windows\\System32\\Printing_Admin_Scripts\\en-US\\prnmngr.vbs -l -s \\\\svmsimp1 -a -p \"slj05%\" " );
Read the prnmngr.vbs script. There is next function for parsing the command line (abbreviated, omitted parts replaced by '...'):
' Parse the command line into its components
function ParseCommandLine(iAction, strServer, strPrinter, strDriver _
, strPort, strUser, strPassword)
on error resume next
'...'
dim oArgs
dim iIndex
'...'
iIndex = 0
set oArgs = wscript.Arguments
while iIndex < oArgs.Count
select case oArgs(iIndex)
case "-a"
iAction = kActionAdd
'...'
case "-p"
iIndex = iIndex + 1
strPrinter = oArgs(iIndex)
'...'
case else
Usage(true)
exit function
end select
iIndex = iIndex + 1
wend
'...'
end function
Crucial line strPrinter = oArgs(iIndex) says the script takes printer name from command line parameter -p "printer" as such, with no attempt to treat any wildcards. Neither in this function nor anywhere else in the whole script.
BTW, all parameters to the ParseCommandLine function are passed by reference (default if ByVal and ByRef are omitted).
Conclusion: although you would like to use wildcards, it's impossible with -a argument (add local printer) as in next call
'...'
select case iAction
case kActionAdd
iRetval = AddPrinter(strServer, strPrinter, strDriver _
, strPort, strUser, strPassword)
'...'
we can see (inside AddPrinter function):
'...'
set oPrinter = oService.Get("Win32_Printer").SpawnInstance_
'...'
oPrinter.DriverName = strDriver
oPrinter.PortName = strPort
oPrinter.DeviceID = strPrinter
oPrinter.Put_(kFlagCreateOnly)
'...'
On the other hand, you could parse output from prnmngr -l -s server to get desired printer names.

reading java property value with spaces into one variable

Hello my problem is as follows:
i have a property fiel with a startconfig for external program to run from java:
# Standardauswahl falls keine PlayerType übergeben wurden
Default = 1
# Liste der gültigen PlayerTypes
PlayerTypes = Human,MCTS,TMM,Random,Value
StartConfig = \"C:\\Program Files\\Java\\jdk1.7.0_13\\bin\\javaw.exe\" -Dlog4j.configuration=file:///C:/Users/djdeejay/git/myGit/com.djdeejay.cowTrade.client.standaloneplayer.application/bin/log4j.xml -Dfile.encoding=Cp1252 -classpath [..... some parameter deleted.....] 0.0-RC1.jar;C:\\Users\\djdeejay\\git\\myGit\\de.thWildau.cowTrade.server\\lib\\slf4j-api-1.5.2.jar;C:\\Users\\djdeejay\\git\\myGit\\de.thWildau.cowTrade.server\\lib\\slf4j-log4j12-1.5.2.jar;C:\\Users\\djdeejay\\git\\myGit\\de.thWildau.cowTrade.server\\lib\\log4j-1.2.16.jar com.djdeejay.cowTrade.client.standaloneplayer.application.RandomPlayerApplication %1 %2 %3
when i load the properties as follows
cmd = this.serverSettings.getPlayerTypeSetting("StartConfig");
#Override
public String getPlayerTypeSetting(String key) {
return this.startPlayerTypeSettingsProp.getProperty(key);
}
java cutting startconfig after the first space:
Cannot run program """C:\Program" when its in doublequotes or Cannot run program ""C:\Program":
i have tried several variants with "", with escaping and so on nothing gives my needed result
how do i config getproperty to read until EOL?
cheers
As discussed in the comments, the getProperty call is alright. But the usage as a single string in Runtime.getRuntime().exec(cmd) uses the default whitespace Tokenizer to split the string into command and argument.
To do this yourself, first split the string manually and then pass it to Runtime#exec:
String startCmdLine = this.serverSettings.getPlayerTypeSetting("StartConfig");
int cmdEndPos = startCmdLine.indexOf("javaw.exe") + "javaw.exe".length();
String cmd = startCmdLine.substring(0, cmdEndPos);
String args = startCmdLine.substring(cmdEndPos);
Runtime.getRuntime().exec(new String[]{ cmd, args });
Though I really advise you to take advantage of the JAVA_HOME environment variable if you just want to start a known java binary. That way you can reduce that to a set of parameters in the property file.
Try replacing your spaces with: "\u0020"
Use this:
StringEscapeUtils.escapeXml(String input);
See doc here

how to use property=value in CLI commons Library

I am trying to use the OptionBuilder.withArgName( "property=value" )
If my Option is called status and my command line was:
--status p=11 s=22
It only succeeds to identify the first argument which is 11 and it fails to identify the second argument...
Option status = OptionBuilder.withLongOpt("status")
.withArgName( "property=value" )
.hasArgs(2)
.withValueSeparator()
.withDescription("Get the status")
.create('s');
options.addOption(status);
Thanks for help in advance
You can access to passed properties using simple modification of passed command line options
--status p=11 --status s=22
or with your short syntax
-s p=11 -s s=22
In this case you can access to your properties simply with code
if (cmd.hasOption("status")) {
Properties props = cmd.getOptionProperties("status");
System.out.println(props.getProperty("p"));
System.out.println(props.getProperty("t"));
}
If you need to use your syntax strictly, you can manually parse your property=value pairs.
In this case you should remove .withValueSeparator() call, and then use
String [] propvalues = cmd.getOptionValues("status");
for (String propvalue : propvalues) {
String [] values = propvalue.split("=");
System.out.println(values[0] + " : " + values[1]);
}

Java absolute path adds user.home property when adding quotes - Linux

If I try to use a path that contains spaces in Linux I get FileNotFoundException, obviously. But if I try to add double/single quotes in the path as workaround, I get the same exception.
I was trying to check the reason and I found out that the generated absolute path when using quotes became: the user.home system property + specified path.
For example:
If I use this path:
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs
This is the absolute path I get when trying to use quotes:
/home/db2inst1/"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs"
I also tried to replace the spaces with "\ " instead of adding quotes, but it did not work.
I tried a lot of API's and it happens every time, made this code just for testing:
System.out.println("- regular path: ");
System.out.println(new File(path).getPath());
System.out.println(new File(path).getAbsolutePath());
System.out.println("- quoted path: ");
System.out.println(new File(quotedPath).getPath());
System.out.println(new File(quotedPath).getAbsolutePath());
And this is the output:
- regular path:
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log
- absolute path:
"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log"
/home/db2inst1/"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log"
Does anyone know why this is happening and how to make it work?
From your description it seems that you are calling the File(java.lang.String pathname) constructor.
If so, the String used to represent your path should not use quotes.
Quotes are not considered as special characters in the abstract pathname definition, as described in the java.io.File documentation.
An abstract pathname has two components:
An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX >root directory, or "\\" for a Microsoft Windows UNC pathname, and
A sequence of zero or more string names.
Since quotes are not special characters, they are considered part of a name.
Example:
public static void main(String[] args) {
File quotes = new File("\"C:\\myFolder\"");
File noQuotes = new File("C:\\myFolder");
System.out.println("Absolute path with quotes:" + quotes.getAbsolutePath());
System.out.println("Absolute path without quotes:" + noQuotes.getAbsolutePath());
System.out.println("Equal: " + quotes.equals(noQuotes));
File empty = new File("");
File emptyQuotes = new File("\"\"");
System.out.println("Empty path with quotes:" + empty.getAbsolutePath());
System.out.println("Empty path without quotes:"
+ emptyQuotes.getAbsolutePath());
System.out.println("Equal: " + empty.equals(emptyQuotes));
}
will produce the following output when run in C:\temp on Windows:
Absolute path with quotes:C:\temp\"C:\myFolder"
Absolute path without quotes:C:\myFolder
Equal: false
Empty path with quotes:C:\temp
Empty path without quotes:C:\temp\""
Equal: false
In windows a file name without blanks and the same quoted should refer to the same file (or folder). For instance if we have a folder called c:\uni2 both command lines
dir c:\uni2
dir "c:\uni2"
should give the same result. But in java
String rename;
boolean ya;
File f1 = new File ("C:/UNI2"); // given that exists and it is a directory
ya = f1.exists(); // true
ya = f1.isFile(); // false
ya = f1.isDirectory(); // true
rename = f1.getAbsolutePath(); // "C:\\UNI2"
f1 = new File ("\"C:/UNI2\""); // in windows this should be the same directory!!
ya = f1.exists(); // false
ya = f1.isFile(); // false
ya = f1.isDirectory(); // false
rename = f1.getAbsolutePath(); // "C:\tmp\"C:\UNI2""
which is not the expected behavior (even if it is documented).

Categories