From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/ru/rhino/documentation/index.html | 83 ++++++++ files/ru/rhino/download_rhino/index.html | 106 ++++++++++ files/ru/rhino/embedding_tutorial/index.html | 302 +++++++++++++++++++++++++++ files/ru/rhino/index.html | 22 ++ 4 files changed, 513 insertions(+) create mode 100644 files/ru/rhino/documentation/index.html create mode 100644 files/ru/rhino/download_rhino/index.html create mode 100644 files/ru/rhino/embedding_tutorial/index.html create mode 100644 files/ru/rhino/index.html (limited to 'files/ru/rhino') diff --git a/files/ru/rhino/documentation/index.html b/files/ru/rhino/documentation/index.html new file mode 100644 index 0000000000..98686fb771 --- /dev/null +++ b/files/ru/rhino/documentation/index.html @@ -0,0 +1,83 @@ +--- +title: Rhino documentation +slug: Rhino/Documentation +tags: + - Rhino +translation_of: Mozilla/Projects/Rhino/Documentation +--- +

Сведения о Rhino для разработчиков скриптов и приложений.

+ +

Главное

+ +
+
Обзор
+
Обзор языка  JavaScript и Rhino.
+
Лицензия
+
Информация о лицензии Rhino.
+
Требования и ограничения
+
Что необходимо, чтобы запустить Rhino; чего не может делать Rhino.
+
Загрузка архива
+
Включает комментарии к выпуску для Rhino
+
Оптимизация
+
Подробная информация о различных уровнях оптимизации.
+
FAQ
+
Ответы на частые вопросы о Rhino.
+
История Rhino
+
История зверя.
+
+ +

Написание скриптов

+ +
+
Java в скриптах
+
Как использовать  Rhino, чтобы  в скриптах задействовать  классы Java.
+
Java в скриптах
+
How to use Rhino to script Java classes (an older treatment).
+
Советы по улучшению производительности
+
Некоторые советы по написанию быстрого кода JavaScript.
+
+ +

Инструменты JavaScript

+ +
+
Оболочка Rhino
+
Интерактивное или пакетное выполнение скриптов.
+
Отладчик JavaScript
+
Отладка скриптов, запущенных в Rhino.
+
Компилятор JavaScript
+
Компиляция скриптов в файлы классов Java.
+
Запуск тестов Rhino
+
Запуск тестов JavaScript с Rhino.
+
+ +

Встраивание Rhino

+ +
+
Руководство по теме
+
Краткое руководство по встраиванию Rhino в приложение.
+
Справочник по API Javadoc  (Link broken?  Try this at Jarvana.)
+
An annotated outline of the programming interface to Rhino (tip only).
+
Области видимости и контекстыs
+
Describes how to use scopes and contexts for the best performance and flexibility, with an eye toward multithreaded environments.
+
Сериализация
+
Как выполнить сериализацию объектов и функций JavaScript  в Rhino.
+
Runtime
+
A brief description of the JavaScript runtime.
+
Small Footprint
+
Hints for those interested in small-footprint embeddings.
+
Примеры
+
Набор примеров того, как контролировать движок JavaScript и собирать объекты хоста JavaScript.
+
Использование Rhino вместе с h Bean Scripting Framework (BSF)
+
Как использовать Rhino вместе с приложениями, поддерживающими BSF (Bean Scripting Framework) из проекта Apache Jakarta.
+
+ +

Внешние ссылки

+ +
+
Скриптовые языки для Java
+
Статья сравнивает и противопоставляет Rhino и Jython.
+
+ +

Авторы Rhino

+ +

Interested in contributing to Rhino? Check out the Rhino Wish List.

diff --git a/files/ru/rhino/download_rhino/index.html b/files/ru/rhino/download_rhino/index.html new file mode 100644 index 0000000000..d6b61aee73 --- /dev/null +++ b/files/ru/rhino/download_rhino/index.html @@ -0,0 +1,106 @@ +--- +title: ска́чивание Rhino +slug: Rhino/Download_Rhino +translation_of: Mozilla/Projects/Rhino/Download_Rhino +--- +

