gradle execute process error stream - android

I have an android project and trying to start the emulator. It works fine locally, but not on the build server, so I'm trying to figure out why, but I'm not able to see any of the error output (even locally).
task startEmulator << {
def process = "emulator -avd nexus4 -no-boot-anim -no-window".execute()
//...consumption code here
}
Here's what I tried for reading the error output:
process.waitFor()
print process.err.text
and
process.waitForProcessOutput(System.out, System.err)
and
process.consumeProcessOutput(System.out, System.err)
and
process.consumeProcessErrorStream(System.err)
The error code gets set properly to 1 or 0 depending on whether the run was successful. It's not a matter of the code exiting too soon. For example when I try the code with an AVD name that doesn't exist, the error stream is empty.
What am I missing?
PS: Can't use an exec task since I need this execute call to be asynchronous/in the background.

Make sure the tomcat user (if you are using a tomcat) has the privileges to run the command emulator. If tomcat user doesn´t have the privileges, you are not going to be able to run the command.

My workaround is to use a string buffer.
def bout = new StringBuffer()
// Not sure if a common buffer is always a good idea.
"ls".execute().waitForProcessOutput(bout, bout)
println bout.toString()

Related

script execution failing in Android emulator code (Android Studio) with permission denied

I am able to run a shell script on the Mac command line, but when I call it in Android Studio java it fails with this error:
GenerateActivity::THE COMMAND=[./go.top-level, Sweden]
java.io.IOException: Cannot run program "./go.top-level" (in directory "/data/user/0/com.example.frontpage/files/scripts"): error=13, Permission denied
My java code to call the script is as follows:
dir = lcontext.getFilesDir(); //lcontext is passed into this procedure
File workingDirectory = new File(dir + "/scripts/");//go.top-level is in /scripts dir
List<String> command = new ArrayList<String>();
command.add("./go.top-level"); // command
command.add(country); // command
System.out.println(TAG + "THE COMMAND=" + command.toString());
// creating the process
ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(workingDirectory);
try {
pb.start(); //pb.wait() errors out indicating need a lock and a thread.....
} catch (Exception e) {
e.printStackTrace();
}
The process is failing immediately in the java. But, when I run it at the command line, i.e., via:
%./go.top-level Sweden (in /scripts dir)
it works, although it takes a couple of minutes. (note: I do "run-as com.example.frontpage" before running). The java seems logical to me since I set the workingDirectory appropriately. Also the /scripts folder and all of the files in it as well as the other folders used in this code are set to 777 permissions dynamically in the code. Why doesn't the error say, "./go.top-level Sweden" since the script call takes one argument? What am I missing here as far as this permission error? Is pb.start() a bad idea since the execution takes on the order of minutes? But when I try pb.wait() I get a different error indicating I need a lock and a thread. If that is best can someone indicate how best to do that?
TIA

Nativescript getting debugging to work in VS Code

Thank you, thank you, thank you for sharing your Nativescript expertise. I'm pretty stuck
I'm really trying. I'm searching and trying for last couple days to get a simple Nativescript demo app to run in VS Code debugger and break.
I have my dev environment fully setup. I can build and run Nativescript demo apps in VS Code as long as I don't try to use the debugger.
Here is my tns doctor output. You can see I have it all setup correctly.
I'm only doing Android for now. Ignore the tns-ios update.
I have my launch.json setup like this...
{
"name": "Launch on Android",
"type": "nativescript",
"request": "launch",
"platform": "android",
"appRoot": "${workspaceRoot}",
"sourceMaps": true,
"watch": true,
"tnsArgs": [
"--debug",
"--bundle"
]
},
I've added this line to my webpack.config.js...
devtool: "eval-source-map",
And so far, above is all I can find on how to get Nativescript app debugging working in VS Code. What am I missing? Here is what I get in VS Code debug output when I try to do Launch on Android. Link is to Pastebin...
Nativescript VSCode 'Launch on Android' debug output
EDIT 2/3 console output after running commands in first comment...
[NativeScriptCli] execute: tns --analyticsClient VSCode --version
[NativeScriptCli] execute: tns --analyticsClient VSCode --version
[NSDebugAdapter] Using tns CLI v5.1.1 on path 'tns'
[NSDebugAdapter] Running tns command...
[NativeScriptCli] execute: tns --analyticsClient VSCode debug android --watch --bundle
[NSDebugAdapter] Watching the tns CLI output to receive a connection token
Searching for devices...
Executing before-watchPatterns hook from C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\hooks\before-watchPatterns\nativescript-dev-webpack.js
Executing before-watch hook from C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\hooks\before-watch\nativescript-dev-webpack.js
Running webpack for Android...
Bundling application for entryPath .\app...
C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack-cli\bin\cli.js:453
throw err;
^
Error: EPERM: operation not permitted, scandir 'C:/Users/markd/Documents/code-projects/nativescript/blank-vue-app/platforms/android/app/src/main/assets/app/App_Resources/Android/drawable-mdpi/background.png'
at Object.readdirSync (fs.js:786:3)
at GlobSync._readdir (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:288:41)
at GlobSync._readdirInGlobStar (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:267:20)
at GlobSync._readdir (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:276:17)
at GlobSync._processReaddir (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:137:22)
at GlobSync._process (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:132:10)
at GlobSync._processGlobStar (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:380:10)
at GlobSync._process (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:130:10)
at GlobSync._processGlobStar (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:383:10)
at GlobSync._process (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:130:10)
at GlobSync._processGlobStar (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:383:10)
at GlobSync._process (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:130:10)
at GlobSync._processGlobStar (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:383:10)
at GlobSync._process (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:130:10)
at new GlobSync (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:48:10)
at Function.globSync [as sync] (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\glob\sync.js:26:10)
at Function.rimrafSync [as sync] (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\rimraf\rimraf.js:280:22)
at C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\clean-webpack-plugin\index.js:166:16
at Array.forEach ()
at CleanWebpackPlugin.clean (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\clean-webpack-plugin\index.js:92:15)
at CleanWebpackPlugin.apply (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\clean-webpack-plugin\index.js:212:20)
at webpack (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack\lib\webpack.js:47:13)
at processOptions (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack-cli\bin\cli.js:441:16)
at yargs.parse (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack-cli\bin\cli.js:536:3)
at Object.parse (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\yargs\yargs.js:567:18)
at C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack-cli\bin\cli.js:219:8
at Object. (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack-cli\bin\cli.js:538:3)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object. (C:\Users\markd\Documents\code-projects\nativescript\blank-vue-app\node_modules\webpack\bin\webpack.js:155:2)
at Module._compile (internal/modules/cjs/loader.js:689:30)
[31;1mExecuting webpack failed with exit code 1.[0m
[31;1mCannot read property 'kill' of undefined[0m
tns debug
Description
Initiates a debugging session for your project on a connected device or native emulator. When necessary, the command will prepare, build, deploy and launch the app before starting the debug session. While debugging, the output from the application is printed in the console and any changes made to your code are synchronized on all connected devices or running emulators.
Commands
┌─────────┬─────────────────────┐
│ Usage │ Synopsis │
│ General │ $ tns debug android │
└─────────┴─────────────────────┘
If you aren't getting Chrome debugger to work, you won't get any better results with VS Code, since it uses the same protocol.
I assume you have nativescript-dev-webpack included in your 'devDependencies' block of your package.json?
If not, npm install --save-dev nativescript-dev-webpack
then, tns debug android should prompt you with the URL for the chrome debugger connection, and from there you should be able to set a breakpoint somewhere in your code that your application can hit after a button click or some similar direct user event. If you try to set a breakpoint early in the startup of the app, it may not hit it unless you use the --debug-brk flag (see https://docs.nativescript.org/tooling/debugging/debugging#debugger-options). Best to start with something you can trigger after the app if fully up and running. this will be especially true when using VS Code.
Once you get this level of success with Chrome, install the Nativescript extensions for VS Code (https://docs.nativescript.org/tooling/visual-studio-code-extension).
Note that, when in VS Code, clicking the 'settings gear' icon allows you to edit launch.json which controls the target configuration for the debug options. If you have a root other than ${workspaceRoot}, for example, you may need to edit it here so that finds your project in the right place.
When I use this, I use the 'attach android' option, rather than the launch, but that's mostly just my preference. I believe it works either way. I launch from the command line with tns debug android and then in VS Code select 'attach android' and then wait (a short but seemingly long time) for the 'back and forth' progress indicator at the top to stop and the console output to say 'ready to attach debugger' Then I can select a breakpoint and trigger the app, and it will catch it. It can be frustrating to insure the debugger attachment is in place, especially after an edit that triggers a restart, because of the delay. But I use it for my android debugging quite a bit. For whatever reason, it disconnects repeatedly for me when I try to do the same for iOS, but for that, Chrome works nicely.
What I'd really like is a tight and clean debugger solution for WebStorm, which is my IDE of choice, and there used to be one (that no longer works). Such is life.
You need nativescript-dev-webpack#0.19.1 and need to update your webpack.config file
npm i nativescript-dev-webpack#latest --save-dev
./node_modules/.bin/update-ns-webpack --configs

Gradle task using adb to install apk not being executed

I am writing a gradle task to install an apk unto emulators before espresso tests are run.
This is the task I have so far.
task installButlerApk {
doLast {
println "Verifying test-butler installation in emulators"
final adb = "$android.sdkDirectory.absolutePath/platform-tools/adb"
final String[] split = ["$adb", "devices", "-l"].execute().text.split("\\r?\\n")
split.each {
if (it.isEmpty())
return;
println "Emulator: $it"
final emu = it.split("\\s")[0]
checks whether the APK is already installed
if (["$adb", "-s", "$emu", "shell", "pm", "list", "packages"].execute().text.contains(butlerPackage))
return;
final installResult = ["$adb", "-s", "$emu", "install", "$butlerApkPath"].execute().text
if (!installResult.contains("Success"))
println "Could not install APK. Install output:\n$installResult"
else
println "Installed $butlerApkPath in $emu successfully"
}
}
}
However when I run it via the terminal the task ends up freezing. I am not sure why. I did some research about it and at one point I thought the command that was being passed to ProcessGroovyMethods' execute was failing because it was being passed as a string (execute(String self)) so I then used the array representation of execute (execute(String[] commandArray)) to see if that would work but I am still ending up with the same result so I am just asking for someone who has experience writing these tasks to give me some assistance. So far, I am printing the result of the command and it hasn't shown any errors. It's just stuck at the building process for hours.
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.
C:\Users\Joel\Documents\Projects\Forms>gradlew installButlerApk
Picked up _JAVA_OPTIONS: -XX:ParallelGCThreads=2
To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon:
https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html.
Incremental java compilation is an incubating feature.
:app:installButlerApk
Verifying test-butler installation in emulators
Emulator: List of devices attached
> Building 0% > :app:installButlerApk
Well, this is expected behavior.
If you look at your output closely, you see
Emulator: List of devices attached
So following your code:
println "Emulator: $it"
outputs that line I quoted
final emu = it.split("\\s")[0]
takes the first space separated token which is List
checks whether the APK is already installed
this will not even compile, but I guess you just forgot the comment characters that you added in the question as explanation
if (["$adb", "-s", "$emu", "shell", "pm", "list", "packages"].execute().text.contains(butlerPackage))
return;
Now you execute adb -s List shell pm list
Executed manually this two times prints error: device not found for me and then exits, so your contains condition is false and the return is not done.
final installResult = ["$adb", "-s", "$emu", "install", "$butlerApkPath"].execute().text
Now you execute adb -s List install butler.apk
Executed manually this three times prints out error: device not found, then one time - waiting for device - and then sits there waiting until you cancel it, or a device with serial number List becomes available which of course will never happen and thus your task hangs until you kill it.
You have to skip the header line when you work through the list of devices, as this is of course not a device.
Besides this, you can of course use the Groovy standard ways to execute external commands. Yet while in Gradle, I'd rather use the Gradle variants. If you only want to execute one thing it would be a task of type Exec, if you want to execute multiple things like in your case, it is the Project.exec() or Script.exec() methods, so you would do something like
def output
new ByteArrayOutputStream().withStream { baos ->
exec {
executable adb
args "-s", emu, "shell", "pm", "list", "packages"
standardOutput os
}.assertNormalExitValue()
output = baos.toString()
}
if (output.contains(butlerPackage)) {
return
}
exec {
executable adb
args "-s", emu, "install", butlerApkPath
}.assertNormalExitValue()

Why Android uiautomator's UiDevice#takeScreenshot always return false on emulator

When using uiautomator, takeScreenshot(File storePath) always returns false no matter what parameter I pass in.
I've tried to give either new File(dir_name, file_name) or new File(file_name), neither of them works (of course mkdir first if the dir_name doesn't exist).
Every time it just return false and /data/local/tmp/ on emulator is empty.
BTW, I don't think it's a permission problem, since trying the similar dumpWindowHierarchy could generate a dump file there.
Thanks in advance for your help.
If you are using emulator to run the tests you should turn on "Use Host GPU" in your AVD configuration. After this change it worked for me.
If you still got a problem you may try screencap. It is command line tool for taking screenshots. It works in both emulator settings. To save screenshot in given path execute:
Process process = Runtime.getRuntime().exec("screencap <path>");
process.waitFor();
Use /data/local/tmp to avoid problems with permission. You can use SD Card dir as well. It is asynchronous so wait until process is finished with waitFor(). It will recognize desired output format by extension of provided file.
Or you can get PNG in InputStream (no need to wait):
Process process = Runtime.getRuntime().exec("screencap -p");
InputStream output = new BufferedInputStream(process.getInputStream());
You can omit -p if you wish to get file in JPEG. They JPEG screenshots are bigger, but it takes less time to get them.
The takeScreenshot() method is applicable from 4.2 and above android version devices
If the device version is appropriate, then use the following piece of code
File path = new File("/sdcard/filename.png");
int SDK_VERSION = android.os.Build.VERSION.SDK_INT;
if (SDK_VERSION >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
mUiAutomatorTestCase.getUiDevice().takeScreenshot(PATH);
}
We can view the file by following command
$ adb shell ls -l /sdcard/name-of-file

why does CAT command is not working in android device?

I am working in android application. I want to copy data from 1 file to other file.I have executed below command for it, but not able to copy data from file1 -> file 2.
// Executes the command.
String CAT_COMMAND = "cat /sdcard/file1 > /sdcard/file2";
Process process = Runtime.getRuntime().exec(CAT_COMMAND);
I have used ADB SHELL command at DOS , executed CAT command which works fine.
But code execution is not working into the real devices.
please help me out why does it is not copying data from file1->file2.??
provide resolution for writing/copying data using CAT command.
Thanks
can you try with the complete path /mnt/sdcard .(or) Try to get the right path by Environment.getExternalStorageDirectory()

Categories

Resources