How to Execute FreeSWITCH (fs_cli) from a java application - java

I am new to freeswitch, I have tried originate command in freeswitch from fs_cli console and it was working properly. now my requirement is to execute the same from a java application.
I have tried following code
package org.freeswitch.esl.client.outbound.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Call {
Call() throws IOException {
Process pr = Runtime.getRuntime().exec("./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789#192.168.0.198)\"");
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
System.out.print("success");
}
public static void main(String[] args) throws IOException {
Call call;
call = new Call();
}
}
Output
-ERR "originate Command not found!
success
please help me,
fs_cli is at "/usr/local/freeswitch/bin/" location
I have created a symbolic link in my workspace directory.

why don't you use the ESL client? It should provide much more options, and originating a call would be no problem.
Regarding your particular problem, it looks like your program tried to execute "originate" command in the shell, not the ./fs_cli. Probably it needs more Java documentation reading :)

Related

Not able read json file loacted in app's resource folder on azure

I have spring boot app. I am trying to read json file which is located in my resource folder (using class loader). I have deployed my app on azure its giving me error no such file exist and when i print path it is giving me null.
I tried to create a simple Maven project to fix your issue.
My source code structure is like below.
simpleMavenProj
|-src/main/java/Hello.java
|-src/main/resources/hello.json
The content of Hello.java is as below.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Hello {
public static void main(String[] args) throws IOException {
InputStream resourceInputStream = null;
URL resourceURL = Hello.class.getClassLoader().getResource("resources/hello.json");
if(resourceURL == null) {
System.out.println("Get the InputStream of hello.json in IDE");
resourceInputStream = new FileInputStream(Hello.class.getClassLoader().getResource("").getPath()+"../../src/main/resources/hello.json");
} else {
System.out.println("Get the InputStream of hello.json from runnable jar");
resourceInputStream = Hello.class.getClassLoader().getResourceAsStream("resources/hello.json");
}
System.out.println();
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(resourceInputStream));
String line = null;
while((line = br.readLine()) != null) {
builder.append(line+"\n");
}
br.close();
System.out.println(builder.toString());
}
}
And hello.json:
{
"hello":"world"
}
If you are developing in an IDE, run the code and the result is:
Get the InputStream of hello.json in IDE
{
"hello":"world"
}
Else for generating a runable jar file, then to run the jar file via java -jar simpleMavenProj.jar and the result is:
Get the InputStream of hello.json from runnable jar
{
"hello":"world"
}
Hope it helps. Any concern, please feel free to let me know.

Java authentication against local SASL

I'm trying to make a java class in order to authenticate users against local SASL. My saslauthd configuration is like this:
$ cat /etc/sysconfig/saslauthd
# Directory in which to place saslauthd's listening socket, pid file, and so
# on. This directory must already exist.
SOCKETDIR=/run/saslauthd
# Mechanism to use when checking passwords. Run "saslauthd -v" to get a list
# of which mechanism your installation was compiled with the ablity to use.
MECH=pam
# Additional flags to pass to saslauthd on the command line. See saslauthd(8)
# for the list of accepted flags.
FLAGS="-t 1"
Basically it redirects an authentication against PAM. So, if I'm doing for example a test like this.
testsaslauthd -s login -u <user> -p <password>
0: OK "Success."
It is all working correctly.
I now want to manage this mechanism through Java so I compiled something like this:
import java.util.Arrays;
import java.util.List;
import java.io.*;
public class PamAuthenticator {
public static void main(String args[]) {
String s = null;
try {
Process p = Runtime.getRuntime().exec("testsaslauthd -s "+args[2]+" -u "+args[0]+" -p "+args[1]);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("Exception: ");
e.printStackTrace();
System.exit(-1);
}
}
}
This is correctly working:
$ java -cp .:* PamAuthenticator <user> <password> login
0: OK "Success."
My problem is that I don't want to execute the testsaslauthd command, since this is just a test command. Is there something better and smart I can do in order to try the authentication agains SASL with java?
You are on the right track, not to use the code above. Besides being a test solution it would introduce a serious security problem: command injection.
From Java 1.6 there is an interface called SaslClient. This does exactly what you need. An example on the JDK8 version of it:
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import java.util.HashMap;
public class Test {
public static void main(String[] args) throws SaslException {
String userName = "username";
String password = "password";
SaslClient saslClient = Sasl.createSaslClient(new String[]{"PLAIN"},
null, null, null, new HashMap<>(), callbacks -> {
for (final Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback.class.cast(callback).setName(userName);
continue;
}
if (callback instanceof PasswordCallback) {
PasswordCallback.class.cast(callback).setPassword(password.toCharArray());
continue;
}
throw new UnsupportedCallbackException(callback);
}
});
}
}
Of course you should alter the source of the username and password.

