Trying SSH CLI , reading command line method is infinte loop problem!
I am trying excute command and reading result. but reading result part has problem.
below source is a part of my method.
try{
SessionChannelClient sessionChannel = ssh.openSessionChannel();
sessionChannel.startShell();
OutputStream out = sessionChannel.getOutputStream();
String cmd = s + "\n";
out.write(cmd.getBytes());
out.flush();
InputStream in = sessionChannel.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte buffer[] = new byte[255];
String read= "";
while (true) {
String line = br.readLine();
if (line == null)
break;
str += line;
str += "\n";
System.out.print(str); //print result
sessionChannel.close();
in.close();
out.close();
}catch(IOException ee){
System.out.println(ee);
}finally{
System.out.println("=============end cmd=============");
while loop has problem. While statement has infinite loop problem.
why has this problem?
anybody, help me please. Thanks for reading .
Edited by: BreathAir on Aug 5, 2008 12:16 AM
That loop will loop until readLine() returns null, which will only happen when the other end closes its end of the connection, and it will block while no data is available.
Similar Messages
-
Wrong to process command line args in a loop?
I tried to process my command line args like this:
int[] rgb = {0,0,0};
for(int i=1;i<3;i++)
rgb[i-1] = Integer.parseInt(args);
I enter six args where args 1 to 3 are ints and not zero, but rgb[2] always ends up being zero. I had to do away with the loop and write out three assignment statements, but if I had ten or more args that would be a headache! Does anyone know why this is happening? I'm using JDK 1.3.1_15.for(int i=0;i<3;i++)
rgb[i] = Integer.parseInt(args);
Look closely and make sure you understand the differences between my code and yours:
* i starts at 0, not 1
* rgb uses i for index, not i - 1.
Why would you have rgb using i -1 and args using i?
Now, if you have an arg [i]before the RGB args, then it would make sense for args' index to be different than rgb's. In that case, you might have i-1 and i, or i and i+1, etc. depending on how you structure your loop.
The main problem is that you had i=1; i<3, which will go through the loop body for i=1 and i=2 only. Make sure you understand why. -
Command line method to obtain DNS and proxy info?
Hello All,
I have poked around the man pages but am not making any progress on this. I am looking for a command that would query the network to find a) whether there is a DNS server, and b) if there is, what the domain and IP address is. Similarly, if there is a proxy server being advertised, how would I get the IP address and port number info from the command line? The command cannot depend on the machine already being configured for DNS or running DHCP because in the majority of cases where I need it, the machine has been set to a fixed IP address and the customer may not know the DNS & proxy information. Right now I am relying on them going to a Windows system and running the ipconfig /all command.
Any help on this would be apreciated. Thanks,
Mausul.Ok, I tried that, but it seems there is a catch -- I have to first configure the system for DHCP, then the dhcpinfo command will display these values that it obtained from the DHCP server. The problem with that approach is this -- if there is no DHCP server, it will sit there for a long time with the interface "pending command" while it searches. Can I test for the presence of a DHCP server without actually attempting to configure the interface? As I am typing this, I think one way to cheat might be to create a clone of the interface and try to configure the clone for DHCP...
-
Acrobat Reader command line problem
In windows xp professional I'm programatically creating a batch file and executing it (shell command in visual basic) to convert pdf files to Microsoft xps.
The batch command looks like this one:
"C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "D:\MyDir\Microsoft XPS Document\x.pdf" "Microsoft XPS Document Writer" /t "D:\MyDir\Microsoft XPS Document\x.xps".
When the user logged in on the machine is an administrator, acrobat reader does the operation silently. When a normal user (not belonging to administrators group) is logged in on the machine, acrobat reader opens the save as dialog window requiring user interaction.
The normal user has full control over the destination directory. I already tested giving the normal user full control over AcroRd32.exe and over cmd.exe with no success. I also tried in visual basic 2008 executing the command through System.Diagnostics.Process.Start with the exact same curious results.
Can someone help.
Thank you.Hi.
I couldn't find a solution within Adobe for the problem I reported Oct 9, 2012, so I went to a fallback solution aimed to complete the needed stages. I'm posting here the visual basic 2008 code I wrote then. It is not a graceful solution and has some coarse code but was designed as part of an application that must keep processing files without user intervention. The procedure "followAcroRd32PDFtoXPS" must be called after the execution of a batch command like the described in the previous post:
Module fallback
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hwndParent As Integer, ByVal hwndChildAfter As Integer, ByVal lpszClass As String, ByVal lpszWindow As String) As Integer
Declare Function GetDlgCtrlID Lib "user32" (ByVal hDlg As Integer) As Integer
Declare Function SendDlgItemMessage Lib "user32" Alias "SendDlgItemMessageA" (ByVal hDlg As Integer, ByVal nIDDlgItem As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
Const WM_SETTEXT = &HC
Const BM_CLICK = &HF5
Function FileInUse(ByVal filepath As String) As Boolean
Dim f001 As Integer
If System.IO.File.Exists(filepath) Then
Try
f001 = FreeFile()
FileOpen(f001, filepath, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
FileClose(f001)
Catch
Return True
End Try
End If
End Function
'outpfile <-- path to the XPS Document to be created
'starttime <-- system date and time when the batch command line was executed
Sub followAcroRd32PDFtoXPS(ByVal outpfile As String, ByVal starttime As System.DateTime)
Dim p As System.Diagnostics.Process, q As System.Diagnostics.Process, proc() As System.Diagnostics.Process
Dim i As Integer, j As Integer
Dim l As Long, memusage() As Long
Dim t000 As System.DateTime
Dim t999 As System.DateTime
Dim hwnd As Integer, lObjhWndTB As Integer, lObjhWndBu As Integer
Dim nIDDlgItem As Integer
Dim resu As Integer
dim maximumacrobatwaittime = 60 'seconds
dim memoryusageinactivity = 12 'seconds
dim acrord32pdftoxpstimelimit = 12 'seconds
'Identify necessary Adobe Reader process
t000 = DateTime.Now
Do
System.Threading.Thread.Sleep(1000)
i = 0
For Each p In System.Diagnostics.Process.GetProcesses
If LCase(p.ProcessName) = LCase("AcroRd32") Then
If Not p.StartTime < starttime Then
ReDim Preserve proc(i)
proc(i) = p
i = i + 1
End If
End If
Next
If i > 0 Then Exit Do
t999 = DateTime.Now
If DateDiff(DateInterval.Second, t000, t999) > maximumacrobatwaittime Then
Exit Sub
End If
Loop
'Identify necessary window
t000 = DateTime.Now
Do
System.Threading.Thread.Sleep(1000)
hwnd = FindWindow(vbNullString, "Save the file as")
If hwnd <> 0 Then
Exit Do
End If
t999 = DateTime.Now
If DateDiff(DateInterval.Second, t000, t999) > maximumacrobatwaittime Then
Exit Sub
End If
Loop
'Send click message to button save
t000 = DateTime.Now
Do
System.Threading.Thread.Sleep(1000)
lObjhWndTB = FindWindowEx(hwnd, 0, "ComboBoxEx32", "")
If Not lObjhWndTB = 0 Then
nIDDlgItem = GetDlgCtrlID(lObjhWndTB)
resu = SendDlgItemMessage(hwnd, nIDDlgItem, WM_SETTEXT, 0, outpfile)
If resu > 0 Then
lObjhWndBu = FindWindowEx(hwnd, 0, "Button", "&Save")
If Not lObjhWndBu = 0 Then
resu = PostMessage(lObjhWndBu, BM_CLICK, 0, 0)
If Not resu = 0 Then
Exit Do
End If
End If
End If
End If
t999 = DateTime.Now
If DateDiff(DateInterval.Second, t000, t999) > maximumacrobatwaittime Then
Exit Sub
End If
Loop
'Adobe Reader eventually will enter inactivity after printing to XPS Document
ReDim memusage(0)
Do
System.Threading.Thread.Sleep(1000)
ReDim Preserve memusage(UBound(memusage) + 1)
For Each p In proc
p.Refresh()
memusage(UBound(memusage)) = memusage(UBound(memusage)) + p.WorkingSet64
Next
If Not UBound(memusage) < memoryusageinactivity Then
j = 0
l = memusage(UBound(memusage))
For i = UBound(memusage) - 1 To UBound(memusage) - memoryusageinactivity + 1 Step -1
If l = memusage(i) Then j = j + 1
Next
Select Case j
Case memoryusageinactivity - 1
Exit Do
Case Else
End Select
End If
Loop
'Wait for the new XPS Document
t000 = DateTime.Now
Do
System.Threading.Thread.Sleep(1000)
Select Case My.Computer.FileSystem.FileExists(outpfile)
Case True
If Not FileInUse(outpfile) Then Exit Do
Case Else
End Select
t999 = DateTime.Now
If DateDiff(DateInterval.Second, t000, t999) > acrord32pdftoxpstimelimit Then
Exit Do
End If
Loop
'Kill Adobe Reader process
For Each p In proc
p.Refresh()
Try
p.Kill()
Catch ex As Exception
End Try
Next
'Kill eventual MS Windows error reporting system process
For Each p In System.Diagnostics.Process.GetProcesses
If LCase(p.ProcessName) = LCase("WerFault") Then
If LCase(p.MainWindowTitle) = LCase("Print driver host for 32bit applications") Then
For Each q In System.Diagnostics.Process.GetProcesses
If LCase(q.ProcessName) = LCase("splwow64") Then
Try
q.Kill()
Catch ex As Exception
End Try
End If
Next
Try
p.Kill()
Catch ex As Exception
End Try
End If
End If
Next
End Sub
End Module -
Acrobat reader command line switch - password
Hello everybody,
I am a developer for macromedia director applications.
I need to open a password protected PDF-file from within a
director-projector-application with any suitable
xtra-extension (not the
problem discussed here!).
all I would need is the complete command line for acrobat
reader to do
this.
A complete list of command line switches for Acrobat Reader
would be helpful
in respect to further needs.
where can i get this.
By the way, the solution for Windows and Mac OS would be
welcome. Are they
the same?
Thanks
Peter GrambitterHello everybody,
I am a developer for macromedia director applications.
I need to open a password protected PDF-file from within a
director-projector-application with any suitable
xtra-extension (not the
problem discussed here!).
all I would need is the complete command line for acrobat
reader to do
this.
A complete list of command line switches for Acrobat Reader
would be helpful
in respect to further needs.
where can i get this.
By the way, the solution for Windows and Mac OS would be
welcome. Are they
the same?
Thanks
Peter Grambitter -
Read command line arguments with an ActiveX step
Hi
I would like to read the command line parameters from TestStand startup. I did find an ActiveX resulting in a Object Reference (See Locals.CommandsRef). How do I use this reference to really get the arguments and their count? See also screenshot.
Solved!
Go to Solution.
Attachments:
Screenshot.jpg 160 KBHi Paulus,
Via this link, you find an forumthread that describes the same issue. testStand does not support this, but there is a workaround. Attached you find the code.
The attachment includes a LV vi with the command line. If you doen't use Labview, here is the command line:
C:\Program Files (x86)\National Instruments\TestStand 2012\Bin\SeqEdit.exe /goto "Parameter1 = test" /runEntryPoint "Test UUTs" D:\Testsequence.seq
Regards,
Bas
Attachments:
Command line TestStand.zip 10 KB -
Adobe reader command line search
Hello everyone,
I am opening a PDF file using command line arguments and perform a search.
My command looks like this:
"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /A search="word" "C:\File.pdf"
The command is working, but I have the issue that it looks like the search is only performing with option "Match whole words only".
Does anybody know if I can change this option for command line search to get all search results?
Thanks in advance.
Regards,
ajay311Does anyone have an idea?
Thanks! -
How to read the DOS command line by JAVA.
for example when i type on DOS DIR, want to save all output to Text file.
Thanks and best regardsI found somthing to help, but i need to make a process which let me to type a command into the Concole and the output will appeare like i am working with Dos Wndows ( Start--> Run--> cmd)
Thanks and best regards -
Is there a command line method for publishing/deploying reports?
Is it possible to publish/deploy reports using the command line?
Also, it is possible to change the datasource for a report via some command line option?
I am developing the reports locally (Win XP), and then checking them into source control. They need to be deployed to a BO Server for Dev, Test and Prod.
I would like to be able to create a script to deploy the reports into the different environments.
In addition, the datasource needs to be changed before deploying to TEST (since it is on the same server as DEV, just a different port). Having to manually open each report and change the datasource as the reports are migrated could get to be time consuming as the number of reports increases.
Thanks for any suggestions.
PaulHi Paul,
No, but you can do all of this using one of our SDK's. Look for samples above or from this WIKI:
Root Page
http://wiki.sdn.sap.com/wiki/display/BOBJ/BusinessObjectsHome
Enterprise Samples (including managed and unmanaged ras)
http://wiki.sdn.sap.com/wiki/display/BOBJ/BusinessObjectsSDKSampleApplications
Non-Enterprise Samples
http://wiki.sdn.sap.com/wiki/display/BOBJ/CrystalReportsSDKSampleApplications
Exporting Samples (RAS)
http://wiki.sdn.sap.com/wiki/display/BOBJ/NETRASSDK+Samples#NETRASSDKSamples-Exporting%2FPrinting
Thank you
Don -
Comparing input from command line to a String token problem
Hi,
I want to compare my input from the command line to a token.
my command line looks like "java myProgram george bush president washington"
The next command could be "java myProgram geoge president washington"
Basically I have a text file which has a name, job and location field. The text file looks as follows
jim, farmer, chicago
paul, builder, texas,
george bush, president, washington
I am using string tokenizer with a "," as my field delimiter.
My lecturer wants me to take the input from the command line so applets are out of the question. However even though there are 3 fields, args.length() could equal 4 because "george bush" is only the name but george is args[0] and bush is args[1]. Is there a way to have a delimiter on the command line instead of a space such a ",". Can anyone see any other way around this?
Thanks1982. The year of.....wait for it.....
Jack And Diane
Tainted Love
Key Largo
Open Arms
Do You Believe In Love
Gloria
Working For the Weekend and of course the GREATEST song of 1982...
drum roll please......
Heat Of The Moment. -
What do these Reader command line parms mean?
--channel=4956.0037FA0C.303535326
--type=renderer
/o /eo /l /b /w 984644 /id 1476
TIA, PeteThat did the job!....Thanks so much!!!
seeren wrote:
Those indicate control surfaces. Go into control surface setup to change color or delete those which you may have inadvertantly configured or don't use anymore. Right click on the header to configure header and deselect the box that shows those, if you want.
Message was edited by: Torrid41 -
Making a Java Command Line Bot...Loop?
Okay, so I'm working on just a fun bot, I have two questions:
1. Is there any function to get a random number, 1-5 or something like PHP: rand(1,5);
2. Okay, so I have some things that they can type, but I want them to be able to keep talking instead of having to do "java bot" or, currently for me, "java test" so I think I need a loop? If so, how would I go about this, it would quit if you said bye, c ya, see ya, anything along those lines...like the things I made.
My Code:
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
InputStreamReader isr;
BufferedReader input;
String userentry;
isr = new InputStreamReader(System.in);
input = new BufferedReader(isr);
System.out.println("Please type something and then hit enter!");
userentry = input.readLine();
if((userentry.equals("Hey"))||(userentry.equals("hey"))) {
System.out.println("Hey! Nice to see you again!");
} else if((userentry.equals("Sup?"))||(userentry.equals("sup"))) {
System.out.println("Not a lot, how 'bout you?");
} else if((userentry.equals("Bye"))||(userentry.equals("bye"))||(userentry.equals("c ya"))||(userentry.equals("peace"))) {
System.out.println("See ya later!");
} else {
System.out.println("I don't understand: " + userentry);
}Not the whole thing:
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
InputStreamReader isr;
BufferedReader input;
String userentry;
isr = new InputStreamReader(System.in);
input = new BufferedReader(isr);
while (true) { //loops forever
System.out.println("Please type something and then hit enter!");
userentry = input.readLine();
if((userentry.equals("Hey"))||(userentry.equals("hey"))) {
System.out.println("Hey! Nice to see you again!");
} else if((userentry.equals("Sup?"))||(userentry.equals("sup"))) {
System.out.println("Not a lot, how 'bout you?");
} else if((userentry.equals("Bye"))||(userentry.equals("bye"))||(userentry.equals("c ya"))||(userentry.equals("peace"))) {
System.out.println("See ya later!");
break; //exits the loop
} else {
System.out.println("I don't understand: " + userentry);
input.close();
isr.close();
} -
Consistent error when trying to install Command Line Tools
Hi there,
after downloading XCode from the App-store without problems, I then tried to add the Command Line Tools via the Preference/Download/Components menu.
When it comes to install the downloaded package, Xcode states "An error occured while extractng files from DevSDK.pkh", and thats about it. Re-installed Xcode, same result. Downloaded the image for the CL-utilities by hand, several versions including older ones, with the same result. The error message in /var/log/install is not very enlighning (for me)
NSUnderlyingError = "Error Domain=BOMCopierFatalError Code=1 \"The operation couldn\U2019t be completed. FinishStreamCompressorQueue error\" UserInfo=0x7ff9e1ec9ae0 {destinationPath=/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/Cleanup At Startup/PKInstallSandboxManager/1.sandbox/Root, offset=1156350, type=BOMCopierFatalError, sourcePath=/var/folders/2f/vqq1hf8d0851_5ty12s5g0ym0000gp/T/attached-image-2b66 48c01a1f4d20c9a96b45cf50d1e78e216eb4/Command Line Tools (Mountain Lion)/Packages/DevSDK.pkg, NSLocalizedFailureReason=FinishStreamCompressorQueue error}";
PKInstallPackageIdentifier = "com.apple.pkg.DevSDK"
I am a bit stuck here (and in desperate need of a c++ compiler). Any suggestions what to do ?the last entry in the list you provided is "zz" so ...
if you look at the second path in the error message (bolded)...:
/var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/Cleanup At Startup/PKInstallSandboxManager/1.sandbox/Root
you will see that the path matches. If you don't feel compfortable navigating via the terminal you can also navigate via the finder and go directly to this folder by selecting the menu item "Go > Go To Folder...":
then enter the path "/var/folders"
you will see the "zz" folder in there. you can open that and continue until you can see the folder "zyxvpxvq6csfxvn_n0000000000000"
Here is view from the terminal and the Finder of the same structure:
I have that same folder:
select this folder and delete (I think you will have to authenticate to remove).... sorry I am not going to remove since things are working on my end.
locate the other folder and do the same. -
Design Question - Command Line Argument Processor
Folks,
I'm a java and OO newbie... I've been going through Sun's java tutorials
I've "enhanced" Sun's RegexTestHarness.java (using Aaron Renn's gnu.getopt package) to expose the various Pattern.FLAGS on the command line.
Whilst it does work the arguement processing code is awkward so I want to rewrite it... but I'm pretty new to OO, so before I spend days hacking away at a badly designed ArgsProcessor package I thought I'd run my deign ideas past the guru's... and atleast see if my ideas are impossible, or just plain bad.
Any comments would be greatly appreciated.
The starting point is RegexTestHarness.java/**
*@source : C:\Java\src\Tutorials\Sun\RegexTestHarness.java
*@compile : C:\Java\src\Tutorials\Sun>javac -classpath ".;C:\Java\lib\java-getopt-1.0.13.jar" RegexTestHarness.java
*@run : C:\Java\src\Tutorials\Sun>java -classpath ".;C:\Java\lib\java-getopt-1.0.13.jar" RegexTestHarness -i
*@usage : RegexTestHarness [-vcixmslud]
//http://java.sun.com/j2se/1.5.0/docs/api/java/io/package-summary.html
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
//http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/package-summary.html
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
//http://www.urbanophile.com/arenn/hacking/getopt/gnu.getopt.Getopt.html
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
* private command line options interpreter class
class Options {
public boolean verbose = false;
public int flags = 0;
public Options(String progname, String[] argv) throws IllegalArgumentException {
LongOpt[] longopts = new LongOpt[9];
longopts[0] = new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v');
longopts[1] = new LongOpt("CANON_EQ", LongOpt.NO_ARGUMENT, null, 'c');
longopts[2] = new LongOpt("CASE_INSENSITIVE", LongOpt.NO_ARGUMENT, null, 'i');
longopts[3] = new LongOpt("COMMENTS", LongOpt.NO_ARGUMENT, null, 'x');
longopts[4] = new LongOpt("MULTILINE", LongOpt.NO_ARGUMENT, null, 'm');
longopts[5] = new LongOpt("DOTALL", LongOpt.NO_ARGUMENT, null, 's');
longopts[6] = new LongOpt("LITERAL", LongOpt.NO_ARGUMENT, null, 'l');
longopts[7] = new LongOpt("UNICODE_CASE", LongOpt.NO_ARGUMENT, null, 'u');
longopts[8] = new LongOpt("UNIX_LINES", LongOpt.NO_ARGUMENT, null, 'd');
Getopt opts = new Getopt(progname, argv, "vcixmslud", longopts);
opts.setOpterr(false);
int c;
//String arg;
while ( (c=opts.getopt()) != -1 ) {
//arg = opts.getOptarg();
//(char)(new Integer(sb.toString())).intValue()
switch(c) {
case 'v': verbose = true; break;
//http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html
case 'c': this.flags |= Pattern.CANON_EQ; break;
case 'i': this.flags |= Pattern.CASE_INSENSITIVE; break;
case 'x': this.flags |= Pattern.COMMENTS; break;
case 'm': this.flags |= Pattern.MULTILINE; break;
case 's': this.flags |= Pattern.DOTALL; break;
case 'l': this.flags |= Pattern.LITERAL; break;
case 'u': this.flags |= Pattern.UNICODE_CASE; break;
case 'd': this.flags |= Pattern.UNIX_LINES; break;
case '?': throw new IllegalArgumentException("bad switch '"+(char)opts.getOptopt()+"'"); //nb: getopt() spits
public String toString() {
StringBuffer s = new StringBuffer(128);
if (verbose) s.append("verbose, ");
if ((this.flags & Pattern.CANON_EQ) != 0) s.append("CANON_EQ, ");
if ((this.flags & Pattern.CASE_INSENSITIVE) != 0) s.append("CASE_INSENSITIVE, ");
if ((this.flags & Pattern.COMMENTS) != 0) s.append("COMMENTS, ");
if ((this.flags & Pattern.MULTILINE) != 0) s.append("MULTILINE, ");
if ((this.flags & Pattern.DOTALL) != 0) s.append("DOTALL, ");
if ((this.flags & Pattern.LITERAL) != 0) s.append("LITERAL, ");
if ((this.flags & Pattern.UNICODE_CASE) != 0) s.append("UNICODE_CASE, ");
if ((this.flags & Pattern.UNIX_LINES) != 0) s.append("UNIX_LINES, ");
if (!s.equals("")) {
s.insert(0,"{");
s.replace(s.length()-2,s.length(),"");
s.append("}");
return(s.toString());
* public regular expression test harness
public class RegexTestHarness {
public static void main(String[] argv){
BufferedReader in = null;
try {
Options options = new Options("RegexTestHarness", argv);
//System.out.println(options);
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("RegexTestHarness");
System.out.println("----------------");
System.out.println();
System.out.println("usage: Enter your regex (none to exit), then the string to search.");
System.out.println("from: http://java.sun.com/docs/books/tutorial/essential/regex/index.html");
String regex = null;
while(true) {
try {
System.out.println();
System.out.print("regex: ");
regex = in.readLine();
if (regex.equals("")) break;
Pattern pattern = Pattern.compile(regex, options.flags);
System.out.print("string: ");
Matcher matcher = pattern.matcher(in.readLine());
if (options.verbose) System.out.printf("groupCount=%d%n", matcher.groupCount());
while (matcher.find()) {
System.out.printf("%d-%d:'%s'%n", matcher.start()+1, matcher.end(), matcher.group());
//start is a zero based offset, but one based is more meaningful to the user, Me.
} catch (PatternSyntaxException e) {
System.out.println("Pattern.compile("+regex+") " + e);
} catch (IllegalStateException e) {
System.out.println("matcher.group() " + e);
} //wend
} catch (IllegalArgumentException e) {
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {in.close();} catch(Exception e){}
}... I haven't got a clue if it's possible, but I want my ArgProcessor.getArgs method to return a hash (keyed on name) of Objects of the requested "mixed" types... for example a boolean, a String, and a String[].
I want the client code of my new fangled ArgProcessor to look something like this:class testArgProcessor {
public static void main(String[] args) {
//usage testArgProcessor [-v] [-o outfile] file ...
try {
HashMap<Arguement> args = ArgProcessor.getArgs( args,
{ //hasArg value, letter, name, type, value, default
{hasArg.NONE, 'v', 'verbose', 'boolean', true, false}
, {hasArg.REQUIRED, 'o', 'outfile', 'String', null, null}
, {hasArg.ARRAY, '', 'filelist', 'String[]', null, null}
if (args.outfile != null) {
out = new BufferedWriter(......);
} else {
out = System.out;
for (String file : filelist) {
if (args.verbose) System.out.println("processingFile: " + file)
... process the file ...
} catch (IllegalArgumentException e) { //from ArgProcessor.getArgs()
System.out.println(e);
}Paul,
What are you trying to do, and why?Sorry I should have made myself a lot clearer...
What I'm really trying to do is learn Java, and good OO design... so I'm going through the Sun tutorials, and I see that the standard Pattern class has a few handy switches, so I wanted to expose them to the command line... which I did using the handy gnu.getopts library...
Are you trying to write a general purpose
command-line processing library?Yes, I'm trying to write a general purpose command-line processing library? one that's "cleaner" to use than the gnu.getopts.
I've been hacking away for a few hours and haven't gotten very far... what I have discovered is that gnu.getopts class is in fact very clever (surprise surprise)... and my idea to "simplify" it's usage leads to loss of flexibility. So, I'm starting to think I'm completely barking up the wrong tree... and that I was somewhat vanglorious thinking that I (a newbie) could improve upon it.
Are you trying to write a command-line app to do
pattern matching?Yep, That too... That's where I started... with an example from Sun's tutorials... where it's used to parse a long series of patterns and strings, exploring java's regex capabilities.
I think I'll just give up on "improving" on gnu.getopts... my options processing code is ugly, and so be it.
Thanx for your interest anyway.
Keith. -
Problem with tokenized input from command line
I am trying to take an input from the command line, parse it to tokens and perform whatever operation is needed depending on the name of the token, on a binary tree of stacks for example, if i type 1 2 1 3 printLevelOrder, then the root of the tree should have 3, 2,1 in the stack, the left child should have 1 and the right child should be empty. and then a level order print of the tree should be performed.
however what is happening when i run this code is the numbers are being put into the right stacks of the tree, but any commands such as printLevelOrder or PrintPopRoot are entering the code that is for placing numbers onto the stack instead of executing that command and skipping past this piece of code.
so my question is, why is the if statement if (word =="printLevelOrder") not being executed when thats whats in the word ?
example input and output shown below code fragment.
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (line != "***") {
System.out.print("> prompt ");
line = in.readLine();
StringTokenizer tokenizer = new StringTokenizer(line," ");
String word = new String();
while (tokenizer.hasMoreTokens()) {
word = tokenizer.nextToken();
boolean notCommand = true;
if (word =="printLevelOrder") {
theTree.printLevelOrder();
System.out.println("(word ==printLevelOrder)");
notCommand=false;
if (word == "printPopLevelOrder") {
theTree.printPopLevelOrder();
notCommand=false;
if (word == "printPopInorder") {
theTree.printPopInorder();
notCommand=false;
if (word == "printPopPreorder") {
theTree.printPopPreorder();
notCommand=false;
if (word == "printPopRoot") {
theTree.printPopRoot();
notCommand=false;
if (word == "***") {
notCommand=false;
if (notCommand == true) {
System.out.println("(notCommand == true)");
boolean notPlaced = true;
int v = 1;
while ((notPlaced==true) && (v < theTree.size())) {
if (theTree.element(v).isEmpty()) {
theTree.element(v).push(Integer.valueOf(word));
System.out.println("Inserting"+word);
System.out.println("in empty stack at location: "+v);
notPlaced=false;
if (notPlaced==true) {
if ( Integer.valueOf(word) >= Integer.valueOf( theTree.element(v).top().toString() ) ) {
theTree.element(v).push(Integer.valueOf(word));
System.out.println("Inserting"+word);
System.out.println("in stack at location: "+v);
notPlaced=false;
v++;
}valid inputs: int value, printLevelOrder, printPopLevelOrder, printPopInorder, p
rintPopPreorder, printPopRoot, *** to quit
prompt 1 3 2 4 2 printLevelOrder(notCommand == true)
Inserting1
in empty stack at location: 1
(notCommand == true)
Inserting3
in stack at location: 1
(notCommand == true)
Inserting2
in empty stack at location: 2
(notCommand == true)
Inserting4
in stack at location: 1
(notCommand == true)
Inserting2
in stack at location: 2
(notCommand == true)
Exception in thread "main" java.lang.NumberFormatException: For input string: "printLevelOrder"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.valueOf(Integer.java:553)
at TreeStack.main(TreeStack.java:73)
Press any key to continue . . .lol aww, shame that you forgot to do that. i had 10 / 10 for mine, and seing as the deadline is now well and trully over,
here is the entire source for anybody who was following the discussion or whatever and wanted to experiment.
additional files needed >
http://users.cs.cf.ac.uk/Paul.Rosin/CM0212/Stack.java
http://users.cs.cf.ac.uk/Paul.Rosin/CM0212/ArrayStack.java
http://users.cs.cf.ac.uk/Paul.Rosin/CM0212/StackEmptyException.java
http://users.cs.cf.ac.uk/Paul.Rosin/CM0212/StackFullException.java
/*TreeStack.java - reads command line input of values and assigns them to stacks in a binary tree and performs
operations on the ADT. valid inputs: <int>, printLevelOrder, printPopLevelOrder,
printPopInorder, printPopPreOrder, printPopRoot. Terminates on invalid input.
Written by George St. Clair.
S/N:0208456 22/11/2005
import java.util.Vector;
import java.io.*;
import java.util.StringTokenizer;
public class TreeStack {
private final int TREE_CAPACITY = 7 + 1;
private final int STACK_CAPACITY = 10;
Vector tree = new Vector(TREE_CAPACITY) ;
//collect input from command line, add values to stacks at nodes of the teee
//and perform required operations on the treestack
public static void main (String [] args) {
//create a tree of stacks
TreeStack theTree = new TreeStack ();
try {
//collect standard input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (line != null) {
System.out.print("");
line = in.readLine();
//tokenise input
StringTokenizer tokenizer = new StringTokenizer(line," ");
String word = new String();
while (tokenizer.hasMoreTokens()) {
//assign word to the token
word = tokenizer.nextToken();
boolean notCommand = true;
//perform operation on treestack depending on what word is
if (word.equals("printLevelOrder")) {
System.out.println("printLevelOrder");
theTree.printLevelOrder();
notCommand=false;
if (word.equals("printPopLevelOrder")) {
System.out.println("printPopLevelOrder");
theTree.printPopLevelOrder();
notCommand=false;
if (word.equals("printPopInorder")) {
System.out.println("printPopInorder");
theTree.printPopInorder();
notCommand=false;
if (word.equals("printPopPreorder")) {
System.out.println("printPopPreorder");
theTree.printPopPreorder();
notCommand=false;
if (word.equals("printPopRoot")) {
System.out.println("printPopRoot");
theTree.printPopRoot();
notCommand=false;
//if word was not a command it must be a number
if (notCommand == true) {
boolean notPlaced = true;
int v = 1;
//starting at the root, find suitable place for number
while ((notPlaced==true) && (v < theTree.size())) {
//if the stack at v is empty, number goes here
if (theTree.element(v).isEmpty()) {
theTree.element(v).push(Integer.valueOf(word));
System.out.println("inserting: "+word);
System.out.println("in empty stack at location: "+(v-1));
notPlaced=false;
//if the stack is not empty
if (notPlaced==true) {
//if the value on the top of the stack is smaller than number, number goes onto the stack
if ( Integer.valueOf(word) > Integer.valueOf( theTree.element(v).top().toString() ) ) {
theTree.element(v).push(Integer.valueOf(word));
System.out.println("inserting: "+word);
System.out.println("in stack at location: "+(v-1));
notPlaced=false;
//if that node was no good, check the next one for suitability
v++;
catch (Exception e) {
//occurs when user inputs something that is neither a command, or a number, or upon EOF, or stack is full
public TreeStack () {
//create the TreeStack ADT by adding stacks in the vector, note vector 0 is instantiated but not used.
for (int i = 1;i<=TREE_CAPACITY;i++)
tree.add(new ArrayStack(STACK_CAPACITY));
public int size() {
//return the size of the tree +1 (as 0 is not used)
return tree.size();
public ArrayStack element (int v) {
//return the ArrayStack at v
return (ArrayStack)tree.get(v);
public int leftChild (int v ) {
//return left child of v
return v*2;
public int rightChild (int v ) {
//return the right child of v
return v*2+1;
public boolean children (int v ) {
//search for children of v and return true if one exists
for (int i =v;i<size();i++) {
if (i/2==v ) {
//left child found at i
return true;
if ((i-1)/2==v ) {
//right child found at i
return true;
//no children found
return false;
public boolean isInternal (int v ) {
//test whether node v is internal (has children)
if (children (v)== true) {
//has children
return true;
return false;
//print the top value in each stack encountered on a level-order traversal of tree
public void printLevelOrder() {
//for every node of tree v
for (int v = 1;v<size();v++) {
if (!element(v).isEmpty() ) {
//print the top value in stack v
System.out.println(" "+element(v).top());
else {
//stack at v is empty
System.out.println(" -");
//pop off and print the top value in each stack encountered on a level-order traversal of tree
public void printPopLevelOrder () {
//pop off and print the top value in stack v
for (int v = 1;v<size();v++) {
//for each node of tree v
if (!element(v).isEmpty() ) {
//if v isnt empty print the top value in stack v
System.out.println(" "+element(v).top());
//pop the top value in the stack at v
element(v).pop();
else {
//stack at v is empty
System.out.println(" -");
//pop off and print the top value in each stack encountered on an in-order traversal of tree
public void printPopInorder () {
printPopInorder (1);
public void printPopInorder (int v) {
boolean isInternal = false;
if (isInternal (v)) {
//use a boolean for isInternal to save on running the method twice
isInternal = true;
//recursively search left subtree
printPopInorder (leftChild(v));
//pop off and print the top value at v
if (element(v).isEmpty() ) {
//stack at v is empty
System.out.println(" -");
else {
//if v isnt empty print the top value in stack v then pop
System.out.println(" "+element(v).top());
element(v).pop();
if (isInternal ) {
//recursively search right subtree
printPopInorder (rightChild(v));
//pop off and print the top value in each stack encountered on an pre-order traversal of tree
public void printPopPreorder() {
printPopPreorder(1);
public void printPopPreorder(int v) {
//pop off and print the top value at v
if (!element(v).isEmpty() ) {
//if v isnt empty print the top value in stack v then pop
System.out.println(" "+element(v).top());
element(v).pop();
else {
//stack at v is empty
System.out.println(" -");
if (isInternal (v)) {
//recursively search left and right subtrees
printPopPreorder (leftChild(v));
printPopPreorder (rightChild(v));
//pop off and print all values from the stack at the root
public void printPopRoot (){
//while the root stack has values left
while (!element(1).isEmpty()) {
//print, then pop
System.out.println(" "+element(1).top());
element(1).pop();
}
Maybe you are looking for
-
Applescript to add a note to multiple contacts
Hi I wonder if someone well versed in Applescript could help me with this? For each contact, I need to add their group names to the existing notes field, something like this: Groups: Work, Christmas card Why do I want to? Because I am moving to Kerio
-
Some dialogs where i have to input text freeze
the problem is only in some compilers. i attach a copy of my code package rail.editor; import rail.model.*; import javax.swing.JOptionPane; import javax.swing.*; import java.beans.*; //Property change stuff import java.awt.*; import java.awt.event.*;
-
Hi, Been using airplay regularly from iPad 2 to Apple TV for streaming video. Suddenly today I cannot see Airplay icon during video play on any device (iphone, imac, ipad, etc). Can't use mirroring either. All devices on same wifi network. Tried powe
-
How to translate Function text matching to fucntion code?
I try to translate Function text matching to Function code in GUI status? Is there any way you know how to solve it?
-
Clean install mavericks and migrate time machine
I have been having lots of trouble with my MacBookPro, 17", late 2009. Seems like it takes forever to boot or to launch apps. I have reinstalled th OS several times and done a full restore from TimeMachine twice. I still see the beachball for hours e