search
HomeJavajavaTutorialHow does Java call Javascript and Python algorithms?

How does Java call Javascript and Python algorithms?

Apr 28, 2019 pm 02:15 PM
javajavascriptpython

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:博客园. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),