adb shell command from android app - java

When I try to run the following
process = Runtime.getRuntime().exec("input touchscreen swipe 100 1000 300 1000 1000"); //Normal swipe
it works.
However, when I am using it as following, it is not working.
String[] inputs = {"adb", "shell", "input touchscreen swipe 500 1000 600 1000 1000"};
Process p = Runtime.getRuntime().exec(inputs);
p.waitFor();
I've another command which I want to run, and for it to run, I have to use the second approach. Can someone tell me what is the reason or how can I make the second one run?

Process p = Runtime.getRuntime().exec(inputs);
throws a couple of exceptions, including but not limited to IO, Null Pointer, Index Out of Bound.
Try surrounding that line with a try catch
Process p;
try {
p = Runtime.getRuntime().exec(ch);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You should paste what the error is, if it exists. (For example, in logcat.)
adb is the client, which may not exist in your Android device (since Android 5.0+). You are not expected to use it in your Android App command. For your sample, you can directly use input command without adb.
Also,
process = Runtime.getRuntime().exec("input touchscreen swipe 100 1000 300 1000 1000");
is equivalent to
String[] inputs = {"input", "touchscreen", "swipe", "100", "1000", "300", "1000", "1000"};
process = Runtime.getRuntime().exec(inputs);.
Note the dropped first two element in inputs from your question.

As #Geno Chen mentioned, the parameters, need to go with double quotes.
String[] inputs = {"input", "touchscreen", "swipe", "100", "1000", "300", "1000", "1000"};
p.waitFor(); must be removed to get this working.

Related

Process does not exit when launched from Java

I am launching WebTorrent-CLI from within my Java application as a separate process. I am using zt-exec for managing the process. When WebTorrent is launched with the following command, it is supposed to exit after the file at given index (value of --select) has been downloaded.
"D:\downloadmanager\node\webtorrent.cmd" download "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel" --select 0 --out "D://nf/"
As expected, webtorrent-cli does exit after downloading 0th file when the command above is used to launch it from command line. But when I try the same from within my Java app, it completely ignores the --select option and continues downloading other files in the torrent.
Basically, when launched as a process from Java, webtorrent ignores all the options set (--select, --out or whatever). I should mention that there is nothing wrong with the library because recently I've tried replacing it with commons-exec and that solved nothing. Also, to make sure that the right command is passed while starting the process, I'm printing the command right before calling executor.start(). The command above is copied from the output retrieved from printing the command before the process starts.
This is how the process is started:
#Override
public synchronized void start() throws IOException {
if (mWasDownloadStarted || mWasDownloadFinished) return;
mExec.getCommand().listIterator().forEachRemaining(s -> {
System.out.print(s + " ");
});
mExec.start();
setProcessId();
mWasDownloadStarted = true;
mWasDownloadStopped = false;
}
This is how the command is prepared:
private String buildCommand() {
List <String> command = new ArrayList<>();
command.add("\"" + mManager.mWTLocation + "\"");
command.add("download");
command.add("\"" + mManager.mMagnetUrl + "\"");
if (mManager.mFileIndex >= 0) {
command.add("--select " + mManager.mFileIndex);
}
if (mManager.mSaveTo != null) {
command.add("--out \"" + mManager.mSaveTo + "\"");
}
mManager.mExec.command(command);
String cmdStr = "";
for (String s : command) {
cmdStr = cmdStr.concat(s + " ");
}
return cmdStr.trim();
}
What might be wrong?
Okay, so I was able to fix this issue.
The / character following the path specified as value of --out was causing the problem. In order to fix this, I added a line in node_modules/webtorrent-cli/bin/cmd.js to print the arguments passed to webtorrent:
console.log(process.argv)
With the /, output of this line was something like the following:
[ 'D:\\downloadmanager\\node\\node.exe',
'D:\\downloadmanager\\node\\node_modules\\webtorrent-cli\\bin\\cmd.js',
'download',
'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel',
'--select',
'0',
'--out',
'D:\\nf"' ]
Note the " that is included in the path after D:\\nf. When / is removed from the path, the quote disappears and webtorrent behaves as expected.
I doubt that this is a bug in webtorrent. I think zt-exec (or maybe I) was doing something stupid.
Somewhat unrelated, but I think I should also mention that I had to enclose every value for each option with quotes, even the index, to get rid of other nasty errors (e.g.: Error 87, the parameter is incorrect)

Having Java call an Applescript file with arguments

I have a Java program that calls an Applescript file to run, and returns information back to Java. However, I need to also pass some arguments to the Applescript file. The relevant portion of the Java file:
public static void scriptRunner(String[] args) {
// Connect to the database.
ConnectionManager.getInstance().setDBType(DBType.MYSQL);
// Prepare the AppleScript file to be executed.
String homeFolder = System.getenv("HOME");
File scriptFile = new File(homeFolder + "/Documents/Output--Test.applescript");
InputStream scriptStream = null;
try {
scriptStream = FileUtils.openInputStream(scriptFile);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Could not find the Output AppleScript file. Please notify Chris McGee", "File not found", JOptionPane.ERROR_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(scriptStream));
// These two lines prepare the scripting engine, ready to run the script.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
// Add the parameters to the engine so they will be passed to the script.
engine.put("javaOrderNum", args[0]);
engine.put("javaShipDate", args[1]);
engine.put("javaInitials", args[2]);
engine.put("javaOverruns", args[3]);
// Run the script and evaluate the result.
log.trace("Run the script and evaluate the result.");
Object result = null;
try {
result = engine.eval(bufferedReader); // Run the script and place the result into an abstract object.
} catch (ScriptException e) {
JOptionPane.showMessageDialog(null, "Either an error occurred with the Output script or the user cancelled it.", "Script error / cancel", JOptionPane.INFORMATION_MESSAGE);
ConnectionManager.getInstance().close();
System.exit(1);
}
log.debug(result); // Check that we received the correct information back from the script.
log.debug("");
.
.
.
Sadly, the engine.put lines, as suggested from a forum I read during my searches to get this problem solved, don't seem to work. The AppleScript file:
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
set jInitials to item 3 of arguments
set jOverruns to item 4 of arguments
-- Set the correct folder variable
if (folderExists(POSIX path of "/Volumes/Users/Scripts/")) then
set server_prefix to "/Volumes/Users/Scripts/"
else if (folderExists(POSIX path of "/centralserver/Users/Scripts/")) then
set server_prefix to "/centralserver/Users/Scripts/"
else
display alert "Please connect to the central server, then try again.
If you have already done so, please let Chris McGee know."
end if
with timeout of (30 * 60) seconds
tell application "Adobe InDesign CS6"
set myJavaScript to server_prefix & "sky-artdept/Test/Output.jsx"
set myResult to do script myJavaScript with arguments {jOrderNum, jShipDate, jInitials, jOverruns} language javascript
return myResult
end tell
end timeout
on folderExists(posixPath)
return ((do shell script "if test -e " & quoted form of posixPath & "; then
echo 1;
else
echo 0;
fi") as integer) as boolean
end folderExists
I am given an error that the variable arguments is not defined. What can I try next?
I can't help with the javascript running the applescript. But, you applescript code is missing a declaration. You're asking for "item 1 of arguments" but you never define the variable arguments.
When the script is not inside any handler, it is implicit that it is inside a run() handler. And, since you're needing to pass arguments on run, you should try wrapping your script, minus the on folderExists() handler, inside a run handler that includes the arguments declaration.
on run(arguments)
-- Get variables passed in
set jOrderNum to item 1 of arguments
set jShipDate to item 2 of arguments
…
end timeout
end run
on folderExists(posixPath)
…
end folderExists

Corrupt Olympus Makernote Exif Directory

I'm trying to extract information from my photos via Java.
My camera, an Olympus E-510 saves all the pictures with a corrupt makernote directory. When I try to get the tags from the OlympusMakernoteDirectory, there are none. Each directory has one error which turns out to be an "Illegally sized directory" error.
Do I have any chance of somehow accessing the data in the directory? I wouldn't mind juggling bytes but I have no idea where to start :(
Currently working on a javascript only solution.
Will contribute it here in the next days:
https://github.com/redaktor/exiftool.js (it is just a fork for now)
Some Olympus Cameras seem to store their makernotes only in subIFDs.
I wouldn't mind juggling bytes but I have no idea where to start :(
start here :
this has a special meaning ::
0x3000: 'RawInfo',
0x4000: 'MainInfo',
they can be either pointers to SubIFDs or arrays
some cameras store the "root tags" in 0x4000 ...
{
0x2010: '_IFDpointer_Equipment', // (misleading name returns many things, e.g. serial)
0x2020: '_IFDpointer_CameraSettings',
0x2030: '_IFDpointer_RawDevelopment',
0x2031: '_IFDpointer_RawDevelopment2',
0x2040: '_IFDpointer_ImageProcessing',
0x2050: '_IFDpointer_FocusInfo',
0x0000: 'MakerNoteVersion',
0x0001: 'CameraSettings',
0x0003: 'CameraSettings',
0x0040: 'CompressedImageSize',
0x0081: 'PreviewImageData',
0x0088: 'PreviewImageStart',
0x0089: 'PreviewImageLength',
0x0100: 'ThumbnailImage',
0x0104: 'BodyFirmwareVersion',
0x0200: 'SpecialMode',
0x0201: 'Quality',
0x0202: 'Macro',
0x0203: 'BWMode',
0x0204: 'DigitalZoom',
0x0205: 'FocalPlaneDiagonal',
0x0206: 'LensDistortionParams',
0x0207: 'Olympus CameraType Values',
0x0208: 'Olympus TextInfo',
0x020b: 'EpsonImageWidth',
0x020c: 'EpsonImageHeight',
0x020d: 'EpsonSoftware',
0x0280: 'PreviewImage',
0x0300: 'PreCaptureFrames',
0x0301: 'WhiteBoard',
0x0302: 'OneTouchWB',
0x0303: 'WhiteBalanceBracket',
0x0304: 'WhiteBalanceBias',
0x0404: 'SerialNumber',
0x0405: 'Firmware',
0x0e00: 'PrintIM',
0x0f00: 'DataDump',
0x0f01: 'DataDump2',
0x0f04: 'ZoomedPreviewStart',
0x0f05: 'ZoomedPreviewLength',
0x0f06: 'ZoomedPreviewSize',
0x1000: 'ShutterSpeedValue',
0x1001: 'ISOValue',
0x1002: 'ApertureValue',
0x1003: 'BrightnessValue',
0x1004: 'FlashMode',
0x1006: 'ExposureCompensation',
0x1007: 'SensorTemperature',
0x1008: 'LensTemperature',
0x1009: 'LightCondition',
0x100a: 'FocusRange',
0x100b: 'FocusMode',
0x100c: 'ManualFocusDistance',
0x100d: 'ZoomStepCount',
0x100e: 'FocusStepCount',
0x100f: 'Sharpness',
0x1010: 'FlashChargeLevel',
0x1011: 'ColorMatrix',
0x1012: 'BlackLevel',
0x1013: 'ColorTemperatureBG?',
0x1014: 'ColorTemperatureRG?',
0x1017: 'RedBalance',
0x1018: 'BlueBalance',
0x1019: 'ColorMatrixNumber',
0x101a: 'SerialNumber',
0x101b: 'ExternalFlashAE1_0?',
0x101c: 'ExternalFlashAE2_0?',
0x101d: 'InternalFlashAE1_0?',
0x101e: 'InternalFlashAE2_0?',
0x101f: 'ExternalFlashAE1?',
0x1020: 'ExternalFlashAE2?',
0x1021: 'InternalFlashAE1?',
0x1022: 'InternalFlashAE2?',
0x1023: 'FlashExposureComp',
0x1024: 'InternalFlashTable',
0x1025: 'ExternalFlashGValue',
0x1026: 'ExternalFlashBounce',
0x1027: 'ExternalFlashZoom',
0x1028: 'ExternalFlashMode',
0x1029: 'Contrast',
0x102a: 'SharpnessFactor',
0x102b: 'ColorControl',
0x102c: 'ValidBits',
0x102d: 'CoringFilter',
0x102e: 'OlympusImageWidth',
0x102f: 'OlympusImageHeight',
0x1030: 'SceneDetect',
0x1031: 'SceneArea?',
0x1033: 'SceneDetectData?',
0x1034: 'CompressionRatio',
0x1035: 'PreviewImageValid',
0x1036: 'PreviewImageStart',
0x1037: 'PreviewImageLength',
0x1038: 'AFResult',
0x1039: 'CCDScanMode',
0x103a: 'NoiseReduction',
0x103b: 'FocusStepInfinity',
0x103c: 'FocusStepNear',
0x103d: 'LightValueCenter',
0x103e: 'LightValuePeriphery',
0x103f: 'FieldCount?'
}
_IFDpointer_Equipment: {
0x0000: 'EquipmentVersion',
// 0x0100: { ref: ' Olympus CameraType Values' }, // TODO
0x0101: 'SerialNumber',
0x0102: 'InternalSerialNumber',
0x0103: 'FocalPlaneDiagonal',
0x0104: 'BodyFirmwareVersion',
// 0x0201: { ref: ' Olympus LensType Values' }, // TODO
0x0202: 'LensSerialNumber',
0x0203: 'LensModel',
0x0204: 'LensFirmwareVersion',
0x0205: 'MaxApertureAtMinFocal',
0x0206: 'MaxApertureAtMaxFocal',
0x0207: 'MinFocalLength',
0x0208: 'MaxFocalLength',
0x020a: 'MaxAperture',
0x020b: 'LensProperties',
0x0301: 'Extender',
0x0302: 'ExtenderSerialNumber',
0x0303: 'ExtenderModel',
0x0304: 'ExtenderFirmwareVersion',
0x0403: 'ConversionLens',
0x1000: 'FlashType',
0x1002: 'FlashFirmwareVersion',
0x1003: 'FlashSerialNumber'
},
_IFDpointer_CameraSettings: {
0x0000: 'CameraSettingsVersion',
0x0100: 'PreviewImageValid',
0x0101: 'PreviewImageStart',
0x0102: 'PreviewImageLength',
0x0200: 'ExposureMode',
0x0201: 'AELock',
0x0203: 'ExposureShift',
0x0204: 'NDFilter',
0x0300: 'MacroMode',
0x0302: 'FocusProcess',
0x0303: 'AFSearch',
0x0304: 'AFAreas',
0x0305: 'AFPointSelected',
0x0306: 'AFFineTune',
0x0307: 'AFFineTuneAdj',
0x0401: 'FlashExposureComp',
0x0404: 'FlashControlMode',
0x0405: 'FlashIntensity',
0x0406: 'ManualFlashStrength',
0x0501: 'WhiteBalanceTemperature',
0x0502: 'WhiteBalanceBracket',
0x0503: 'CustomSaturation',
0x0504: 'ModifiedSaturation',
0x0505: 'ContrastSetting',
0x0506: 'SharpnessSetting',
0x0507: 'ColorSpace',
0x050a: 'NoiseReduction',
0x050b: 'DistortionCorrection',
0x050c: 'ShadingCompensation',
0x050d: 'CompressionFactor',
0x050f: 'Gradation',
0x0521: 'PictureModeSaturation',
0x0522: 'PictureModeHue?',
0x0523: 'PictureModeContrast',
0x0524: 'PictureModeSharpness',
0x0527: 'NoiseFilter',
0x052d: 'PictureModeEffect',
0x052e: 'ToneLevel',
0x0600: 'DriveMode',
0x0601: 'PanoramaMode',
0x0603: 'ImageQuality2',
0x0604: 'ImageStabilization',
0x0900: 'ManometerPressure',
0x0901: 'ManometerReading',
0x0902: 'ExtendedWBDetect',
0x0903: 'LevelGaugeRoll',
0x0904: 'LevelGaugePitch',
0x0908: 'DateTimeUTC'
},
_IFDpointer_RawDevelopment: {
0x0000: 'RawDevVersion',
0x0100: 'RawDevExposureBiasValue',
0x0101: 'RawDevWhiteBalanceValue',
0x0102: 'RawDevWBFineAdjustment',
0x0103: 'RawDevGrayPoint',
0x0104: 'RawDevSaturationEmphasis',
0x0105: 'RawDevMemoryColorEmphasis',
0x0106: 'RawDevContrastValue',
0x0107: 'RawDevSharpnessValue',
0x0108: 'RawDevColorSpace',
0x0109: 'RawDevEngine',
0x010a: 'RawDevNoiseReduction',
0x010b: 'RawDevEditStatus'
},

Java ProgramCall.run hangs

Busy trying to Call RPG function from Java and got this example from JamesA. But now I am having trouble, here is my code:
AS400 system = new AS400("MachineName");
ProgramCall program = new ProgramCall(system);
try
{
// Initialise the name of the program to run.
String programName = "/QSYS.LIB/LIBNAME.LIB/FUNNAME.PGM";
// Set up the 3 parameters.
ProgramParameter[] parameterList = new ProgramParameter[2];
// First parameter is to input a name.
AS400Text OperationsItemId = new AS400Text(20);
parameterList[0] = new ProgramParameter(OperationsItemId.toBytes("TestID"));
AS400Text CaseMarkingValue = new AS400Text(20);
parameterList[1] = new ProgramParameter(CaseMarkingValue.toBytes("TestData"));
// Set the program name and parameter list.
program.setProgram(programName, parameterList);
// Run the program.
if (program.run() != true)
{
// Report failure.
System.out.println("Program failed!");
// Show the messages.
AS400Message[] messagelist = program.getMessageList();
for (int i = 0; i < messagelist.length; ++i)
{
// Show each message.
System.out.println(messagelist[i]);
}
}
// Else no error, get output data.
else
{
AS400Text text = new AS400Text(50);
System.out.println(text.toObject(parameterList[1].getOutputData()));
System.out.println(text.toObject(parameterList[2].getOutputData()));
}
}
catch (Exception e)
{
//System.out.println("Program " + program.getProgram() + " issued an exception!");
e.printStackTrace();
}
// Done with the system.
system.disconnectAllServices();
The application Hangs at this lineif (program.run() != true), and I wait for about 10 minutes and then I terminate the application.
Any idea what I am doing wrong?
Edit
Here is the message on the job log:
Client request - run program QSYS/QWCRTVCA.
Client request - run program LIBNAME/FUNNAME.
File P6CASEL2 in library *LIBL not found or inline data file missing.
Error message CPF4101 appeared during OPEN.
Cannot resolve to object YOBPSSR. Type and Subtype X'0201' Authority
FUNNAME insert a row into table P6CASEPF through a view called P6CASEL2. P6CASEL2 is in a different library lets say LIBNAME2. Is there away to maybe set the JobDescription?
Are you sure FUNNAME.PGM is terminating and not hung with a MSGW? Check QSYSOPR for any messages.
Class ProgramCall:
NOTE: When the program runs within the host server job, the library list will be the initial library list specified in the job description in the user profile.
So I saw that my problem is that my library list is not setup, and for some reason, the user we are using, does not have a Job Description. So to over come this I added the following code before calling the program.run()
CommandCall command = new CommandCall(system);
command.run("ADDLIBLE LIB(LIBNAME)");
command.run("ADDLIBLE LIB(LIBNAME2)");
This simply add this LIBNAME, and LIBNAME2 to the user's library list.
Oh yes, the problem is Library list not set ... take a look at this discussion on Midrange.com, there are different work-around ...
http://archive.midrange.com/java400-l/200909/msg00032.html
...
Depe

Execute jar file many times and analyse output

I'd like to test which of two implementation in java of a problem is the fastest.
I've 2 jar files with the two implementation I can execute from the terminal. I want to execute both about 100 times and analyse which one is the fastest to do that or that task.
In the output one of the line is "executing time : xx", I need to catch this xx to put in an array or something like that to analyse it later
While I'm executing the jar, I've also to give some input commands (like a name to search or a number).
I don't with which language is it the easiest to do it.
I know the basis in Bash and Python
thank you
Excuse me, but Why you dont make a jar that call n-times any jar?
For Example:
public static void main(String[] args) {
for(int i=0;i<1000;i++) {
params1 = randomNumber();
params2 = randomName();
...
paramsN = randomTime();
MYJAR1 test1 = new MYJAR1(params1,params2,...,paramsN);
timerStart();
test1.start();
timerEnd();
printTimer();
}
}
and make the same for the second jar.
I hope that my idea can help you.
Bye
If you use (say) Perl, you can spawn the process off, capture the output via a redirection and filter the times. e.g.
if (open(PROCESS, "myproc |")) {
while(<PROCESS>) {
if (/executing time : (\d+)/) {
# $1 has the time now
}
}
}
(not compiled or tested!)
Perhaps the simplest way of analysing the data is to redirect the above output to a file, and then load it into Excel. You can then use Excel to calculate averages/max/mins and std. devs (if you wish) trivially.
Ok I've found with 3 different scripts ^^
in the java code, for each function :
long time1 = System.currentTimeMillis();
// some code for function 1
long time2 = System.currentTimeMillis();
try {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File("log.txt"),true));
osw.write("function1,"+(time2 - time1)+"\n");
osw.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
a bash code to run the 500 times the two algorithms
#!/bin/bash
i=0
while [ $i -lt 500 ]
do
./algo1.ex
./algo2.ex
i=$(( $i+1 ))
done
an (or two actually, one for each algorithm) expect code to do the command during the execution
#!/usr/bin/expect -f
spawn java -jar algo1.jar
expect "enter your choice" {send "1\n"}
expect "enter a name :" {send "Peju, M.\n"}
expect "enter your choice" {send "2\n"}
expect "enter a name :" {send "Creasy, R. J.\n"}
expect "enter your choice" {send "0\n"}
exit
As I didn't know how to do it in bash, to count I used a python code
#!/usr/bin/python
# -*- coding: utf8 -*-
import sys
if __name__ == "__main__":
if sys.argv[1:]:
arg = sys.argv[1]
filin = open(arg, 'r')
line = filin.readline()
res= 0, 0, 0
int n = 1
while line !='':
t = line.partition(',')
if t[0] == "function1":
res = (res[0] + int(t[2]), res[1], res[2])
if t[0] == "function2":
res = (res[0], res[1] + int(t[2]), res[2])
if t[0] == "function3":
res = (res[0], res[1], res[2] + int(t[2]))
ligne = filin.readline()
n = n+1
print res
print (res[0]/(n/3.0), res[1]/(n/3.0), res[2]/(n/3.0))
filin.close()
and it works
but thanks for your propositions

Categories