Home  >  Article  >  Java  >  How does Java call Javascript and Python algorithms?

How does Java call Javascript and Python algorithms?

little bottle
little bottleforward
2019-04-28 14:15:102988browse

This article mainly talks about using Java to call Javascript and Python algorithms. It has certain reference value. Interested friends can learn about it.

In recent projects, it is often necessary to publish algorithms in Javascript or Python as services, and publishing Tomcat services requires calling these algorithms in Java, so it is inevitable to call algorithms across languages. Whether you are calling a Javascript file or a python script, you need to make appropriate changes to the original algorithm file so that you can pass in parameters in Java and get the algorithm operation results.

1. Java calls Javascript

It should be noted that Javascript is a weakly typed language. Only one var is needed to define a variable. However, in Java, you must pay attention to the variable type and different inputs. Parameters will be of different types.

When calling a js file, you need to adjust it and set the functions and related parameters that need to be called. The js file code used is as follows (some core algorithms cannot be displayed):

function get3DCode(Latitude,Longitude,Height,level){
    var latcode=[];var lngcode=[];
    latcode=GeoSOTCode1D(Latitude,level);
    lngcode=GeoSOTCode1D(Longitude,level);
    var heicode=[];var geosot3Dcode=[];
    heicode=Altcode(Height,level);
    geosot3Dcode=GeoSOT3D(latcode,lngcode, heicode,level);//三维网格编码
    var d3code=[];
    d3code=getQuantcodeString(geosot3Dcode);
    return d3code;
}

In It can be called using the corresponding interface in Java. You need to set the js file path and input parameters. The calling code is as follows;

package whu.get.three.beidou;

import java.io.FileReader; 
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**  * Java调用并执行js文件,传递参数,并获得返回值    */ 
public class ThreeD_GetBeidouCode {
    //获取经纬度及高度,返回三维码
    public static String main(String Latitude,String Longitude,String Height,int CodeSize) throws Exception {      
        //获取经纬度及高度,保存为double类型
        Double latitude = Double.parseDouble(Latitude);
        Double longitude = Double.parseDouble(Longitude);
        Double height = Double.parseDouble(Height);
        int level = CodeSize;

        //调用js文件
        ScriptEngineManager manager = new ScriptEngineManager();   
        ScriptEngine engine = manager.getEngineByName("javascript");     
        String jsFileName = System.getProperty("catalina.home") + "/webapps/3DBeiDouCode/WEB-INF/classes/3Dcode.js";   // 读取js文件
        FileReader reader = new FileReader(jsFileName);   // 执行指定脚本   
        engine.eval(reader); 
        String c = "";
        if(engine instanceof Invocable) {    
            Invocable invoke = (Invocable)engine;    // 调用merge方法,并传入两个参数    
            c = String.valueOf(invoke.invokeFunction("get3DCode", latitude, longitude, height, level));    
            }
        reader.close();  
        return c; //返回三维码
    }
}

The ThreeD_GetBeidouCode class here is just an ordinary class and needs to be in other runnable main functions. Call the main method of this class and pass in the running parameters to get the result.

2. Java calls Python

There are several ways for Java to call python scripts. The simplest is to directly run the python code through Jython, but this method does not support the third code referenced in python. Third-party library, so I used Runtime to call the method, which is equivalent to executing the script on the console.

It should be noted that when Java calls python, the return value cannot be obtained through the return statement, but the result can only be written to the standard output stream through print, and then read through the standard input stream in Java. Get the return result.

If there are requirements for the python environment, such as installing a third-party library that needs to be referenced in a specific environment, you must also add a running environment to the Java project and click Run->Run Configurations- in eclipse >environment, add Path, and set the value to the path of the python installation.

Make appropriate modifications in the python program: add a reference to import sys, and set the called function parameters to sys.argv[1], sys.argv[2]... Note that counting must start from 1 , use the print function to print the results that need to be returned.

The python code in this example is as follows:

# -*- coding:utf-8 -*-
import BaseFunction
import numpy as np
import itertools
import math
import sys
#计算中心要素
def cal_central_feature(path,x,y):
    sf = BaseFunction.open_shpfile(path)
    x_records = BaseFunction.get_attr_records(sf,x)
    y_records = BaseFunction.get_attr_records(sf,y)
    dis = []
    for x0,y0 in zip(x_records,y_records):
        distance = 0
        for x1,y1 in zip(x_records,y_records):
            distance = distance + get_distance(x0,y0,x1,y1)
        dis.append(distance)
    i = dis.index(np.min(dis))
    result = [x_records[i],y_records[i]]
    return result
#计算两点之间的距离
def get_distance(x0,y0,x1,y1):
    xd = x1 - x0
    yd = y1 - y0
    distance = math.sqrt(xd**2+yd**2)
    return distance

if __name__ == '__main__':
    result = cal_central_feature(sys.argv[1],sys.argv[2],sys.argv[3])
    print(result[0])
    print(result[1])

The code called in Java is as follows:

package whu.get.three.beidou;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**  * Java调用并执行js文件,传递参数,并活动返回值    */ 
public class CalCentralFeatureClass {
    //输入shp路径,获取坐标
    public static String main(String filepath) {
        String pyPath = System.getProperty("catalina.home") + "/webapps/CalCentralFeature/WEB-INF/classes/CalCentralFeature.py"; //python文件路径
        String[] args = new String[] { "python", pyPath, filepath, "x","y"};
        String c = "";  //记录返回值
        try {    
            Process proc = Runtime.getRuntime().exec(args);  //执行py文件
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
            String line = null;
            while ((line = in.readLine()) != null) {
                c = c+line+' ';
            }
            in.close();
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c; //返回结果
    }
}

Among the obtained operation results, each print result in python corresponds to one in.readLine(), you can get the results you want as needed.

If you need to publish a program that calls python as a service using tomcat, you also need to configure the tomcat operating environment. You also need to add a Path and assign it to the python installation path.

Related tutorials: Java video tutorial

The above is the detailed content of How does Java call Javascript and Python algorithms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete