Exception occurred while executing 'put' - java

I'm trying to run an adb shell command programmatically through an app to change the rtt_calling_mode variable value, but I'm running into this error.
Exception occurred while executing 'put':
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:220)
at com.android.server.appop.AppOpsService.checkPackage(AppOpsService.java:2969)
at android.app.AppOpsManager.checkPackage(AppOpsManager.java:7697)
at android.content.ContentProvider.getCallingPackage(ContentProvider.java:954)
at com.android.providers.settings.SettingsProvider.mutateSecureSetting(SettingsProvider.java:1732)
at com.android.providers.settings.SettingsProvider.insertSecureSetting(SettingsProvider.java:1652)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:412)
at android.content.ContentProvider.call(ContentProvider.java:2448)
at android.content.ContentProvider$Transport.call(ContentProvider.java:517)
at com.android.providers.settings.SettingsService$MyShellCommand.putForUser(SettingsService.java:375)
at com.android.providers.settings.SettingsService$MyShellCommand.onCommand(SettingsService.java:277)
at android.os.BasicShellCommandHandler.exec(BasicShellCommandHandler.java:98)
at android.os.ShellCommand.exec(ShellCommand.java:44)
at com.android.providers.settings.SettingsService.onShellCommand(SettingsService.java:49)
at android.os.Binder.shellCommand(Binder.java:929)
at android.os.Binder.onTransact(Binder.java:813)
at android.os.Binder.execTransactInternal(Binder.java:1159)
at android.os.Binder.execTransact(Binder.java:1123)
When running on A10 I was able to run this command perfectly fine and It would change the RTT variable as if I ran the command 'adb shell settings put secure rtt_calling_mode0 1' via the command prompt. But now on an A11 build I receive this error. I'm not sure what could be causing this issue and why it now has an issue with 'put' now. Also not sure where the NullPointerException is coming from either. Does anyone know what could be causing this issue? Below is the code that's throwing the error when its run.
public static String setRealTimeText(int simSlot, int enabled){
String command = "settings put secure rtt_calling_mode" + slot + " " + enabled;
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorOutput = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//get the error output
String s = "";
String outputString = "";
if (errorOutput.readLine() != null) {
while ((s = errorOutput.readLine()) != null) {
outputString += " " + s + "\n";
}
return outputString;
}
//get the console output
while ((s = output.readLine()) != null) {
outputString += "- " + s + "\n";
}
return "RTT was enabled"
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}

If you do not need to issue a shell command, you can programmatically do
Settings.Secure.putInt(getContentResolver(), Settings.Secure.RTT_CALLING_MODE, 1);
But you need root access to do this. Only system apps have permission to change secure settings. This might as well be the cause for the exception when running the shell command.

Related

I execute command in android apk, but I can't get right returns

I execute system command in android app, but I can't get right execute results.
Here is my code:
String cmd = "ls /";
try {
Process p = Runtime.getRuntime().exec(cmd);
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
p.waitFor();
if (p.exitValue() != 0) {
System.out.println(p.exitValue());
Log.d("test",p.exitValue()+" ");
}
String s;
List<String> stdout_list = new ArrayList<>();
while ((s = reader.readLine()) != null) {
Log.d("test", s);
s = s + "\n";
stdout_list.add((String)s);
}
callableGetData.stdout_list = stdout_list;
} catch(Exception e) {
System.out.println(e);
}
cmd, such as ls, will get the wrong answer 1, but if I use ps -A, I will get right answers. The wrong answer 1, may be the exitValue().
What causes this?
See here for example. It says:
Exit status:
...
1 if minor problems (e.g., cannot access subdirectory)
Your app probably does not have sufficient privileges to ls the whole root directory /.

Get the Infornation from getRuntime().exec hat java app hangs up

