Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

216 fix issue where pyjnius is loaded from global context #217

Merged
Merged
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
Empty file modified ci/linux/lint.sh
100644 → 100755
MichielTukker marked this conversation as resolved.
Show resolved Hide resolved
Empty file.
16 changes: 6 additions & 10 deletions src/omotes_simulator_core/entities/assets/ates_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,12 @@
from omotes_simulator_core.entities.assets.asset_defaults import ATES_DEFAULTS

from omotes_simulator_core.entities.assets.esdl_asset_object import EsdlAssetObject
from omotes_simulator_core.entities.assets.pyjnius_loader import PyjniusLoader
from omotes_simulator_core.solver.network.assets.production_asset import ProductionAsset
from omotes_simulator_core.entities.assets.utils import (
heat_demand_and_temperature_to_mass_flow,
)

path = os.path.dirname(__file__)
import jnius_config # noqa

jnius_config.add_classpath(os.path.join(path, "bin/jfxrt.jar"))
jnius_config.add_classpath(os.path.join(path, "bin/rosim-batch-0.4.2.jar"))
from jnius import autoclass # noqa

javaioFile = autoclass("java.io.File")
RosimSequential = autoclass("tno.calc.RosimSequential")


class AtesCluster(AssetAbstract):
"""A AtesCluster represents an asset that consumes heat and produces heat."""
Expand Down Expand Up @@ -93,6 +84,8 @@ def __init__(self, asset_name: str, asset_id: str, port_ids: list[str]):
# Output list
self.output: list = []

self.pyjnius_loader = PyjniusLoader.get_loader()

def _calculate_massflowrate(self) -> None:
"""Calculate mass flowrate of the asset."""
self.mass_flowrate = heat_demand_and_temperature_to_mass_flow(
Expand Down Expand Up @@ -208,6 +201,7 @@ def write_to_output(self) -> None:

def _init_rosim(self) -> None:
"""Function to initailized Rosim from XML file."""
path = os.path.dirname(__file__)
xmlfile = os.path.join(path, "bin/sequentialTemplate_v0.4.2_template.xml")
with open(xmlfile, "r") as fd:
xml_str = fd.read()
Expand Down Expand Up @@ -251,6 +245,8 @@ def _init_rosim(self) -> None:
with open(temp_xmlfile_path, "w") as temp_xmlfile:
temp_xmlfile.write(xml_str)

javaioFile = self.pyjnius_loader.load_class("java.io.File")
RosimSequential = self.pyjnius_loader.load_class("tno.calc.RosimSequential")
xmlfilejava = javaioFile(temp_xmlfile_path)
self.rosim = RosimSequential(xmlfilejava, False, 2)

Expand Down
74 changes: 74 additions & 0 deletions src/omotes_simulator_core/entities/assets/pyjnius_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright (c) 2023. Deltares & TNO
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""Binding to Rosim through Pyjnius."""

import os
from typing import Dict, Callable

JavaClass = Callable


class PyjniusLoader:
"""Class to load Pyjnius and connect to Rosim.

This is a singleton and you should only use PyjniusLoader.get_loader() instead of
constructing this class directly.

Also ensure that after loading this class, the process is not forked into a subprocess
as this will destroy the connection to Pyjnius and may lead to an indefinite hang when using
Java code.
"""

INSTANCE = None
loaded_classes: Dict[str, JavaClass]

def __init__(self) -> None:
"""Create an instance of PyjniusLoader.

This function should only be called ONCE. Do not use construct this class directly
but rather use `PyjniusLoader.get_loader`.
"""
path = os.path.dirname(__file__)
import jnius_config # noqa

jnius_config.add_classpath(os.path.join(path, "bin/jfxrt.jar"))
jnius_config.add_classpath(os.path.join(path, "bin/rosim-batch-0.4.2.jar"))

self.loaded_classes = {}

def load_class(self, classpath: str) -> JavaClass:
"""Load a Java class.

If it has been loaded previously, the reference to the class will be laoded from cache.
MichielTukker marked this conversation as resolved.
Show resolved Hide resolved
Otherwise, it is loaded through pyjnius.

"""
from jnius import autoclass # noqa
if classpath not in self.loaded_classes:
self.loaded_classes[classpath] = autoclass(classpath)

return self.loaded_classes[classpath]

@staticmethod
def get_loader() -> 'PyjniusLoader':
"""Get the global instance of the PyjniusLoader.

This loader allows to load Java classes. This is the preferred method of retrieving
a reference to the PyjniusLoader.
"""
if PyjniusLoader.INSTANCE is None:
PyjniusLoader.INSTANCE = PyjniusLoader()
return PyjniusLoader.INSTANCE
Loading