How to make infinite stream (bash) into java args from console? - java

consider the following java program:
class PrintName{
public static void main(String[] args){
System.out.println("Hi " + args[0]);
}
}
Now I just compile and execute it from console (I'm on Ubuntu server):
~$:javac PrintName.java
~$:java PrintName "Fernando"
I get the next output:
Hi Fernando
I know there are commands like 'yes' in Linux, with which I can get infinite stream of data. My idea is to do something like this:
yes "Fernando" | java PrintName >> my_file.txt
I want to be able to pass "infinite" Fernando's to my program and have it run infinitely many times, then be able to manipulate the STDO to redirect to some file.
I don't know if I explained it clearly, sorry for my poor handling of the English language. Thank you very much for your time.

This is where you want the xargs command:
yes Fernando | xargs java PrintName
xargs takes each line of stdin, and passes it as command line arguments to the given command.
To redirect it to a file, you can wrap that in a grouping construct:
{ yes Fernando | xargs java PrintName; } >> my_file.txt

Related

Java Runtime.exec() works for some command but not others [duplicate]

This question already has an answer here:
Why does Runtime.exec(String) work for some but not all commands?
(1 answer)
Closed 10 months ago.
I am doing an exercise related to Runtime.exec(), I understand that Runtime.exec is not a shell interpreter, that's why I execute "bash -c 'command'" instead, but for some reason, I can execute commands like ls bash -c 'ls' but not echo or redirection or multiple commands. These does not work:
bash -c 'echo 1234'
bash -c 'ls > abc'
bash -c 'ls;id'
bash -c 'ls -al'
Here is my java code:
import java.util.*;
import java.io.*;
public class runtime {
public static void main(String args[]) throws Exception{
String cmd = args[0];
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
OutputStream os = p.getOutputStream();
InputStream in = p.getInputStream();
DataInputStream dis = new DataInputStream(in);
String disr = dis.readLine();
while ( disr != null ) {
System.out.println("Out: " + disr);
disr = dis.readLine();
}
}
}
I run the above commands with the syntax:
java runtime "bash -c 'command'"
This works:
$ java runtime "bash -c 'ls'"
bash -c 'ls'
Out: Main.class
Out: Main.java
Out: runtime.class
Out: runtime.java
I am using openjdk 11.0.15 on Ubuntu 20.04 and zsh.
Can anyone tell me why Runtime doesn't work in this case? Thank you!
Because of shell parsing.
These are all concepts that the OS just does not have:
The concept of 'every space separates one argument from another (and the command from the list of arguments'). The concept that a single string can possibly run anything, in fact; at the OS level that's just not what the 'run this thing' API looks like. When you type commands on the command prompt, your shell app is 'interpreting' these strings into a command execution request.
The concept of figuring out that bash means /bin/bash, i.e. $PATH resolution.
The concept that *.txt is supposed to refer to all files that ends in .txt.
The concept that $FOO should be replaced with the value of the environment variable 'FOO'
The concept that ; separates 2 commands, and it's supposed to run both.
The concept that single and double quotes escape things. "Escape things" implies that things can cause interpretation to happen. The OS interprets nothing, therefore there's nothing to escape. Obvious, then, that the OS doesn't know what ' is, or ".
That >foo means: Please set the standard output of the spawned process such that it sends it all to file 'foo'.
In windows shells, that # in front of the command means 'do not echo the command itself'. This and many other things are shellisms: /bin/bash does that, maybe /bin/zsh does something else. Windows's built in shell thing definitely is quite different from bash!
Instead, an OS simply wants you to provide it a full path to an executable along with a list of strings, and pick targets for standard in, standard out, and standard err. It does no processing on any of that, just starts the process you named, and passes it the strings verbatim.
You're sort of half there, as you already figured out that e.g. ls >foo cannot work if you execute it on its own, but it can work if you tell bash to execute it. As ALL of that stuff in the above list? Your shell does that.
It gets more complicated: Turning *.txt into foo.txt bar.txt is a task of bash and friends, e.g. if you attempted to run: ls '*.txt' it does not work. But on windows, it's not the shell's job; the shell just passes it verbatim to dir, and it is the command's job to undo it. What a mess, right? Executing things is hard!
So, what's wrong here? Two things:
Space splitting isn't working out.
Quote application isn't being done.
When you write:
bash -c 'ls >foo'
in a bash shell, bash has to first split this up, into a command, and a list of arguments. Bash does so as follows:
Command: bash
arg1: -c
arg2: ls >foo
It knows that ls >foo isn't 2 arguments because, effectively, "space" is the bash operator for: "... and here is the next argument", and with quotes (either single or double), the space becomes a literal space instead of the '... move to next argument ...' operator.
In your code, you ask bash to run java, and then java to run bash. So, bash first does:
cmd: java
arg1: bash -c 'ls >foo'
With the same logic at work. Your java app then takes that entire string (that's args[0]: "bash -c 'ls >foo'"), and you then feed it to a method you should never use: Runtime.exec(). Always use ProcessBuilder, and always use the list-based form of it.
Given that you're using the bad method, you're now asking java to do this splitting thing. After all, if you just tell the OS verbatim, please run "bash -c 'ls >foo'", the OS dutifully reports: "I'm sorry, but file ./bash -c ;ls >foo' does not exist", because it does not processing at all". This is unwieldy so java's exec() method is a disaster you should never use: Because people are confused about this, it tries to do some extremely basic processing, except every OS and shell is different, java does not know this, so it does a really bad job at it.
Hence, do not use it.
In this case, java doesn't realize that those quotes mean it shouldn't split, so java tells the OS:
Please run:
cmd: /bin/bash (java DOES do path lookup; but you should avoid this, do not use relative path names, you should always write them out in full)
arg1: -c
arg2: 'ls
arg3: >foo'
and now you understand why this is just going completely wrong.
Instead, you want java to tell the OS:
cmd: /bin/bash
arg1: -c
arg2: ls >foo
Note: ls >foo needs to be one argument, and NOTHING in the argument should be containing quotes, anywhere. The reason you write:
/bin/bash -c 'ls >foo'
In bash, is because you [A] want bash not to treat that space between ls and >foo as an arg separator (you want ls >foo to travel to /bin/bash as one argument), and [B] that you want >foo to just be sent to the bash you're spawning and not to be treated as 'please redirect the output to file foo' at the current shell level.
Runtime.exec isn't a shell, so the quotes stuff? Runtime.exec has no idea.
This means more generally your plan of "I shall write an app where the entire argument you pass to it is just run" is oversimplified and can never work unless you write an entire quotes and escaper analyser for it.
An easy way out is to take the input, write it out to a shell script on disk, set the exec flag on it, and always run /bin/bash -c /path/to/script-you-just-wrote, sidestepping any need to attempt to parse anything in java: Let bash do it.
The ONE weird bizarro thing I cannot explain, is that literally passing 'ls' to /bin/bash -c, with quotes intact, DOES work and runs ls as normal, but 'ls *' does not, perhaps because now bash thinks you want executable file /bin/ls * which obviously does not exist (a star cannot be in a file name, or at least, that's not the ls executable, and it's not an alias for the ls built-in). At any rate, you want to pass ls without the quotes.
Let's try it!
import java.util.*;
import java.io.*;
public class runtime {
public static void main(String args[]) throws Exception{
ProcessBuilder pb = new ProcessBuilder();
pb.command("/bin/bash", "-c", "echo 1234");
// pb.command("/bin/bash", "-c", "'echo 1234'");
Process p = pb.start();
OutputStream os = p.getOutputStream();
InputStream in = p.getInputStream();
DataInputStream dis = new DataInputStream(in);
String disr = dis.readLine();
while ( disr != null ) {
System.out.println("Out: " + disr);
disr = dis.readLine();
}
int errCode = p.waitFor();
System.out.println("Process exit code: " + errCode);
}
}
The above works fine. Replace the .command line with the commented out variant and you'll notice it does not work at all, and you get an error. On my mac I get a '127' error; perhaps this is bash reporting back: I could not find the command you were attempting to execute. 0 is what you're looking for when you invoke waitFor: That's the code for 'no errors'.

Want to read Code from Windows Command Skipt(CMD) File and extract Information

a specific directory receives some different files including some .cmd files.
Here is and example of one of these:
X_COMMAND=DELETE_DOCUMENT
X_DOCIDENTIFICATION=FREE
DTY=MSDS
X_DELIMITER=;
X_FollowingFields=STA;DTY;PRN;SID;CTY;LAN;VKG
V;MSDS;340000021613012300;800000000160;ES;E;ES00
I want to work with the last 2 lines of Code to extract Data:
String xyz = (the command to get 340000021613012300);
The Question is: How do I get this Data?
I have tried to look this up, but did not find anything regarding this issue. If you can help me with this or redirect me to the information I look for I would appreciate that.
Thank you for your time helping me here.
Here is one way to do it. If you are on a supported Windows system, PowerShell will be available.
FOR /F %%A IN ('powershell -NoLogo -NoProfile -Command ^
"(Get-Content -Path "C:\src\t\Get-LastLineData.txt" |" ^
"Select-Object -Last 1).Split(';')[2]"') DO (
SET "xyz=%%~A"
)
ECHO %xyz%
If your script could be written in PowerShell, it would just be:
$xyz = (Get-Content -Path "C:\src\t\Get-LastLineData.txt" |
Select-Object -Last 1).Split(';')[2]
Using just cmd:
for /f "tokens=3 delims=;" %%a in (file.ext) do set "xyz=%%a"
echo %xyz%
(assuming you want the third token of the last line)

How to parse file patterns using Apache commons CLI

I'm trying to parse my command line arguments using the apache commons CLI. It might be a bit heavy handed for the example here, but it makes sense in the context of the program I'm creating. I'm trying to read a file pattern filter, similar to what grep uses to select files to process.
My Argument looks like this:
Program --input *.*
I've written a test program to see what the parser is seeing;
public static void main(String[] args) {
Options options = new Options();
options.addOption(new Option(INPUT_FILTER_SHORT, INPUT_FILTER_LONG, true, INPUT_FILTER_DESCRIPTION));
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(options, args);
System.out.println(cmd.getOptionValue(INPUT_FILTER_SHORT));
}
This prints out:
.classpath
If I change my arguments to:
Program --input test.txt
I get the output:
test.txt
I'm assuming that I have to do something to tell apache commons what * is not a special character? I can't seem to find anything about this online.
I'm experiencing this on Windows (7). I'm fairly certain it's the *.* which is causing the issue as when I swap to using patterns that don't use *, the expected pattern shows up.
Your problem isn't really to do with Commons CLI, but to do with how the shell and the Java executable together process the parameters.
To eliminate other factors, and see what's going on, use a short Java program:
public class ArgsDemo {
public static void main(String[] args) {
for(int i=0; i<args.length; i++) {
System.out.println("" + i + ": " + args[i]);
}
}
}
Play with java ArgsDemo hello world, java ArgsDemo * etc. and observe what happens.
On UNIX and Linux:
Java does no special processing of *. However, the shell does. So if you did:
$ mkdir x
$ cd x
$ touch a b
$ java -jar myjar.jar MyClass *
... then MyClass.main() would be invoked with the parameter array ["a","b"] -- because the UNIX shell expands * to files in the current directory.
You can suppress this by escaping:
$ java -jar myjar MyClass * // main() sees ["*"])
(Note that a UNIX shell wouldn't expand *.* to .classpath because this form would ignore "hidden" files starting with .)
On Windows
cmd.exe does not do UNIX-style wildcard expansion. If you supply * as a parameter to a command in Windows, the command gets a literal *. So for example, PKUNZIP *.zip passes *.zip to PKUNZIP.EXE, and it's up to that program to expand the wildcard if it wants to.
Since some release of Java 7, the Java executable for Windows does some wildcard to filename expansion of its own, before passing the parameters to your main() class.
I've not been able to find clear documentation of Java-for-Windows' wildcard expansion rules, but you should be able to control it with quoting, escaping the quotes to prevent cmd.exe interpreting them:
> java.exe -jar myjar.jar MyClass """*.*"""
(Untested as I don't have a Windows box handy, and quoting in cmd.exe is a bit of a beast - do please experiment and either edit the above or leave a comment)

how to use windows default voice using java? [duplicate]

Is there a way to use the MS Speech utility from command line? I can do it on a mac, but can't find any reference to it on Windows XP.
My 2 cents on the topic, command line one-liners:
on Win using PowerShell.exe
PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('hello');"
on Win using mshta.exe
mshta vbscript:Execute("CreateObject(""SAPI.SpVoice"").Speak(""Hello"")(window.close)")
on OSX using say
say "hello"
Ubuntu Desktop (>=2015) using native spd-say
spd-say "hello"
on any other Linux
refer to How to text-to-speech output using command-line?
commandline function using google TTS (wget to mp3->mplayer)
command using google with mplayer directly:
/usr/bin/mplayer -ao alsa -really-quiet -noconsolecontrols "http://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=Hello%20World&tl=en";
on Raspberry Pi, Win, OSX (or any remote) using Node-Red
npm i node-red-contrib-sysmessage
There's a nice open source program that does what you're asking for on Windows called Peter's Text to Speech available here: http://jampal.sourceforge.net/ptts.html
It contains a binary called ptts.exe that will speak text from standard input, so you can run it like this:
echo hello there | ptts.exe
Alternatively, you could use the following three line VBS script to get similar basic TTS:
'say.vbs
set s = CreateObject("SAPI.SpVoice")
s.Speak Wscript.Arguments(0), 3
s.WaitUntilDone(1000)
And you could invoke that from the command line like this:
cscript say.vbs "hello there"
If you go the script route, you'll probably want to find some more extensive code examples with a variable timeout and error handling.
Hope it helps.
There's also Balabolka: http://www.cross-plus-a.com/bconsole.htm
It has a command line tool balcon.exe. You can use it like this:
List voices:
balcon.exe -l
Speak file:
balcon.exe -n "IVONA 2 Jennifer" -f file.txt
Speak from the command-line:
balcon.exe -n "IVONA 2 Jennifer" -t "hello there"
More command line options are available. I tried it on Ubuntu with SAPI5 installed in Wine. It works just fine.
If you can't find a command you can always wrap the System.Speech.Synthesis.SpeechSynthesizer from .Net 3.0 (Don't forget to reference "System.Speech")
using System.Speech.Synthesis;
namespace Talk
{
class Program
{
static void Main(string[] args)
{
using (var ss = new SpeechSynthesizer())
foreach (var toSay in args)
ss.Speak(toSay);
}
}
}
There is a powershell way also:
Create a file called speak.ps1
param([string]$inputText)
Add-Type –AssemblyName System.Speech
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$synth.Speak($inputText);
Then you can call it
.\speak.ps1 "I'm sorry Dave, I'm afraid I can't do that"
rem The user decides what to convert here
:input
cls
echo Type in what you want the computer to say and then press the enter key.
echo.
set /p text=
rem Making the temp file
:num
set num=%random%
if exist temp%num%.vbs goto num
echo ' > "temp%num%.vbs"
echo set speech = Wscript.CreateObject("SAPI.spVoice") >> "temp%num%.vbs"
echo speech.speak "%text%" >> "temp%num%.vbs"
start temp%num%.vbs
pause
del temp%num%.vbs
goto input
pause
Your best approach is to write a small command line utility that will do it for you. It would not be a lot of work - just read text in and then use the ms tts library.
Another alternative is to use Cepstral. It comes with a nice command line utility and sounds light years better than the ms tts.

java return specific value to shell script

public class Test200 {
public static void main (String args []) {
System.out.println("David");
System.out.println("Peter");
}
}
output=$(java Test200)
echo $output
I get the both value which are David Peter. Let say I only want "David" to be returned in shell script ? Any clue ? Thanks.
You don't return "David" and "Peter", you print them to STDOUT. So if you only want to print one of these, just remove the other println call.
You can only return integer values to the shell. This is done by System.exit(status).
Try using grep command so that it will return the expected value alone for multiple values use egrep
output=$(java Test200)
instead use
output=$(java Test200 | grep 'David')
But i didnt tested this code, it should work.
or try this
java Test200 >> outfile
all the SYSOUT will redirect to outfile base on that you can do te operation with external script.

Categories

Resources