My code so far:
public static void getTasklist(Table table, Login login){
for(TableItem tableItem : table.getItems()){
try {
if(tableItem.getChecked()){
String command = ("cmd.exe /k tasklist /s " + tableItem.getText(3) + " /U .\\" + SettingsManager.getSetting(login, "Current-User") + " /p " + SettingsManager.getSetting(login, SettingsManager.getSetting(login, "Current-User")+"-PW"));
Process p = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}
catch (IOException e) {
}
}
}
What I want to do: get task list information from a computer and print it to console (later print it to a window maybe). The host name from the computer comes from the checked table (tableItem.getText(3)) and the credentials comes from something I called settingsmanager (SettingsManager.getSetting....).
What works ATM: I get the Information and it got printed to console but after the last line the app hangs up.. I assume that the while loop never breaks but I am not sure about that..

Runtime.getRuntime.exec() Error codes

I am trying to use runtime.getruntime.exec in a Java application.
For quite a while, I've been trying to run different command and I keep getting Error Code 2 which I've found to mean that the file or directory doesn't exist. To test, I attempted to pass a basic command and am getting Error Code 1. Why am I getting this and what does Error Code 1 mean?
Here is my code:
private String executeCommand(String command) {
logger.info("executing command : " + command);
String result = null;
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String line = null;
while ((line = input.readLine()) != null) {
result = result + line;
}
while ((line = stdError.readLine()) != null) {
result = result + line;
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
logger.info("This is the result:" + result);
return result;
Here is how I call it:
String temp = executeCommand("cd $HOME/my-directory/my-subdirectory");
Here is my output:
INFO : programname - executing command : cd $HOME/my-directory/my-
subdirectory
Exited with error code 1
INFO : programname - This is the result:null/usr/bin/cd[8]: $HOME/my-
directory/my-subdirectory: not found
Runtime.getRuntime().exec(command) is expecting an exe file as its first parameter in the passed string. Commands like (cd, echo, etc...) are specific for the Command Line Tool and will not work as directly passed commands. You will need to invoke the command line tool first and then pass your command as it's arguments:
// Invoke Command Line Tool (.exe is optional) (cmd for windows sh for Linux)
// 1st argument indicates you want to run a command (/C for windows -c for Linux)
// 2nd argument is the cmd line command to run (echo)
Runtime.getRuntime().exec("cmd.exe /C echo helloworld");
Runtime.getRuntime().exec("sh -c echo helloworld");
On a separate note. you will want to initialize your result to be an empty string instead of null. Otherwise the word "null" will be prepended to what your printing out.
Do Process pr = rt.exec("cmd /c "+command);

Passing windows credentials programmatically

I have a VB script to which I need to pass username and password.
I want to run this VB script through Java code programmatically.
Is there a way that I can pass the Windows credentials to the VB script in Java programmatically?
You can have the credentials on the OS environment and read them from there:
String credentials = System.getenv().get("encrypted_credentials_or_something");
And then run your command from Java. However, Runtime.exec() won't work in some cases:
When the command is not on the System's PATH
When arguments are involved
When you want to have access to the process output
When you need to be able to kill the process
When you need to check if it terminated successfully or in error (status code != 0 - which is why you write System.exit(int) to terminate a Java application. The System.exit(1), for example, indicates abnormal termination)
That's why I created this utility class to execute external processes with arguments and everything. It works very well for me:
import java.io.*;
import java.util.*;
public class ExternalCommandHelper {
public static final void executeProcess(File directory, String command) throws Exception {
InputStreamReader in = null;
try {
//creates a ProcessBuilder with the command and its arguments
ProcessBuilder builder = new ProcessBuilder(extractCommandWithArguments(command));
//errors will be printed to the standard output
builder.redirectErrorStream(true);
//directory from where the command will be executed
builder.directory(directory);
//starts the process
Process pid = builder.start();
//gets the process output so you can print it if you want
in = new InputStreamReader(pid.getInputStream());
//simply prints the output while the process is being executed
BufferedReader reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int status = 0;
//waits for the process to finish. Expects status 0 no error. Throws exception if the status code is anything but 0.
if ((status = pid.waitFor()) != 0) {
throw new IllegalStateException("Error executing " + command + " in " + directory.getAbsolutePath() + ". Error code: " + status);
}
} finally {
if (in != null) {
in.close();
}
}
}
//Splits the command and arguments. A bit more reliable than using String.split()
private static String[] extractCommandWithArguments(String command) {
StringTokenizer st = new StringTokenizer(command);
String[] cmdWithArgs = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens(); i++) {
cmdWithArgs[i] = st.nextToken();
}
return cmdWithArgs;
}
}

how to write log file while starting services using java

hello everyone i created a java file,in that java i written a code for starting,stoping and restarring a windows service ,in that i want to create a log file and write output of window service as a console please if any one knows give suggestion
i used code for stoping service
public static void stopService(String serviceName) throws IOException,
InterruptedException {
String executeCmd = "cmd /c net stop \"" + serviceName + "\"";
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete: " + processComplete);
if (processComplete == 1) {// if values equal 1 process failed
System.out.println("Service failed");
}
else if (processComplete == 0) {
System.out.println("Service Success");
}
}
Probably the best way to achieve this is Log4J. If you haven't used it before it can seem overbearing, but there are a lot of good tutorials out there to cherry pick from, should you need to. Put the LogFactory in your class definition and then pop lines like log.info.println("service starting"). The other keyword to keep an eye our for is FileAppender. (Sorry no better references, writing from my phone!)
The best solution is to use some logging API have a look at http://www.vogella.com/articles/Logging/article.html tutorial.
Or the other trivial option is to redirect the output of executing the command in some text File. Change the command
String executeCmd = "cmd /c net stop \" + serviceName + "\"+" >> "+ fileName".
In order to get the output of a command you can do this:
String lineSeparator = System.getProperty("line.separator");
stderr = runtimeProcess.getErrorStream();
stdout = runtimeProcess.getInputStream();
// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader(new InputStreamReader(stdout));
StringBuilder output = new StringBuilder();
String line;
while ((line = brCleanUp.readLine()) != null) {
output.append(line).append(lineSeparator);
}
brCleanUp.close();
// clean up if any output in stderr
brCleanUp =
new BufferedReader(new InputStreamReader(stderr));
StringBuilder error = new StringBuilder();
while ((line = brCleanUp.readLine()) != null) {
error.append(line).append(lineSeparator);
}
brCleanUp.close();
And now in output and error String you have the "standard output" and "standard error" of the process you executed.

Categories