Java - Flex 4 AIR 2.0 Native Process - java

i'm using Flex 4 Native Process to interact with Java to connect to a remote server using PHP.
I tried this example i found on the internet to connect Flex with Java:
Flex:
protected function windowedApplication1_creationCompleteHandler(event: FlexEvent): void
{
var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
info.executable = new File("C:/Program Files/Java/jre6/bin/java.exe");
info.workingDirectory = File.applicationDirectory;
var args: Vector.<String> = new Vector.<String>();
args.push("-cp", "../bin", "scanner.Main");
info.arguments = args;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onDataOutput);
process.start(info);
}
private function onDataOutput(event: ProgressEvent): void
{
var message:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
Alert.show(message);
}
Java:
public static void main(String[] args)
{
String input;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext("hello|stop"))
{
input = scanner.next();
if (input.equals("hello"))
{
System.out.println("hello flex! ... from java");
}
else if (input.equals("stop"))
{
return;
}
}
}
And it works perfect.
But when i try calling the Java method that connects to the remote server, switching the line System.out.println("hello flex! ... from java"); for the name of the method, it dies (does nothing).
I'm new to the Native Process concept, but researching on the web i found out that you need to send the libraries as arguments that your project uses.
I need some help on how to do so.
The Java project uses Http and JSon libraries.
How do i add those to the arguments? and do i need to add the JRE System libraries too?
PS: The java method works fine if i execute it from eclipse.
Thank you.
Edit: Tried it with a Jar file
var file:File = new File("C:/Program Files/Java/jre6/");
file = file.resolvePath("bin/javaw.exe");
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("prueba3.jar").nativePath);
arg.push("-Djava.library.path=C:\\Users\\Administrador\\Desktop\\libhttp");
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
npInfo.executable = file;
npInfo.arguments = arg;
process = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);
process.start(npInfo);
and adding the library path, but still didn't work.

You could make a AMFPHP service, and connect directly to PHP with AS3

Related

Execute an AWS command in eclipse

I execute an EC2 command through eclipse like:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String spot = "aws ec2 describe-spot-price-history --instance-types"
+ " m3.medium --product-description \"Linux/UNIX (Amazon VPC)\"";
System.out.println(spot);
Runtime runtime = Runtime.getRuntime();
final Process process = runtime.exec(spot);
//********************
InputStreamReader isr = new InputStreamReader(process.getInputStream());
BufferedReader buff = new BufferedReader (isr);
String line;
while((line = buff.readLine()) != null)
System.out.print(line);
}
The result in eclipse console is:
aws ec2 describe-spot-price-history --instance-types m3.medium --product-description "Linux/UNIX (Amazon VPC)"
{ "SpotPriceHistory": []}
However, when I execute the same command (aws ec2 describe-spot-price-history --instance-types m3.medium --product-description "Linux/UNIX (Amazon VPC)") in shell I obtain a different result.
"Timestamp": "2018-09-07T17:52:48.000Z",
"AvailabilityZone": "us-east-1f",
"InstanceType": "m3.medium",
"ProductDescription": "Linux/UNIX",
"SpotPrice": "0.046700"
},
{
"Timestamp": "2018-09-07T17:52:48.000Z",
"AvailabilityZone": "us-east-1a",
"InstanceType": "m3.medium",
"ProductDescription": "Linux/UNIX",
"SpotPrice": "0.047000"
}
My question is: How can obtain in eclipse console the same result as in shell console ?
It looks like you are not getting the expected output because you are passing a console command through your Java code which is not getting parsed properly, and you are not utilizing the AWS SDKs for Java instead.
To get the expected output in your Eclipse console, you could utilize the DescribeSpotPriceHistory Java SDK API call in your code[1]. An example code snippet for this API call according to the documentation is as follows:
AmazonEC2 client = AmazonEC2ClientBuilder.standard().build();
DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest().withEndTime(new Date("2014-01-06T08:09:10"))
.withInstanceTypes("m1.xlarge").withProductDescriptions("Linux/UNIX (Amazon VPC)").withStartTime(new Date("2014-01-06T07:08:09"));
DescribeSpotPriceHistoryResult response = client.describeSpotPriceHistory(request);
Also, you could look into this website containing Java file examples of various scenarios utilizing the DescribeSpotPriceHistory API call in Java[2].
For more details about DescribeSpotPriceHistory, kindly refer to the official documentation[3].
References
[1]. https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/ec2/AmazonEC2.html#describeSpotPriceHistory-com.amazonaws.services.ec2.model.DescribeSpotPriceHistoryRequest-
[2]. https://www.programcreek.com/java-api-examples/index.php?api=com.amazonaws.services.ec2.model.SpotPrice
[3]. https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSpotPriceHistory.html

Redirecting Standard Output of a JAR in c#

