PHP Call from Java Using Quercus - java

I have a sample PHP class which I would like to Utilize in my Java Application.
We have decided to use Quercus as a Libary for doing the Integration.
Can some one let me know How can I call a PHP class from Java Code using Quercus.
For Example.
PHP class name is calculator.php and it has one method say sum() which expects 2 numbers to be passed and It will do the summation of those number.
Please let me know the sample code which can be coded to achive the same.
Thanks,

You should look at QuercusEngine
import com.caucho.quercus.QuercusEngine;
QuercusEngine engine = new QuercusEngine();
engine.setOutputStream(System.out);
engine.executeFile("src/test.php");
Other examples
The only needed jars are resin.jar and servlet-api.jar.

It seems that you can't usefully instantiate a QuercusEngine these days. Instead:
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
You then probably want engine.eval(reader);

Related

How to implement the Google Distance Matrix API in Java without using the HTTP request method

I am aware of the fact that I am able to use a HTTP request to use the distance matrix API (i.e. https://maps.googleapis.com/maps/api/distancematrix/json?origins=42.11622,78.10112&destinations=40.82231,72.224166&key=YOUR_API_KEY)
But I would like to simply use the Java API instead. From my understanding the first step is to create a GeoApiContext and this seems to be where I am failing. I have tried the following code:
private static GeoApiContext context = new GeoApiContext.Builder().apiKey("MyKey").queryRateLimit(500).build();
However I am just met with the following compile error:
java.land.NoClassDefFoundError: com/google/common/util/concurrent/RateLimiter
Any help on the matter would be appreciated. The plan is to use this to create a DistanceMatrix API request if that helps.
check out this link you may find it useful... there are code examples
https://www.programcreek.com/java-api-examples/index.php?api=com.google.maps.model.DistanceMatrix

How to create a tensorflow serving client for the 'wide and deep' model?

I've created a model based on the 'wide and deep' example (https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py).
I've exported the model as follows:
m = build_estimator(model_dir)
m.fit(input_fn=lambda: input_fn(df_train, True), steps=FLAGS.train_steps)
results = m.evaluate(input_fn=lambda: input_fn(df_test, True), steps=1)
print('Model statistics:')
for key in sorted(results):
print("%s: %s" % (key, results[key]))
print('Done training!!!')
# Export model
export_path = sys.argv[-1]
print('Exporting trained model to %s' % export_path)
m.export(
export_path,
input_fn=serving_input_fn,
use_deprecated_input_fn=False,
input_feature_key=INPUT_FEATURE_KEY
My question is, how do I create a client to make predictions from this exported model? Also, have I exported the model correctly?
Ultimately I need to be able do this in Java too. I suspect I can do this by creating Java classes from proto files using gRPC.
Documentation is very sketchy, hence why I am asking on here.
Many thanks!
I wrote a simple tutorial Exporting and Serving a TensorFlow Wide & Deep Model.
TL;DR
To export an estimator there are four steps:
Define features for export as a list of all features used during estimator initialization.
Create a feature config using create_feature_spec_for_parsing.
Build a serving_input_fn suitable for use in serving using input_fn_utils.build_parsing_serving_input_fn.
Export the model using export_savedmodel().
To run a client script properly you need to do three following steps:
Create and place your script somewhere in the /serving/ folder, e.g. /serving/tensorflow_serving/example/
Create or modify corresponding BUILD file by adding a py_binary.
Build and run a model server, e.g. tensorflow_model_server.
Create, build and run a client that sends a tf.Example to our tensorflow_model_server for the inference.
For more details look at the tutorial itself.
Just spent a solid week figuring this out. First off, m.export is going to deprecated in a couple weeks, so instead of that block, use: m.export_savedmodel(export_path, input_fn=serving_input_fn).
Which means you then have to define serving_input_fn(), which of course is supposed to have a different signature than the input_fn() defined in the wide and deep tutorial. Namely, moving forward, I guess it's recommended that input_fn()-type things are supposed to return an InputFnOps object, defined here.
Here's how I figured out how to make that work:
from tensorflow.contrib.learn.python.learn.utils import input_fn_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.framework import dtypes
def serving_input_fn():
features, labels = input_fn()
features["examples"] = tf.placeholder(tf.string)
serialized_tf_example = array_ops.placeholder(dtype=dtypes.string,
shape=[None],
name='input_example_tensor')
inputs = {'examples': serialized_tf_example}
labels = None # these are not known in serving!
return input_fn_utils.InputFnOps(features, labels, inputs)
This is probably not 100% idiomatic, but I'm pretty sure it works. For now.

Converting Jython htmlunit script to pure Java

I have a script for Jython that works perfectly, but it's really really slow, so I decided to try to see if I can convert it to pure java and see if it speeds it up.
In Jython I am using:
from java.util import logging
from java import lang
from org.apache.commons.logging import LogFactory
logger = LogFactory.getLog('com.gargoylesoftware.htmlunit')
logger.getLogger().setLevel(logging.Level.OFF)
webclient = WebClient(BrowserVersion.FIREFOX_3_6)
webclient.setThrowExceptionOnFailingStatusCode(False)
This basically prevents all the annoying warning messages from htmlunit to stop coming on the screen (it tends to complain a lot if the code it's reading isn't perfect but still ends up reading it).
In Java I tried to copy and paste the same code, but Java seems to ignore it. If I add types to my import, it doesn't give me an error it just keeps doing the same thing.
import java import.lang;
import org.apache.commons.logging.LogFactory;
LogFactory.getLog('com.gargoylesoftware.htmlunit');
LogFactory.getLogger().setLevel(logging.Level.OFF);
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
webClient.setThrowExceptionOnFailingStatusCode(false);
Since the file is fairly large and I'll have to do quite a been of converting of code, what is the logic of what I am doing wrong?
Java's Syntax is not equal to Python's Syntax. imports are declared on the top of the Class-File, other things are done within the "class"-container.
Basically a Java file looks something like this:
import [...]
public class YourClass{
public YourClass(){
// Constructor
}
public static void main(Stirng[] args){
// The method Java calls when a class is executed in a JVM
}
}
You should check out some Java-Tutorials first, because Java and Python are quite different.

using .as extenion files in flex

Hai
Am very new to flex application development.Am using flex builder 4 and i need to call .as file from mxml file.please help to do this with sample code (Demo).And how to use java file to get and set data.
Thanks In Advance.
It's very easy, simply do:
import myasfile
Or if it's coming from a different directory, you could simply specify your directory on the dot notation, such as:
import renderers.myrenderer
As per using the Java file, you will need to use remote objects to connect to your Java class. There's a really nice video introduction here
Hope this helps you.
You should be using something like this
<mx:Script source="includes/IncludedFile.as"/>
http://livedocs.adobe.com/flex/3/html/usingas_4.html
If you mean just instantiating or calling an actionscript class, do something like this:
<fx:Script>
<![CDATA[
import yourpackage.SomeClass
private function someFunction():void
{
SomeClass.someStaticFunction();
// or
new SomeClass().someNonStaticFunction();
}
]]>
</fx:Script>
Also, if you class extends IMXMLObject you can include it directly in the mxml withing the declarations tag like this:
<fx:Declarations>
<someNamespace:YourClass someProperty="true" />
</fx:Declarations>
Hope that helps. You should really read up on mxml and look at examples. I have several on my blog.
Try something like this
<mx:Script>
<![CDATA[
import MyAsFile.as //if your file is inculded in .src folder
import path/MyAsFile.as //if in other folder
]]>
</mx:Script>

how to use java to get a js file and execute it and then get the result

How can I use java to get a js file located on a web server, then execute the function in the js file and get the result and use the result in java.
Can you guys give me some code snippet? Great thanks.
You can use the scripting engine built into Java:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
Object result = engine.eval("my-java-script-code")
System.out.println("Result returned by Javascript is: " + result);
}
Here is a more elaborate example.
There's three steps to this process:
Fetch the JS file from the server.
Execute some JS function from the file.
Extract the result.
The first step is fairly simple, there are lots of HTTP libraries in Java that will do this - you effectively want to emulate the simple functionality of something like wget or curl. The exact manner in which you do this will vary depending on what format you want the JS file in for the next step, but the process to get hold of the byte stream is straightforward.
The second step will require executing the JS in a Javascript engine. Java itself cannot interpret Javascript, so you'd need to obtain an engine to run it in - Rhino is a common choice for this. Since you'd need to run this outside of Java, you'll likely have to spawn a process for execution in Rhino using ProcessBuilder. Additionally, depending on the format of the Javascript you might need to create your own "wrapper" javascript that functions like a main class in Java and calls the method in question.
Finally you need to get the result out - obviously you don't have direct access to JavaScript objects from your Java program. The easiest way is going to be for the JS program to print the result to standard out (possibly serialising as something like JSON depending on the complexity of the object), which is being streamed directly to your Java app due to the way you launched the Rhino process. This could be another job for your JS wrapper script, if any. Otherwise, if the JS function has observable side effects (creates a file/modifies a database) then you'll be able to query those directly from Java.
Job done.
I hope you realise this question is far too vague to get full answers. Asking the public to design an entire system goes beyond the point where you'll get useful, actionable responses.
There are plenty of examples on the web of how to download a file from a URL.
Suns version of the JDK and JRE includes the Mozilla Rhino scripting engine.
Assuming you have stored the contents of the javascript file in a string called 'script', you can execute scripts as follows
String result = null;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval(script);
result = jsEngine.get("result")
} catch (ScriptException ex) {
ex.printStackTrace();
}
The result will be extracted from the engine and stored in the 'result' variable.
The is a tutorial on scripting in Java that might be useful.

Categories