Rhino можно загрузить как в виде исходного кода, так и в виде скомпилированной библиотеки.

+ +

Библиотека в двоичном коде

+ +

Последняя версия библиотеки Rhino - 1.7R4.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ReleaseДата освобожденияИнформация о выпускеСсылка на скачивание
Rhino 1.7R42012-06-18New in Rhino 1.7R4rhino1_7R3.zip
Rhino 1.7R52015-01-29Информация о выпускеrhino1_7R5.zip
Rhino 1.7.62015-04-15Информация о выпускеrhino1.7.6.zip
Rhino 1.7.72015-06-17Информация о выпускеrhino1.7.7.zip
Rhino 1.7.7.12016-02-01Информация о выпускеrhino1.7.7.1.zip
Rhino 1.7.7.22017-08-24Информация о выпускеrhino1.7.7.2.zip
Rhino 1.7.82018-01-22Информация о выпускеrhino1.7.8.zip
Rhino 1.7.92018-03-15Информация о выпускеrhino1.7.9.zip
Rhino 1.7.102018-04-09Информация о выпускеrhino1.7.10.zip
Rhino 1.7.112019-05-30Информация о выпускеrhino1.7.11.zip
Rhino 1.7.122020-01-13Информация о выпускеrhino1.7.12.zip
+ +

Если требуются более старые версии библиотеки, ищите их в Архиве hino версий Rhino.

+ +

Лицензия

+ +

Rhino открыт (open source). Начиная с версии 1.7R4, Rhino распространяется с лицензией MPL 2.0.

+ +

Предыдущие версии распространяются с лицензией MPL 1.1/GPL 2.0.

+ +

Дополнительная информация о Лицензиях Rhino.

+ +

Исходный код библиотеки

+ +

В дополнении к исходному коду, который находится в ранее указанном zip-файле, исходный код Rhino можно найти в github-е на странице проекта https://github.com/mozilla/rhino. Для того, чтобы загрузить код используйте команду

+ +
git clone https://github.com/mozilla/rhino.git
+
+ +

Для сборки Rhino используется Ant. Запуск команды ant в корневом каталоге дистрибутива Rhino, по идее, распечатывает список имеющихся подсистем сборки (build targets).

diff --git a/files/ru/rhino/embedding_tutorial/index.html b/files/ru/rhino/embedding_tutorial/index.html new file mode 100644 index 0000000000..eb56c3050c --- /dev/null +++ b/files/ru/rhino/embedding_tutorial/index.html @@ -0,0 +1,302 @@ +--- +title: 'Руководство: Внедрение кода Rhino' +slug: Rhino/Embedding_tutorial +translation_of: Mozilla/Projects/Rhino/Embedding_tutorial +--- +

Внедрение кода Rhino простое но тем не менее приводит к хорошему результату. Приложив больше усилии к embedder,  исполняемые сценарии могут быть настроены дополнительно.

+ +

В этом руководстве по шагово мы рассмотрим способы от простого сценария внедрения кода до сложного. Примеры кода будут соправождать нас в процессе изучения.

+ +

Примеры можно найти в папках дистрибутива rhino/examples   и cvs  сервере по адресу mozilla/js/rhino/examples.  В этом руководстве мы будем ссылатся на эти примеры посредством lxr.

+ +

 JavaScript код будет помечен зеленым, Java код так же будет помечен зеленым, и shell logs будет отмечен пурпурным.

+ +

Содержание:

+ + + +

RunScript: Простой пример

+ +

Возможно самый простой пример внедрения Rhino вы найдете здесь RunScript example. Он считывает строку параметра, который должен быть фрагментом js-кода, запускает код и выводит результат.

+ +

Ниже приведен данный пример. Используйте команду RunScript в командной строке консоли:

+ +
$ java RunScript "Math.cos(Math.PI)"
+-1
+$ java RunScript "function f(x){return x+1} f(7)"
+8
+
+ +