Why any file can be read with using java.security.SecurityManager in java?

I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.
The Main.java file is below
import java.io.*;
import java.util.*;
public class Main {
static private final String INPUT = "in.txt";
public static void main(String args[]) throws Exception {
FileInputStream instream = null;
BufferedReader reader = new BufferedReader(new FileReader(INPUT));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
}
}
and the file /opt/java.policy like below
grant {
permission java.io.FilePermission "./out.txt", "write";
};
Then I run
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?
From the Javadoc:
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.

Cannot open file in java

I am trying to open a text file in java. I am using ubuntu 12.04. Following is my code:
package nlp;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
public class sentence {
public static void main(String[] args) {
System.out.println("hello");
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
}
}
I am using Eclipse for development. It says "FileNotFound". I have put the text file in .class as well as .java folder. Where am I going wrong?
The default execution directory in Eclipse is the root of the project folder. Put the file there or prefix the path with correct underlying folder structure.
you need to put that in try-catch because it throws IOException which is checked Exception.Put the code in try-catch or handle the exception using "public static void main(String[] args) throws IOException"
The file should be in root of the project folder as given below. Your code is working fine.
As Arnaud mentioned try this to find where Java is expecting the file:
System.out.println(new File(".").getAbsolutePath());

Executing Hive Query from Java

I tried to execute a small hive query from Java, but it is failing with below error, bur when I copy the same query and run on terminal it is giving me the result.
Can someone help me on this.
Java Code:
Runtime.getRuntime().exec("hive -e 'show databases;'");
Error thrown:
FAILED: ParseException line 1:5 cannot recognize input near '<EOF>' '<EOF>' '<EOF>' in ddl statement
Regards,
GHK.
I have been working with this Java problem for a while, and I believe I have solved this problem. Basically the reason you are failing is because the environment variables are not ser up properly. put the following in your /home/<username>/.bash_profile file and restart your machine to fix this.
HIVE_HOME=/usr/lib/hive
export HIVE_HOME
PATH=$PATH:$HIVE_HOME/bin/hive
export PATH
This will ensure that they get set up properly.
However while this will get rid of the error it still won't show you a list of databases because the process that runs the hive command will run in the background, not on the console the main program is running from. The following code will let you redirect the outputs of the program to the console that the main program is running from.
package testing.console;
import java.io.IOException;
import java.lang.ProcessBuilder;
import java.util.Map;
import testing.console.OutputRedirector;
//This Works
public class ConsoleTester {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
ProcessBuilder hiveProcessBuilder = new ProcessBuilder("hive", "-e",
"show databases");
String path = processEnv.get("PATH");
Process hiveProcess = hiveProcessBuilder.start();
OutputRedirector outRedirect = new OutputRedirector(
hiveProcess.getInputStream(), "HIVE_OUTPUT");
OutputRedirector outToConsole = new OutputRedirector(
hiveProcess.getErrorStream(), "HIVE_LOG");
outRedirect.start();
outToConsole.start();
}
}
And the OutputRedirector class used to get the output to console.
package testing.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class OutputRedirector extends Thread {
InputStream is;
String type;
public OutputRedirector(InputStream is, String type){
this.is = is;
this.type = type;
}
#Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(type + "> " + line);
}
} catch (IOException ioE) {
}
}
}

Categories

Resources