Running a Java program from Adobe AIR's native process - java

I've use Adobe native process to run java program from my air app. Here the code and it works fine. But i should write absolute path to java runtime for that:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java.
If user installed java runtime in diff folder, or have diff version then this code would not work. How i can detect where java were installed or maybe there is another right way to run java applications from air applications? If i run java library from terminal command line then i could just write "java -jar pdfbox-app-1.6.0.jar" etc. and it runs fine.
private function convertPdf2Txt():void{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("pdfbox-app-1.6.0.jar").nativePath);
arg.push("ExtractText");
arg.push("-force");
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.pdf").nativePath);
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.txt").nativePath);
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (fjava.exists==false){
Alert.show("Can't find Java Runtime in default folder.","Idea Rover",mx.controls.Alert.OK, null,null,imgInfo);
return;
}
var npInfo:NativeProcessStartupInfo;
npInfo = new NativeProcessStartupInfo();
npInfo.executable = fjava;
npInfo.arguments = arg;
var nativeProcess:NativeProcess;
nativeProcess = new NativeProcess();
nativeProcess.addEventListener(NativeProcessExitEvent.EXIT,onNativeProcessExit);
nativeProcess.start(npInfo);
}

Absolute path is:
Mac OS: /usr/bin/java
Win OS: (default)
64bit : C:\Program Files\Java
32bit : C:\Program Files (x86)\Java

rather than popping up an Alert, you could open a file selection dialog, using File.browseForOpen(). then, the File you want is contained in the event passed by the Event.SELECT handler. this flow seems standard for applications i've used that need to access other applications, but aren't sure where to find their executables.
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// setup npInfo, nativeProcess...
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (!fjava.exists) {
fjava.addEventListener(Event.SELECT, onFileSelected);
fjava.browseForOpen("Where is Java located?");
}
private function onFileSelected (evt:Event) :void {
npInfo.executable = evt.target;
nativeProcess.start(npInfo);
fjava.removeEventListener(Event.SELECT, onFileSelected);
}
of course, you can use the same logic to find the file java needs to launch as well.

You may be able to determine where the Java binaries are by looking at the JAVA_HOME environment variable. I'd like to do the same thing as you're doing, so I'll post more after I do more research.

Related

Get same JAVA compilation error as in PowerShell or CMD in Visual Studio Code

