Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ tasks.withType<JavaCompile> {

allprojects {
group = "com.github.otymko.jos"
version = "0.0.1"
version = "0.2.0"

repositories {
mavenCentral()
Expand All @@ -38,6 +38,13 @@ allprojects {
property("sonar.coverage.jacoco.xmlReportPaths", "$buildDir/reports/jacoco/test/jacoco.xml")
}
}

tasks.withType<Jar> {
manifest {
attributes["Implementation-Version"] = project.version
}
}

}

subprojects {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.github.otymko.jos.runtime.SymbolType;
import com.github.otymko.jos.runtime.context.global.FileOperationsGlobalContext;
import com.github.otymko.jos.runtime.context.global.StringOperationGlobalContext;
import com.github.otymko.jos.runtime.context.global.SystemEnvironmentGlobalContext;
import com.github.otymko.jos.runtime.context.global.SystemGlobalContext;
import com.github.otymko.jos.runtime.context.sdo.ScriptDrivenObject;
import com.github.otymko.jos.runtime.context.type.TypeManager;
Expand Down Expand Up @@ -171,6 +172,7 @@ private void initOuterContext() {
outerContext.implementContext(SystemGlobalContext.class);
outerContext.implementContext(StringOperationGlobalContext.class);
outerContext.implementContext(FileOperationsGlobalContext.class);
outerContext.implementContext(SystemEnvironmentGlobalContext.class);
}

private void addGlobalContext() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.github.otymko.jos.runtime.context.global.FileOperationsGlobalContext;
import com.github.otymko.jos.runtime.context.global.GlobalContext;
import com.github.otymko.jos.runtime.context.global.StringOperationGlobalContext;
import com.github.otymko.jos.runtime.context.global.SystemEnvironmentGlobalContext;
import com.github.otymko.jos.runtime.context.global.SystemGlobalContext;
import com.github.otymko.jos.runtime.context.type.TypeManager;
import com.github.otymko.jos.runtime.machine.MachineInstance;
Expand Down Expand Up @@ -44,6 +45,7 @@ public void initialize(MachineInstance machineInstance) {
machineInstance.implementContext(new SystemGlobalContext());
machineInstance.implementContext(new StringOperationGlobalContext());
machineInstance.implementContext(new FileOperationsGlobalContext());
machineInstance.implementContext(new SystemEnvironmentGlobalContext());
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.github.otymko.jos.runtime.context.global;

import com.github.otymko.jos.core.annotation.ContextMethod;
import com.github.otymko.jos.core.annotation.GlobalContextClass;
import com.github.otymko.jos.runtime.context.AttachableContext;
import com.github.otymko.jos.runtime.context.type.ValueFactory;
import com.github.otymko.jos.runtime.context.type.collection.V8Map;
import com.github.otymko.jos.runtime.machine.info.ContextInfo;

import java.util.Map;
import java.util.TreeMap;

@GlobalContextClass
public class SystemEnvironmentGlobalContext implements AttachableContext {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, добавь, плиз, jdoc

public static final ContextInfo INFO = ContextInfo.createByClass(SystemEnvironmentGlobalContext.class);
private static final Map<String, String> environmentVariables = getEnvironmentVariablesSnapshot();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, мне не очень нравится текущее решение с static field, т.к. при многократном использовании контекста будет будут просачиваться значения из других. Давай пока сделаем синглтон + todo на исправление с DI, потом переделаем.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужен какой-то стейт на процесс выполнения (


private static Map<String, String> getEnvironmentVariablesSnapshot() {
final var result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
result.putAll(System.getenv());
return result;
}

@ContextMethod(name = "ПеременныеСреды", alias = "EnvironmentVariables")
public V8Map environmentVariables() {
var result = V8Map.constructor();
for (var envEntry: environmentVariables.entrySet()) {
result.insert(ValueFactory.create(envEntry.getKey()),
ValueFactory.create(envEntry.getValue()));
}
return result;
}

@ContextMethod(name = "ПолучитьПеременнуюСреды", alias = "getEnvironmentVariable")
public String getEnvironmentVariable(String name) {
return environmentVariables.getOrDefault(name, "");
}

@ContextMethod(name = "УстановитьПеременнуюСреды", alias = "SetEnvironmentVariable")
public void setEnvironmentVariable(String name, String value) {
environmentVariables.put(name, value);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, как это работает дальше? Ну изменили мы у себя кеш, а на систему как это влияет?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@otymko На систему никак не влияет.
В рамках работы движка скрипты будут получать значение, установленное внутри скрипта(движка).
При запуске процесса из скрипта в него будем передавать переменные отсюда.
Ну либо пилить нативную либу. Других вариантов гугель не предложил, так что тут либо костыли, либо C++

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, а в оскрипте как?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@otymko в дотнете оно из коробки умеет ставить переменные среды в ОС

https://learn.microsoft.com/ru-ru/dotnet/api/system.environment.setenvironmentvariable?view=net-7.0

}

@Override
public ContextInfo getContextInfo() {
return INFO;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.github.otymko.jos.runtime.context.type.collection.V8ValueTable;
import com.github.otymko.jos.runtime.context.type.common.V8RandomNumberGenerator;
import com.github.otymko.jos.runtime.context.type.common.V8CompareValues;
import com.github.otymko.jos.runtime.context.type.env.V8SystemInfo;
import com.github.otymko.jos.runtime.context.type.common.V8Uuid;
import com.github.otymko.jos.runtime.context.type.file.V8File;
import com.github.otymko.jos.runtime.context.type.primitive.BooleanValue;
Expand Down Expand Up @@ -99,6 +100,7 @@ private void initCollections(TypeManager typeManager) {
implementTypeByInfo(typeManager, Regex.INFO);
implementTypeByInfo(typeManager, V8File.INFO);
implementTypeByInfo(typeManager, V8RandomNumberGenerator.INFO);
implementTypeByInfo(typeManager, V8SystemInfo.INFO);

implementTypeByInfo(typeManager, V8ValueTable.INFO);
implementTypeByInfo(typeManager, V8CompareValues.INFO);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import com.github.otymko.jos.runtime.context.type.enumeration.EnumerationContext;
import com.github.otymko.jos.runtime.context.type.enumeration.MessageStatus;
import com.github.otymko.jos.runtime.context.type.enumeration.SearchDirection;
import com.github.otymko.jos.runtime.context.type.env.PlatformType;
import com.github.otymko.jos.runtime.context.type.env.SpecialFolder;
import com.github.otymko.jos.runtime.context.type.enumeration.SortDirection;
import com.github.otymko.jos.runtime.machine.info.ContextInfo;

Expand Down Expand Up @@ -42,6 +44,8 @@ private static List<EnumerationContext> getSystemEnums() {
contexts.add(AllowedSign.INFO);
contexts.add(DateFractions.INFO);
contexts.add(SearchDirection.INFO);
contexts.add(PlatformType.INFO);
contexts.add(SpecialFolder.INFO);
contexts.add(SortDirection.INFO);

return contexts;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.github.otymko.jos.runtime.context.type.env;

import com.github.otymko.jos.core.annotation.EnumClass;
import com.github.otymko.jos.core.annotation.EnumValue;
import com.github.otymko.jos.runtime.context.EnumType;
import com.github.otymko.jos.runtime.context.type.enumeration.EnumerationContext;

/**
* Содержит известные поддерживаемые типы платформ
*/
@EnumClass(name = "ТипПлатформы", alias = "PlatformType")
public enum PlatformType implements EnumType {

/**
* Операционная система семейства linux, архитектура i386
*/
@EnumValue(name = "Linux_x86", alias = "Linux_x86")
Comment thread
dmpas marked this conversation as resolved.
LINUX_X86,

/**
* Операционная система семейства linux, архитектура amd64
*/
@EnumValue(name = "Linux_x86_64", alias = "Linux_x86_64")
LINUX_X86_64,

/**
* Операционная система Mac OS X, архитектура i386
*/
@EnumValue(name = "MacOS_x86", alias = "MacOS_x86")
MACOS_X86,

/**
* Операционная система семейства Mac OS X, архитектура amd64
*/
@EnumValue(name = "MacOS_x86_64", alias = "MacOS_x86_64")
MACOS_X86_64,

/**
* Операционная система семейства WinNT, архитектура i386
*/
@EnumValue(name = "Windows_x86", alias = "Windows_x86")
WINDOWS_X86,

/**
* Операционная система семейства WinNT, архитектура amd64
*/
@EnumValue(name = "Windows_x86_64", alias = "Windows_x86_64")
WINDOWS_X86_64,

/**
* Неизвестная операционная система
*/
@EnumValue(name = "Unknown", alias = "Unknown")
UNKNOWN;

public static final EnumerationContext INFO = new EnumerationContext(PlatformType.class);

/**
* Определяет тип платформы по строковому представлению операционной системы
* @param osName Строковое представление операционной системы
* @param is64 Признак 64-битной архитектуры
* @return Определенный тип платформы
*/
public static PlatformType parse(String osName, boolean is64) {
var prepared = osName.toUpperCase();
if (prepared.contains("WINDOWS"))
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, узоры: скобочки { }

return is64 ? WINDOWS_X86_64 : WINDOWS_X86;
if (prepared.contains("LINUX"))
return is64 ? LINUX_X86_64 : LINUX_X86;
if (prepared.contains("MAC OS"))
return is64 ? MACOS_X86_64 : MACOS_X86;
return PlatformType.UNKNOWN;
}

@Override
public EnumerationContext getContextInfo() {
return INFO;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.github.otymko.jos.runtime.context.type.env;

import com.github.otymko.jos.core.annotation.EnumClass;
import com.github.otymko.jos.runtime.context.EnumType;
import com.github.otymko.jos.runtime.context.type.enumeration.EnumerationContext;

/**
* Содержит известные поддерживаемые специальные типы каталогов
*/
@EnumClass(name = "СпециальнаяПапка", alias = "SpecialFolder")
public enum SpecialFolder implements EnumType {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, заглушка же, верно? А кинь плиз issue если нет и сюда TODO

;
public static final EnumerationContext INFO = new EnumerationContext(SpecialFolder.class);
@Override
public EnumerationContext getContextInfo() {
return INFO;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.github.otymko.jos.runtime.context.type.env;

import com.github.otymko.jos.core.PropertyAccessMode;
import com.github.otymko.jos.core.annotation.ContextClass;
import com.github.otymko.jos.core.annotation.ContextConstructor;
import com.github.otymko.jos.core.annotation.ContextProperty;
import com.github.otymko.jos.exception.MachineException;
import com.github.otymko.jos.runtime.context.ContextValue;
import com.github.otymko.jos.runtime.machine.info.ContextInfo;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

/**
* Содержит описание ключевых параметров среды исполнения
*/
@NoArgsConstructor
@ContextClass(name = "СистемнаяИнформация", alias = "SystemInfo")
public class V8SystemInfo extends ContextValue {
public static final ContextInfo INFO = ContextInfo.createByClass(V8SystemInfo.class);

/**
* Создает новый объект СистеимнаяИнформация
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, опечатка в "СистеИмная"

*
* @return СистемнаяИнформация
*/
@ContextConstructor
public static V8SystemInfo constructor() {
return new V8SystemInfo();
}

/**
* Возвращает версию движка среды исполнения
*
* @return Строка с версией движка
*/
@ContextProperty(name = "Версия", alias = "Version", accessMode = PropertyAccessMode.READ_ONLY)
public String getVersion() {
var manifestStream = Thread.currentThread()
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, давай вынесем в утилиты? Я думаю это значение еще нам понадобится.

.getContextClassLoader()
.getResourceAsStream("META-INF/MANIFEST.MF");
var manifest = new Manifest();
try {
manifest.read(manifestStream);
} catch (IOException e) {
return "";
}
var versionFromFile = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
return versionFromFile == null ? "" : versionFromFile;
}

/**
* Возвразщает имя компьютера среды исполнения
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, опечатка в "ВозвраЗщает"

*
* @return Имя компьютера
*/
@ContextProperty(name = "ИмяКомпьютера", alias = "MachineName")
public String getMachineName() {
throw MachineException.operationNotImplementedException();
}

/**
* Возвращает имя и версию операцинной системы среды исполнения
*
* @return Имя и версия операционной системы
*/
@ContextProperty(name = "ВерсияОС", alias = "OSVersion")
public String getOsVersion() {
return String.format("%s %s",
System.getProperty("os.name"),
System.getProperty("os.version"));
}

/**
* Возвращает тип платформы среды исполнения
* @return Тип платформы
*/
@ContextProperty(name = "ТипПлатформы", alias = "PlatformType")
public PlatformType getPlatformType() {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, давай тоже вынесем в утилиты.

var is64 = getIs64bitOperatingSystem();
var osName = System.getProperty("os.name");
return PlatformType.parse(osName, is64);
}

/**
* Возвращает пользователя операционной системы, от имени которого исполняется скрипт
* @return Имя пользователя ОС
*/
@ContextProperty(name = "ПользовательОС", alias = "OSUser")
public String getOsUser() {
return System.getProperty("user.name");
}

/**
* Возвращает признак 64-битной операционной системы
*
* @return Признак 64-битной ОС
*/
@ContextProperty(name = "Это64БитнаяОперационнаяСистема", alias = "Is64bitOperatingSystem")
public boolean getIs64bitOperatingSystem() {
var arch = System.getProperty("os.arch");
return arch.endsWith("64");
}

/**
* Возвращает количество процессоров текущей среды исполнения
*
* @return Количество процессоров
*/
@ContextProperty(name = "КоличествоПроцессоров", alias = "ProcessorCount")
public int getProcessorCount() {
return Runtime.getRuntime().availableProcessors();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, кстати, в v8 возвращается количество физический или логических процессоров?

}

/**
* Возвращает размер страницы оперативной памяти текущей среды исполнения
*
* @return Размер страницы
*/
@ContextProperty(name = "РазмерСтраницы", alias = "SystemPageSize")
public int getSystemPageSize() {
throw MachineException.operationNotImplementedException();
}

/**
* Возвращает время работы с момента загрузки системы
*
* @return Время в миллисекундах
*/
@ContextProperty(name = "ВремяРаботыСМоментаЗагрузки", alias = "TickCount")
public long getTickCount() {
return System.currentTimeMillis();
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dmpas, System.currentTimeMillis возвращает не ВремяРаботыСМоментаЗагрузки. Смотри как в https://github.com/oshi/oshi работает getSystemUptime

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно здесь закинуть нон-саппортед, а а отдельной задаче реализовать.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@otymko getSystemUptime - там ад, если честно. Куча if (os1) get_os1(); if (os2) get_os2();

}

@Override
public ContextInfo getContextInfo() {
return INFO;
}
}
Loading