Примечание: Rhino классы и класс RunScript должны быть прописаны в classpath. Let's step through the body of main one line at time.

+ +

Entering a Context

+ +

The code

+ +
Context cx = Context.enter();
+
+ +

Creates and enters a Context. A Context stores information about the execution environment of a script.

+ +

Initializing standard objects

+ +

The code

+ +
Scriptable scope = cx.initStandardObjects();
+
+ +

Initializes the standard objects (Object, Function, etc.) This must be done before scripts can be executed. The null parameter tells initStandardObjects to create and return a scope object that we use in later calls.

+ +

Collecting the arguments

+ +

This code is standard Java and not specific to Rhino. It just collects all the arguments and concatenates them together.

+ +
String s = "";
+for (int i=0; i < args.length; i++) {
+    s += args[i];
+}
+
+ +

Evaluating a script

+ +

The code

+ +
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
+
+ +

uses the Context cx to evaluate a string. Evaluation of the script looks up variables in scope, and errors will be reported with the filename <cmd> and line number 1.

+ +

Printing the result

+ +

The code

+ +
System.out.println(cx.toString(result));
+
+ +

prints the result of evaluating the script (contained in the variable result). result could be a string, JavaScript object, or other values. The toString method converts any JavaScript value to a string.

+ +

Exiting the Context

+ +

The code

+ +
} finally {
+    Context.exit();
+}
+
+ +

exits the Context. This removes the association between the Context and the current thread and is an essential cleanup action. There should be a call to exit for every call to enter. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after Context.enter().

+ +

Expose Java APIs

+ +

Using Java APIs

+ +

No additional code in the embedding needed! The JavaScript feature calledLiveConnect allows JavaScript programs to interact with Java objects:

+ +
$ java RunScript "java.lang.System.out.println(3)"
+3.0
+undefined
+
+ +

Implementing interfaces

+ +

Using Rhino, JavaScript objects can implement arbitrary Java interfaces. There's no Java code to write -- it's part of Rhino's LiveConnect implementation. For example, we can see how to implement java.lang.Runnable in a Rhino shell session:

+ +
js> obj = { run: function() { print("hi"); } }
+[object Object]
+js> obj.run()
+hi
+js> r = new java.lang.Runnable(obj);
+[object Object]
+js> t = new java.lang.Thread(r)
+Thread[Thread-0,5,main]
+js> t.start()
+hi
+
+ +

Adding Java objects

+ +

The next example is RunScript2. This is the same as RunScript, but with the addition of two extra lines of code:

+ +
Object wrappedOut = Context.javaToJS(System.out, scope);
+ScriptableObject.putProperty(scope, "out", wrappedOut);
+
+ +

These lines add a global variable out that is a JavaScript reflection of the System.out variable:

+ +
$ java RunScript2 "out.println(42)"
+42.0
+undefined
+
+ +

Using JavaScript objects from Java

+ +

After evaluating a script it's possible to query the scope for variables and functions, extracting values and calling JavaScript functions. This is illustrated in the RunScript3 example. This example adds the ability to print the value of variable x and the result of calling function f. Both x and f are expected to be defined by the evaluated script. For example,

+ +
$ java RunScript3 "x = 7"
+x = 7
+f is undefined or not a function.
+$ java RunScript3 "function f(a) { return a; }"
+x is not defined.
+f("my args") = my arg
+
+ +

Using JavaScript variables

+ +

To print out the value of x, we add the following code:

+ +
Object x = scope.get("x", scope);
+if (x == Scriptable.NOT_FOUND) {
+    System.out.println("x is not defined.");
+} else {
+    System.out.println("x = " + Context.toString(x));
+}
+
+ +

Calling JavaScript functions

+ +

To get the function f, call it, and print the result, we add this code:

+ +
Object fObj = scope.get("f", scope);
+if (!(fObj instanceof Function)) {
+    System.out.println("f is undefined or not a function.");
+} else {
+    Object functionArgs[] = { "my arg" };
+    Function f = (Function)fObj;
+    Object result = f.call(cx, scope, scope, functionArgs);
+    String report = "f('my args') = " + Context.toString(result);
+    System.out.println(report);
+}
+
+ +