I'm on latest Windows 10. I have JDK 15. Latest Visual Studio Code (System). In VS Code, I have half of the Java Extension Pack Installed, i.e Language Support for Java (Red Hat) | Debugger for Java (Microsoft) | Visual Studio IntelliCode (Microsoft). So I did that to just get that run button on the top right (the default installed VS Code didn't have that run button for JAVA programs), below the close button, to that I can run the JAVA programs inside the VS Code. I didn't wanna go out to the directory then open Power Shell or CMD and then write java filename.java and run the program...
Now the issue is that when I click the run button, I think, a Power Shell is opened inside the VS Code and then something other than "java FileName.java" is being written. Because of that I can't really see what the compilation error is. I can only see the line number where the problem is, not actually the solution for that. || If I run the same in the PowerShell outside the VS Code with this "java FileName.java", I can see that there is some issue at x line and also the solution for the same.
So I wanted to know if there is any way to get this type of output inside the Visual Studio Code.
Or if there is any way that Instead of writing a lot of thing like this, we can simple tell the Visual Studio Code to run "java fileName.java" inside VS Code when I click the Run Button at the top.
EDIT:
The Code that I'm running is this one.....
File Name - test.java
import java.io.*;
public class SOPFileTest{
public static void main(String arr[]){
try{
// Creating a File object that represents the disk file.
PrintStream o = new PrintStream(new File("A.txt"));
// Store current System.out before assigning a new value
PrintStream console = System.out;
// Assign o to output stream
System.setOut(o);
System.out.println("Test 1");
// Use stored value for output stream
System.setOut(console);
System.out.println("Test 2");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Now I've noticed somethings, they are:
-When (FileName == Class Name)
---Then (VS Code)
-----Prints the Last System.out.println in the console
-----A.txt is not created / written inside
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
-When (FileName != Class Name)
---Then (VS Code)
-----shows the error same as the image that I included above.
---Then (Powershell)
-----Prints the Last System.out.println in the console
-----A.txt is created and/or written inside
So powershell works as I intend it would, the VS Code isn't...
If the filename is different from ClassName, java extension will detect it and throws probelms, which is build failed and you can choose if continue:
If you choose proceed, there should be:
[UPDATE -- Screenshot in Powershell:]
It's about the same as problems shown in VS Code.
Java extension requires class must be defined in its own file, so filename should be as the same as ClassName, then everything works well, no matter in integrated Terminal in VS Code, or in the PowerShell outside VS Code:
So I wanted to know if there is any way to get this type of output
inside the Visual Studio Code.
Keeping the filename and classname same makes sure it could be built and compiled successfully, which is the first step.
And the text file should be generated in current working directory, check it in your file explorer.

Include multiple source directories in Qt for Android

I want to include Java source code from multiple directories (which are shared between projects) in a Qt for Android project. On http://imaginativethinking.ca/what-the-heck-how-do-i-share-java-code-between-qt-android-projects/ an approach is described which copies the Java source files:
# This line makes sure my custom manifest file and project specific java code is copied to the android-build folder
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
# This is a custom variable which holds the path to my common Java code
# I use the $$system_path() qMake function to make sure that my directory separators are correct for the platform I'm compiling on as you need to use the correct separator in the Make file (i.e. \ for Windows and / for Linux)
commonAndroidFilesPath = $$system_path( $$PWD/../CommonLib/android-sources/src )
# This is a custom variable which holds the path to the src folder in the output directory. That is where they need to go for the ANT script to compile them.
androidBuildOutputDir = $$system_path( $$OUT_PWD/../android-build/src )
# Here is the magic, this is the actual copy command I want to run.
# Make has a platform agnostic copy command macro you can use which substitutes the correct copy command for the platform you are on: $(COPY_DIR)
copyCommonJavaFiles.commands = $(COPY_DIR) $${commonAndroidFilesPath} $${androidBuildOutputDir}
# I tack it on to the 'first' target which exists by default just because I know this will happen before the ANT script gets run.
first.depends = $(first) copyCommonJavaFiles
export(first.depends)
export(copyCommonJavaFiles.commands)
QMAKE_EXTRA_TARGETS += first copyCommonJavaFiles
With later Qt versions the code has to be changed to this:
commonAndroidFilesPath = $$system_path($$PWD/android/src)
androidBuildOutputDir = $$system_path($$OUT_PWD/../android-build)
createCommonJavaFilesDir.commands = $(MKDIR) $${androidBuildOutputDir}
copyCommonJavaFiles.commands = $(COPY_DIR) $${commonAndroidFilesPath} $${androidBuildOutputDir}
first.depends = $(first) createCommonJavaFilesDir copyCommonJavaFiles
export(first.depends)
export(createCommonJavaFilesDir.commands)
export(copyCommonJavaFiles.commands)
QMAKE_EXTRA_TARGETS += first createCommonJavaFilesDir copyCommonJavaFiles
Is this the standard way to go, or is there some built-in functionality for including multiple Java source directories in Qt for Android projects?
Regards,
A much cleaner solution is this one:
CONFIG += file_copies
COPIES += commonJavaFilesCopy
commonJavaFilesCopy.files = $$files($$system_path($$PWD/android/src))
commonJavaFilesCopy.path = $$OUT_PWD/android-build

hide command prompt while setting java home Python

Currently I am working on PartOfSpeech(POS) tagging in Python using Stanford POStagger. I have set the java home
java_path = "Path to java bin"
os.environ['JAVAHOME'] = java_path
Below is my code
def getPOSandSentiment(sentence):
path_to_model = 'Path/to/Tagger/wsj-0-18-left3words-distsim.tagger'
path_to_jar = "path/to/stanford-postagger.jar"
tagger=StanfordPOSTagger(path_to_model, path_to_jar)
tagger.java_options='-mx2048m'
posWords = tagger.tag(sentence.split())
for words,pos in posWords:
print('Word : ',words)
print('POS :', pos)
Everytime I pass a sentence, The java.exe command prompt gets popped up. Is there any way to hide that command prompt? I am using Anaconda3 and spyder IDE for python. Is there any way to set Java_Home in Spyder or Anaconda?
Thanks

GAE Datastore - cannot start LocalDevelopmentDatastore programmatically on Windows

Environment:
Java API google-api-services-datastore-protobuf v1beta2-rev1-3.0.0.
OS: Windows 7.
Goal:
Start Local Datastore Server using the method:
public void start(String sdkPath, String dataset, String cmdLineOptions)
from com.google.api.services.datastore.client.LocalDevelopmentDatastore.java in order to use it in unit tests.
Steps:
I downloaded gcd tool gcd-v1beta2-rev1-3.0.2.zip and put it to C:\gcd folder
(paths to gcd.cmd and gcd.sh are `C:\gcd).
Also, I set environment variables:
"DATASTORE_HOST"="http://localhost:8080" and
"DATASTORE_DATASET"="myapp".
Problem:
LocalDevelopmentDatastoreException occurs.
Caused by: java.io.IOException: Cannot run program "./gcd.sh" (in directory "C:\gcd"): CreateProcess error=2, The system cannot find the file specified.
Note that it tries to find ./gcd.sh but not gcd.cmd.
Java code:
String datasetName = "myapp";
String hostName = "http://localhost:8080";
DatastoreOptions options = new DatastoreOptions.Builder()
.host(hostName)
.dataset(datasetName).build();
LocalDevelopmentDatastoreOptions localOptions = new LocalDevelopmentDatastoreOptions.Builder()
.addEnvVar("DATASTORE_HOST", hostName)
.addEnvVar("DATASTORE_DATASET", datasetName).build();
LocalDevelopmentDatastore datastore = LocalDevelopmentDatastoreFactory.get().create(options, localOptions);
datastore.start("C:\\gcd", datasetName);
This code is based on the example from LocalDevelopmentDatastore.java documentation.
Please help.
It seems as though the method is only programmed to look for gcd.sh, as it doesn't appear there's anything in your config which could have helped this to not fail. I suggest you open a defect report in the Cloud Platform Public Issue Tracker.
Did you consider gcloud-java for using the Datastore?
It also has an option for programmatically starting the local datastore using LocalGcdHelper which should work on Windows.

System.getenv() only works properly when debugging IntelliJ plugin

I'm running IntelliJ 13 (on OS X Yosemite) and trying to get the Go IDEA plugin working. When I debugged the application to try to find what the problem is, I found that for some reason the slave IDEA that's ran gets my environment just fine.
Normally when trying to run anything involving the go utility, an exception is thrown. The plugin will execute commands by executing go <args> with the environment vars:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command, goEnv, new File(projectDir));
If I change the go command to be the full path of the go binary, all works fine. When debugging however, I don't have to change the path and it still succeeds.
The plugin has an action which prints out the environment which calls System.getenv()
GoToolWindow toolWindow = this.getGoToolWindow(project);
toolWindow.showAndCreate(project);
toolWindow.clearConsoleView();
String[] sysEnv = GoSdkUtil.convertEnvMapToArray(System.getenv());
toolWindow.printNormalMessage(String.format("%s -> %s%n", "Project dir", projectDir));
for (String env : sysEnv) {
toolWindow.printNormalMessage(String.format("%s%n", env));
}
When running IDEA normally, this outputs:
Project dir -> /Users/lander/Development/downloader
SHELL=/bin/zsh
TMPDIR=/var/folders/6y/xxqr1vqn6q7c_ttvdgjt7p1w0000gn/T/
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
PATH=/usr/bin:/bin:/usr/sbin:/sbin
XPC_FLAGS=0x0
USER=lander
HOME=/Users/lander
XPC_SERVICE_NAME=com.jetbrains.intellij.43484
LOGNAME=lander
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.tV9zH4QXK4/Render
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.BCyPknIo2V/Listeners
And when debugging the plugin:
Project dir -> /Users/lander/IdeaProjects/gotest
ZSH=/Users/lander/.oh-my-zsh
com.apple.java.jvmMode=client
GREP_OPTIONS=--color=auto --exclude-dir=.cvs --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn
__CF_USER_TEXT_ENCODING=0x1F5:0x0:0x0
GOROOT=/usr/local/opt/go/libexec
XPC_FLAGS=0x0
JAVA_MAIN_CLASS_14389=com.intellij.idea.Main
LOGNAME=lander
GREP_COLOR=1;32
ZSH_TMUX_TERM=screen
SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.BCyPknIo2V/Listeners
OLDPWD=/Applications/IntelliJ IDEA 13.app/Contents/bin
SHELL=/bin/zsh
LC_CTYPE=
TMPDIR=/var/folders/6y/xxqr1vqn6q7c_ttvdgjt7p1w0000gn/T/
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/texbin:/Users/lander/go/bin
VERSIONER_PYTHON_VERSION=2.7
GOPATH=/Users/lander/go
LESS=-R
USER=lander
com.apple.java.jvmTask=CommandLine_Manual.java
ZSH_TMUX_AUTOSTARTED=true
PAGER=less
HOME=/Users/lander
XPC_SERVICE_NAME=0
Apple_PubSub_Socket_Render=/private/tmp/com.apple.launchd.tV9zH4QXK4/Render
LSCOLORS=Gxfxcxdxbxegedabagacad
_ZSH_TMUX_FIXED_CONFIG=/Users/lander/.oh-my-zsh/plugins/tmux/tmux.extra.conf
VERSIONER_PYTHON_PREFER_32_BIT=no
What's the reason for the difference?
According to a JetBrains employee, this is because the slave instance is launched with the environment given by an external script that's ran. Plugins in the parent process should not call System.getenv() and instead use the EnvironmentUtil.

Categories