I have a C# app that at some point needs to communicate with a JAR app. No problem, I use the following code to start the app but unfortunately, the window that should print the app's console remains black and the jar file executes in GUI mode.
If I call the same file with the same command from RUN or CMD, it works and the console registers messages from the JAR any ideas why when started from my C# app it won't register any message to the console?
[ProcessStartInfo psi32 = default(ProcessStartInfo);
Process proc1 = new Process();
string path1 = Application.StartupPath;
dynamic process3 = pat1 + "java.exe";
dynamic jar = "-jar ";
dynamic param1 = "/ssh.jar";
dynamic args3 = string.Format("{0}{1} {2}", jar, path1, param1);
psi32 = new ProcessStartInfo(process3, args3);
psi32.RedirectStandardInput = true;
psi32.UseShellExecute = false;
proc1.StartInfo = psi32;
proc1.Start();
string condeva;
using (StreamReader reader = proc1.StandardOutput)
{
message= reader.ReadToEnd();
}
if (message.Contains("failed"))
{
message.Text = "found it...";
}

netbeans makefile java execution

Here I have attached the source code and make file of it.
I use netbeans. How should I build my project to execute this java code in netbeans. please help me with detailed steps. I am new to netbeans and java.
I use netbeans 8.0.2 for windows 10 64 bit OS.
Source code:
package net.sourceforge.jpcap.tutorial.example15;
import net.sourceforge.jpcap.capture.*;
import net.sourceforge.jpcap.net.*;
/*
* This example utilizes the endCapture() feature.
*/
public class Example15 {
private static final int INFINITE = -1;
private static final int PACKET_COUNT = INFINITE;
// BPF filter for capturing any packet
private static final String FILTER = "";
private PacketCapture m_pcap;
private String m_device;
public Example15() throws Exception {
// Step 1: Instantiate Capturing Engine
m_pcap = new PacketCapture();
// Step 2: Check for devices
m_device = m_pcap.findDevice();
// Step 3: Open Device for Capturing (requires root)
m_pcap.open(m_device, true);
// Step 4: Add a BPF Filter (see tcpdump documentation)
m_pcap.setFilter(FILTER, true);
// Step 5: Register a Listener for Raw Packets
m_pcap.addRawPacketListener(new RawPacketHandler(m_pcap));
// Step 6: Capture Data (max. PACKET_COUNT packets)
m_pcap.capture(PACKET_COUNT);
}
public static void main(String[] args) {
try {
Example15 example = new Example15();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
class RawPacketHandler implements RawPacketListener
{
private static int m_counter = 0;
private PacketCapture m_pcap = null;
public RawPacketHandler(PacketCapture pcap) {
m_counter = 0;
m_pcap = pcap;
}
public synchronized void rawPacketArrived(RawPacket data) {
m_counter++;
System.out.println("Packet " + m_counter + "\n" + data + "\n");
if(condition())
m_pcap.endCapture();
}
private boolean condition() {
return (m_counter == 5) ? true : false;
}
}
make file:
# $Id: makefile,v 1.1 2002/07/10 23:05:26 pcharles Exp $
#
# package net.sourceforge.jpcap.tutorial.example15
#
PKG = net.sourceforge.jpcap.tutorial.example15
PKG_DIR = $(subst .,/, $(PKG))
REL = ../../../../..
include ${MAKE_HOME}/os.makefile
include ${MAKE_HOME}/rules.makefile
JAVA = \
Example15
JAVA_SOURCE = $(addsuffix .java, $(JAVA))
JAVA_CLASSES = $(addsuffix .class, $(JAVA))
all: $(JAVA_CLASSES)
include ${MAKE_HOME}/targets.makefile
include ${MAKE_HOME}/depend.makefile
Netbeans uses Makefiles for C++ code but not for Java code. It is easy to get this code to build but there is no need for the Makefile.
File -> New Project
Select Category Java on the left and "Java Application with Existing Sources" (with this option the project and sources will be in different directories) on the right.
Click Next
Change the Project name and/or directory to create the project in.
Add the original source directory in the dialog.
Click Finish to Create the project.
Within netbeans you can now use the Run-> Build Project to build it.
If you really have to have a Makefile just make one that just runs the Netbeans project( which is actually an ant project).
eg.
build:
ant jar

How to execute the Windows 'printto' verb using Java?

In the past I have used the 'printto' verb to print PDFs from with a .Net application. It looked something like this:
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.Verb = "printto"; // print to given printer
psi.Arguments = "LPT1";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.ErrorDialog = true;
Process.Start(psi);
How can I do this from a Java application? Or is there an alternative approach? Note that the target platform will always be Windows.
Please try this.
public void print() {
//The desktop api can help calling native applications in windows
Desktop desktop = Desktop.getDesktop();
try {
desktop.print(new File("yourFile.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
Please Note : This is the easy fix. You can also use java's Print API to achieve the same thing

How to integrate googlemap api javascript from a webpage into java program?

from what I've read it seems to be possible to run some javascript within a java program, however I'm still struggling on fully grasping how. Would I be able to do enough to execute a googlemap api to be displayed in my java program?
The two examples of code that I have been looking at is this in java:
import javax.script.*;
public class script {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script = "function hello(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;
// invoke the global function named "hello"
inv.invokeFunction("hello", "Scripting!!" );
}
}
and this as an example found on the google doc site in javascript to produce this:
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
If any of you can assist me in understanding how to integrate these two samples of code so that the map appears in a JPanel instead of "hello world", I think I could figure the rest of it out.
UPDATE: After reading through the terms of usage, I found out that I would be violating the terms, however; if I move the map onto our organizations public site, I should be able to load the result of that script into my Java programs JPanel which would give public access to the map and not be in violation. Am I correct? Is this possible to do? I don't have any experience with javascript.
I don't know much about integrating Google map script with or the integration policies.
But, you can execute JavaScript file from your java code.So i feel you can write your script code in a js file and execute it as follows :
import javax.script.*;
public class EvalFile {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from given file - specified by first argument
engine.eval(new java.io.FileReader(yourfile.js));
}
}
For more info please refer this link http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html. I hope it may help you

Categories

Resources