JavaScript host objects

+ +

Defining Host Objects

+ +

Custom host objects can implement special JavaScript features like dynamic properties.

+ +

Counter example

+ +

The Counter example is a simple host object. We'll go through it method by method below.

+ +

It's easy to try out new host object classes in the shell using its built-in defineClass function. We'll see how to add it to RunScript later. (Note that because the java -jar option preempts the rest of the classpath, we can't use that and access the Counter class.)

+ +
$ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.Main
+js> defineClass("Counter")
+js> c = new Counter(7)
+[object Counter]
+js> c.count
+7
+js> c.count
+8
+js> c.count
+9
+js> c.resetCount()
+js> c.count
+0
+
+ +

Counter's constructors

+ +

The zero-argument constructor is used by Rhino runtime to create instances. For the counter example, no initialization work is needed, so the implementation is empty.

+ +
public Counter () { }
+
+ +

The method jsConstructor defines the JavaScript constructor that was called with the expression new Counter(7) in the JavaScript code above.

+ +
public void jsConstructor(int a) { count
+= a; }
+
+ +

Class name

+ +

The class name is defined by the getClassName method. This is used to determine the name of the constructor.

+ +
public String getClassName() { return "Counter";
+}
+
+ +

Dynamic properties

+ +

Dynamic properties are defined by methods beginning with jsGet_ or jsSet_. The method jsGet_count defines thecount property.

+ +
public int jsGet_count() { return count++;
+}
+
+ +

The expression c.count in the JavaScript code above results in a call to this method.

+ +

Defining JavaScript "methods"

+ +

Methods can be defined using the jsFunction_ prefix. Here we define resetCount for JavaScript.

+ +
public void jsFunction_resetCount() { count
+= 0; }
+
+ +

The call c.resetCount() above calls this method.

+ +

Adding Counter to RunScript

+ +

Now take a look at the RunScript4 example. It's the same as RunScript except for two additions. The method ScriptableObject.defineClass uses a Java class to define the Counter "class" in the top-level scope:

+ +
ScriptableObject.defineClass(scope, Counter.class);
+
+ +

Now we can reference the Counter object from our script:

+ +
$ java RunScript4 "c = new Counter(3); c.count;
+c.count;"
+
+ +

It also creates a new instance of the Counter object from within our Java code, constructing it with the value 7, and assigning it to the top-level variable myCounter:

+ +
Object[] arg = { new Integer(7) };
+Scriptable myCounter = cx.newObject(scope, "Counter", arg);
+scope.put("myCounter", scope, myCounter);
+
+ +

Now we can reference the myCounter object from our script:

+ +
$ java RunScript3 'RunScript4 'myCounter.count; myCounter.count'
+8
+
diff --git a/files/ru/rhino/index.html b/files/ru/rhino/index.html new file mode 100644 index 0000000000..eda494f561 --- /dev/null +++ b/files/ru/rhino/index.html @@ -0,0 +1,22 @@ +--- +title: Rhino +slug: Rhino +translation_of: Mozilla/Projects/Rhino +--- +

Image:rhino.jpg

+ +

Библиотека Rhino (Носорог) - это открытая (open-source) версия языка программирования  JavaScript, реализованная полностью в Java. Библиотека предназначена для встраивания в Java-приложения в качестве пользовательского скриптового (scripting) языка программирования. Она включена в J2SE 6 как один из механизмов реализации сценариев (scripting engine) для Java.

+ +

Загрузка Rhino

+ +

Инструкция по загрузке исходного кода и библиотеки в двоичном коде

+ +

Документация по библиотеке Rhino

+ +

Инструкция для разработчиков скриптов, включая встраивание в Java-программы.

+ +

Дополнительная информация о Rhino

+ +

Некоторые дополнительные ресурсы, в случае возникновения проблем.

+ +

{{ languages( { "ru": "ru/Rhino" } ) }}

-- cgit v1.2.3-54-g00ecf