### Start Standalone Server Source: https://github.com/greendelta/olca-modules/blob/master/olca-proto-io/README.md Starts the standalone olca-proto gRPC server. Requires specifying the database name and optionally a port number. ```bash run -db [-port ] ``` -------------------------------- ### Interact with IPC Server using cURL (Bash) Source: https://context7.com/greendelta/olca-modules/llms.txt Demonstrates how to interact with the running openLCA IPC server using cURL. It shows examples for retrieving data descriptors, specific data sets, inserting/updating data, calculating product systems, getting total impacts, and disposing of results. All requests are formatted as JSON-RPC 2.0. ```bash # Get all process descriptors curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "data/get/descriptors", "params": {"@type": "Process"} }' # Get a specific flow by ID curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 2, "method": "data/get", "params": {"@type": "Flow", "@id": "abc-123-def"} }' # Insert or update a data set curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 3, "method": "data/put", "params": { "@type": "Actor", "@id": "new-actor-id", "name": "Research Institute", "email": "contact@institute.org" } }' # Calculate a product system curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 4, "method": "result/calculate", "params": { "target": {"@type": "ProductSystem", "@id": "system-id"}, "impactMethod": {"@type": "ImpactMethod", "@id": "method-id"}, "withCosts": true } }' # Get total impacts from a calculated result curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 5, "method": "result/total-impacts", "params": {"@id": "result-state-id"} }' # Dispose of a result when done curl -X POST http://localhost:8080 \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 6, "method": "result/dispose", "params": {"@id": "result-state-id"} }' ``` -------------------------------- ### Starting and Configuring the IPC Server in Java Source: https://github.com/greendelta/olca-modules/blob/master/olca-ipc/README.md Shows how to initialize and start the openLCA IPC server in Java. It covers both using default handlers and registering custom handlers for specific methods. ```java Server server = new Server(8080); server.withDefaultHandlers(aDatabase, aMatrixSolver); server.start(); ``` ```java server.register(aHandler1); server.register(aHandler2); // ... ``` -------------------------------- ### IPC Server - Starting and Configuration Source: https://context7.com/greendelta/olca-modules/llms.txt This section describes how to start and configure the IPC server, which provides JSON-RPC over HTTP for remote access to openLCA functionality. ```APIDOC ## Starting the IPC Server The IPC server provides JSON-RPC over HTTP for remote access to openLCA functionality from any programming language. ### Method ```java // Configure the server Derby db = new Derby(new java.io.File("my-database")); ServerConfig config = ServerConfig.defaultOf(db) .withPort(8080); // Start server with default handlers Server server = new Server(config) .withDefaultHandlers(); server.start(); System.out.println("IPC server running on port " + server.getListeningPort()); // Server will handle requests until stopped // server.stop(); ``` ``` -------------------------------- ### Start Apache Derby ij Tool Source: https://github.com/greendelta/olca-modules/blob/master/doc/derby_ij.md Command to start the Apache Derby ij scripting tool. Requires the Derby JAR files to be in a 'lib' folder and the JAVA_HOME environment variable to be set. ```shell java -cp "lib/derby.jar;lib/derbytools.jar" org.apache.derby.tools.ij ``` -------------------------------- ### Start IPC Server with Default Handlers (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt Configures and starts the openLCA IPC server, making openLCA functionalities accessible remotely. It requires the 'org.openlca.core' and 'org.openlca.ipc' libraries. The server listens on a specified port and handles requests until explicitly stopped. ```java import org.openlca.core.database.Derby; import org.openlca.core.services.ServerConfig; import org.openlca.ipc.Server; // Configure the server Derby db = new Derby(new java.io.File("my-database")); ServerConfig config = ServerConfig.defaultOf(db) .withPort(8080); // Start server with default handlers Server server = new Server(config) .withDefaultHandlers(); server.start(); System.out.println("IPC server running on port " + server.getListeningPort()); // Server will handle requests until stopped // server.stop(); ``` -------------------------------- ### Build openLCA Modules from Source Source: https://github.com/greendelta/olca-modules/blob/master/README.md Instructions for building the openLCA modules from their source code. This process requires a JDK version of 21 or higher and Maven 3. The commands clone the repository, navigate into the directory, and install the modules locally. ```bash git clone https://github.com/GreenDelta/olca-modules.git cd olca-modules mvn install ``` -------------------------------- ### IPC Server Configuration and Usage Source: https://github.com/greendelta/olca-modules/blob/master/olca-ipc/README.md This section details how to start and configure the IPC server, including registering default handlers or custom method handlers. ```APIDOC ## IPC Server Operations ### Description Demonstrates how to start an IPC server and configure its handlers for processing method calls. ### Method N/A (Server initialization and configuration) ### Endpoint N/A (Server runs locally on a specified port) ### Parameters #### Server Initialization - **port** (integer) - Required - The port number on which the server will listen for incoming connections. - **aDatabase** (object) - Required (for `withDefaultHandlers`) - An object representing the database to be used by default handlers. - **aMatrixSolver** (object) - Required (for `withDefaultHandlers`) - An object representing the matrix solver to be used by default handlers. #### Method Handlers - **handler** (object) - Required (for `register`) - An object containing methods annotated with `@Rpc` to handle specific method calls. ### Request Example ```java // Starting server with default handlers Server server = new Server(8080); server.withDefaultHandlers(aDatabase, aMatrixSolver); server.start(); // Starting server with custom handlers server.register(aHandler1); server.register(aHandler2); ``` ### Response #### Success Response (Server Start) - **status** (string) - Indicates the server has started successfully. #### Response Example (No direct response for server start, but subsequent method calls will return results or errors.) ### Handler Method Requirements - Methods must be declared `public`. - Methods must be annotated with `@Rpc("method/name")` specifying a unique method name. - Methods must accept a single parameter of type `RpcRequest`. - Methods must return a result of type `RpcResponse`. ### Handler Method Example ```java public class MyHandler { @Rpc("my/method") public RpcResponse myMethod(RpcRequest req) { return Responses.of("Works!", req); } } ``` ``` -------------------------------- ### Implementing an IPC Handler in Java Source: https://github.com/greendelta/olca-modules/blob/master/olca-ipc/README.md Provides an example of a Java class that can be used as a handler for the IPC server. It illustrates the requirements for handler methods, including the @Rpc annotation, parameter types, and return types. ```java public class MyHandler { @Rpc("my/method") public RpcResponse myMethod(RpcRequest req) { return Responses.of("Works!", req); } } ``` -------------------------------- ### Data Import - EcoSpold 2 Import Source: https://context7.com/greendelta/olca-modules/llms.txt This section provides instructions and code examples for importing datasets from EcoSpold 2 format files into an openLCA database. ```APIDOC ## EcoSpold 2 Import Import datasets from ecoinvent or other EcoSpold 2 format files. ### Method ```java import org.openlca.core.database.Derby; import org.openlca.io.ecospold2.input.EcoSpold2Import; import org.openlca.io.ecospold2.input.ImportConfig; import java.io.File; Derby db = new Derby(new java.io.File("target-database")); // Configure import ImportConfig config = new ImportConfig(db); // Create and run import EcoSpold2Import importer = new EcoSpold2Import(config); importer.setFiles(new File[]{ new File("datasets/activity1.spold"), new File("datasets/activity2.spold"), new File("ecoinvent_data.zip") // ZIP files are also supported }); // Run the import (imports reference data first, then processes) importer.run(); // Check import log for any issues var log = importer.log(); System.out.println("Import completed"); System.out.println("Imported: " + log.imported().size() + " datasets"); db.close(); ``` ### Description This process involves configuring an `ImportConfig` with the target database, specifying the files or ZIP archives containing EcoSpold 2 data, and then executing the import using `EcoSpold2Import`. The import log can be accessed to review the outcome. ``` -------------------------------- ### IPC Server - Calling Endpoints Source: https://context7.com/greendelta/olca-modules/llms.txt Examples of how to call the IPC server using `curl` for various operations like retrieving data, inserting/updating datasets, and performing calculations. ```APIDOC ## Calling the IPC Server Use curl or any HTTP client to interact with the running server. All requests use JSON-RPC 2.0 format. ### Method POST ### Endpoint `http://localhost:8080` ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC protocol version. - **id** (integer) - Required - A unique identifier for the request. - **method** (string) - Required - The RPC method to be called (e.g., `data/get/descriptors`, `data/get`, `data/put`, `result/calculate`, `result/total-impacts`, `result/dispose`). - **params** (object) - Optional - Parameters for the RPC method. #### Request Example (Get all process descriptors) ```json { "jsonrpc": "2.0", "id": 1, "method": "data/get/descriptors", "params": {"@type": "Process"} } ``` #### Request Example (Get a specific flow by ID) ```json { "jsonrpc": "2.0", "id": 2, "method": "data/get", "params": {"@type": "Flow", "@id": "abc-123-def"} } ``` #### Request Example (Insert or update a data set) ```json { "jsonrpc": "2.0", "id": 3, "method": "data/put", "params": { "@type": "Actor", "@id": "new-actor-id", "name": "Research Institute", "email": "contact@institute.org" } } ``` #### Request Example (Calculate a product system) ```json { "jsonrpc": "2.0", "id": 4, "method": "result/calculate", "params": { "target": {"@type": "ProductSystem", "@id": "system-id"}, "impactMethod": {"@type": "ImpactMethod", "@id": "method-id"}, "withCosts": true } } ``` #### Request Example (Get total impacts from a calculated result) ```json { "jsonrpc": "2.0", "id": 5, "method": "result/total-impacts", "params": {"@id": "result-state-id"} } ``` #### Request Example (Dispose of a result when done) ```json { "jsonrpc": "2.0", "id": 6, "method": "result/dispose", "params": {"@id": "result-state-id"} } ``` ``` -------------------------------- ### IDatabase Interface Operations in Java Source: https://context7.com/greendelta/olca-modules/llms.txt Provides a common API for database implementations, supporting CRUD operations, transactions, and library management. This example uses the Derby implementation and demonstrates batch operations within a transaction, working with descriptors, and managing linked libraries. Requires org.openlca.core.database.IDatabase. ```java import org.openlca.core.database.IDatabase; import org.openlca.core.database.Derby; import org.openlca.core.model.*; import org.openlca.core.model.descriptors.RootDescriptor; IDatabase db = new Derby(new java.io.File("my-database")); // Transaction support for batch operations db.transaction(em -> { Flow flow1 = new Flow(); flow1.name = "Product A"; flow1.flowType = FlowType.PRODUCT_FLOW; em.persist(flow1); Flow flow2 = new Flow(); flow2.name = "Product B"; flow2.flowType = FlowType.PRODUCT_FLOW; em.persist(flow2); }); // Work with descriptors for better performance var descriptors = db.getDescriptors(Process.class); for (RootDescriptor d : descriptors) { System.out.println(d.name + " [" + d.refId + "]"); } // Library management db.addLibrary("ecoinvent_3.9"); var libs = db.getLibraries(); System.out.println("Linked libraries: " + libs); // Clear entity cache after native SQL modifications db.clearCache(); // Check database version System.out.println("DB Version: " + db.getVersion()); System.out.println("Current Schema: " + IDatabase.CURRENT_VERSION); ``` -------------------------------- ### Execute SQL Query in ij Source: https://github.com/greendelta/olca-modules/blob/master/doc/derby_ij.md Example of executing a simple SQL SELECT statement to retrieve data from a database table using the ij tool. ```sql select id, name from tbl_units; ``` -------------------------------- ### Introduction to openLCA Core API Source: https://github.com/greendelta/olca-modules/blob/master/doc/api_doc_prelude.md This section explains how to read the API documentation, including the structure of headings for packages, types, fields, and methods. It also covers the API's compatibility with JVM languages and its integration with openLCA's Python scripting. ```APIDOC ## Introduction to openLCA Core API ### Description This document contains the documentation of the openLCA core API, automatically extracted from the Java documentation of the [olca-modules repository](https://github.com/GreenDelta/olca-modules) (using the [jmd tool](https://github.com/msrocka/jmd)). The headings of this document follow the structure of the API: 1. Packages (e.g. `org.openlca.core.results`) 2. Types (mainly classes), e.g. `ContributionResult` 3. Fields (e.g. `techIndex`) and methods (e.g. `getFlows()`) A heading `TypeB > TypeA` means that the following section is about `TypeB` which extends `TypeA` and, thus, has all the methods and fields that `TypeA` has. The heading `fieldC : TypeD` means that `fieldC` is an accessible field (a property) of type `TypeD`. Finally, a heading `methodG(): TypeE` means that `methodG` is a callable method that returns an instance of `TypeE`. The parameters of that method are directly listed after the heading in the same order as they need to be applied when calling the method. Methods that have the same name as their type (like `TypeG()`) are constructor methods which create a new instance of that type. The openLCA core API is a plain Java API that should run on any Java Virtual Machine (JVM) >= v8. Thus, you could use it from any JVM language like Java, Scala, Kotlin, Clojure, Jython, etc. It is also fully exposed to the openLCA development tools within openLCA (`Window > Developer tools > Python` within openLCA). The Python scripting environment in openLCA uses [Jython](http://www.jython.org/) (a Python implementation that runs on the JVM). ### Example Usage (Python) ```python # import the type 'FlowDao' from the package # 'org.openlca.core.database' from org.openlca.core.database import FlowDao # create a new instance of "FlowDao" by calling # its constructor method and passing a database # instance as parameter dao = FlowDao(db) # get all flows by calling the method "getAll" # on the instance of the FlowDao type flows = dao.getAll() # writing the value of the field "name" of the # first flow to the logger output log.info("Name of the first flow: {}", flows[0].name) ``` ``` -------------------------------- ### Build Standalone Server with Maven Source: https://github.com/greendelta/olca-modules/blob/master/olca-proto-io/README.md Builds the standalone server application using the 'server-app' Maven profile. This generates a runnable server in the 'target/olca-grpc-server' directory. ```bash mvn package -P server-app ``` -------------------------------- ### Build and Run gRPC Server Source: https://context7.com/greendelta/olca-modules/llms.txt Instructions for building and running the openLCA gRPC server, which enables high-performance Protocol Buffers communication. The server connects to an openLCA database folder and can be configured with custom data directories and ports. ```bash # Build the standalone server cd olca-proto-io mvn package -P server-app # Run the server # Server connects to openLCA database folder ./target/olca-grpc-server/run -db ecoinvent38 -port 8080 # With custom data directory ./target/olca-grpc-server/run -data ~/my-openlca-data -db mydb -port 9999 ``` -------------------------------- ### Build openLCA Modules from Source (Skipping Tests) Source: https://github.com/greendelta/olca-modules/blob/master/README.md This command allows building the openLCA modules from source while skipping any failing tests. This can be useful for development or when tests are not critical for the immediate build process. It uses the same prerequisites as the standard build. ```bash mvn install -DskipTests=true ``` -------------------------------- ### Create and Serialize Flow with Protocol Buffers (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt Demonstrates how to create a 'Flow' object using Protocol Buffers in Java, serialize it to JSON, and then parse it back from JSON. It also shows serialization to a binary format for efficient storage and transmission. ```java import org.openlca.proto.generated.Proto; import com.google.protobuf.util.JsonFormat; import java.util.UUID; // Create a flow using Protocol Buffers Proto.Flow flow = Proto.Flow.newBuilder() .setType("Flow") .setId(UUID.randomUUID().toString()) .setName("Steel") .setFlowType(Proto.FlowType.PRODUCT_FLOW) .setDescription("Hot rolled steel product") .build(); // Convert to JSON String json = JsonFormat.printer().print(flow); System.out.println(json); // Output: // { // "@type": "Flow", // "@id": "481682dd-c2a2-4646-9760-b0fe3e242676", // "name": "Steel", // "flowType": "PRODUCT_FLOW", // "description": "Hot rolled steel product" // } // Parse from JSON Proto.Flow.Builder builder = Proto.Flow.newBuilder(); JsonFormat.parser().merge(json, builder); Proto.Flow parsed = builder.build(); System.out.println("Parsed flow: " + parsed.getName()); // Serialize to binary (very efficient) byte[] binary = flow.toByteArray(); Proto.Flow fromBinary = Proto.Flow.parseFrom(binary); ``` -------------------------------- ### Import EcoSpold 2 Datasets (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt Details the process of importing datasets from EcoSpold 2 format files into an openLCA database. It utilizes the 'org.openlca.core' and 'org.openlca.io.ecospold2' libraries. The import process can handle individual files or ZIP archives and provides a log of imported datasets. ```java import org.openlca.core.database.Derby; import org.openlca.io.ecospold2.input.EcoSpold2Import; import org.openlca.io.ecospold2.input.ImportConfig; import java.io.File; Derby db = new Derby(new java.io.File("target-database")); // Configure import ImportConfig config = new ImportConfig(db); // Create and run import EcoSpold2Import importer = new EcoSpold2Import(config); importer.setFiles(new File[]{ new File("datasets/activity1.spold"), new File("datasets/activity2.spold"), new File("ecoinvent_data.zip") // ZIP files are also supported }); // Run the import (imports reference data first, then processes) importer.run(); // Check import log for any issues var log = importer.log(); System.out.println("Import completed"); System.out.println("Imported: " + log.imported().size() + " datasets"); db.close(); ``` -------------------------------- ### Generate JSON from Java Proto Object Source: https://github.com/greendelta/olca-modules/blob/master/olca-proto-io/README.md Demonstrates how to create a 'Flow' proto object in Java and serialize it to a JSON string using Google's JsonFormat utility. This requires the 'org.openlca.generated.proto' and 'com.google.protobuf.util.JsonFormat' classes. ```java import org.openlca.generated.proto; import com.google.protobuf.util.JsonFormat; var flow = Proto.Flow.newBuilder() .setType("Flow") .setId(UUID.randomUUID().toString()) .setName("Steel") .setFlowType(Proto.FlowType.PRODUCT_FLOW) .build(); var json = JsonFormat.printer().print(flow); System.out.println(json); ``` -------------------------------- ### Representing Different Flows in eILCD and openLCA Source: https://github.com/greendelta/olca-modules/blob/master/doc/eilcd.md Illustrates how the eILCD format allows linking processes with different flows, whereas openLCA requires a connector process to bridge such links. This is a common workaround for discrepancies in flow property handling. ```text eILCD link with different flows: +---------------+ +---------------+ |process1::flow1| --> |flow2::process2| +---------------+ +---------------+ import result in openLCA +---------------+ +-----------------------+ +---------------+ |process1::flow1| --> |flow1::connector::flow2| --> |flow2::process2| +---------------+ +-----------------------+ +---------------+ ``` -------------------------------- ### Accessing FlowDao in Python Source: https://github.com/greendelta/olca-modules/blob/master/doc/api_doc_prelude.md This Python snippet demonstrates how to import the 'FlowDao' type from the 'org.openlca.core.database' package, create an instance of 'FlowDao', retrieve all flows, and log the name of the first flow. It requires a database instance to be available. ```python # import the type 'FlowDao' from the package # 'org.openlca.core.database' from org.openlca.core.database import FlowDao # create a new instance of "FlowDao" by calling # its constructor method and passing a database # instance as parameter dao = FlowDao(db) # get all flows by calling the method "getAll" # on the instance of the FlowDao type flows = dao.getAll() # writing the value of the field "name" of the # first flow to the logger output log.info("Name of the first flow: {}", flows[0].name) ``` -------------------------------- ### Sync LCA Database with Git Repository (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt This code snippet shows how to use the olca-git module to synchronize an openLCA database with a Git repository. It demonstrates opening a Git repository, committing the current database state, and provides insights into the repository's structure. ```java import org.openlca.git.repo.OlcaRepository; import org.openlca.git.writer.DbCommitWriter; import org.openlca.core.database.Derby; import java.io.File; Derby db = new Derby(new java.io.File("my-database")); // Open or create a bare Git repository File repoDir = new File("database.git"); OlcaRepository repo = OlcaRepository.open(repoDir); // Commit current database state DbCommitWriter writer = new DbCommitWriter(repo) .database(db) .as("user@example.com") .withMessage("Initial commit of LCA database"); String commitId = writer.write(); System.out.println("Committed: " + commitId); // Repository structure stores data as: // - Root tree links to model type sub-trees (flows, processes, etc.) // - Category sub-trees contain data set blobs // - Blob names: _.json // - Supports both JSON and Protocol Buffers format repo.close(); db.close(); ``` -------------------------------- ### Import EcoSpold 02 Files using openLCA API Source: https://github.com/greendelta/olca-modules/blob/master/olca-io/README.md This code snippet demonstrates how to import a set of EcoSpold 02 files using the openLCA API. The import process handles '*.spold' files and '*.zip' files containing them. It first imports reference data like flows and categories, then imports and links processes by mapping activity-link fields. ```java EcoSpold2Import es2Import = new EcoSpold2Import(aDatabase); es2Import.run(anArrayOfFiles); ``` -------------------------------- ### Register Custom RPC Handler (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt Shows how to extend the IPC server's functionality by registering custom RPC methods. This involves creating a class with methods annotated with `@Rpc` and then registering an instance of this class with the server. Dependencies include 'org.openlca.ipc' and 'com.google.gson'. ```java import org.openlca.ipc.*; public class CustomHandler { @Rpc("custom/hello") public RpcResponse hello(RpcRequest req) { var name = req.params != null ? req.params.getAsJsonObject().get("name").getAsString() : "World"; return Responses.of("Hello, " + name + "!", req); } @Rpc("custom/calculate-footprint") public RpcResponse calculateFootprint(RpcRequest req) { // Custom calculation logic here var result = new com.google.gson.JsonObject(); result.addProperty("carbonFootprint", 123.45); result.addProperty("unit", "kg CO2-eq"); return Responses.of(result, req); } } // Register the handler with server server.register(new CustomHandler()); ``` -------------------------------- ### Perform Basic LCA Calculation on a Product System Source: https://context7.com/greendelta/olca-modules/llms.txt Calculates LCA results for a given product system, supporting sub-system calculations and various allocation methods. It loads a product system from a database, configures calculation parameters like amount, allocation method, and impact assessment, then executes the calculation. Finally, it accesses and prints inventory, impact assessment, and cost results. ```java import org.openlca.core.database.Derby; import org.openlca.core.math.SystemCalculator; import org.openlca.core.model.*; import org.openlca.core.results.LcaResult; Derby db = new Derby(new java.io.File("ecoinvent-db")); // Load a product system ProductSystem system = db.get(ProductSystem.class, "system-ref-id"); // Create calculation setup CalculationSetup setup = CalculationSetup.of(system) .withAmount(1000) // 1000 units of reference flow .withAllocation(AllocationMethod.PHYSICAL) // Physical allocation .withCosts(true) // Include life cycle costs .withRegionalization(false); // No regionalized results // Optionally add impact assessment ImpactMethod method = db.get(ImpactMethod.class, "method-ref-id"); setup.withImpactMethod(method); // Run calculation SystemCalculator calculator = new SystemCalculator(db); LcaResult result = calculator.calculate(setup); // Access inventory results (elementary flows) var totalFlows = result.getTotalFlows(); for (var flowValue : totalFlows) { System.out.printf("%s: %.4f %s%n", flowValue.enviFlow().flow().name, flowValue.value(), flowValue.enviFlow().flow().referenceUnit.name); } // Access impact assessment results if (result.hasImpacts()) { var impacts = result.getTotalImpacts(); for (var impact : impacts) { System.out.printf("%s: %.4f %s%n", impact.impact().name, impact.value(), impact.impact().referenceUnit); } } // Get total costs if (result.hasCosts()) { System.out.println("Total costs: " + result.getTotalCosts()); } // Clean up resources result.dispose(); db.close(); ``` -------------------------------- ### Custom RPC Handler Source: https://context7.com/greendelta/olca-modules/llms.txt This section explains how to register custom RPC methods to extend the server's functionality. ```APIDOC ## Custom RPC Handler Register custom methods to extend the server's functionality. ### Method ```java public class CustomHandler { @Rpc("custom/hello") public RpcResponse hello(RpcRequest req) { var name = req.params != null ? req.params.getAsJsonObject().get("name").getAsString() : "World"; return Responses.of("Hello, " + name + "!", req); } @Rpc("custom/calculate-footprint") public RpcResponse calculateFootprint(RpcRequest req) { // Custom calculation logic here var result = new com.google.gson.JsonObject(); result.addProperty("carbonFootprint", 123.45); result.addProperty("unit", "kg CO2-eq"); return Responses.of(result, req); } } // Register the handler with server server.register(new CustomHandler()); ``` ### Description Custom RPC handlers allow you to define new endpoints and logic that can be called remotely via the IPC server. Annotate methods with `@Rpc("your/method/path")` and implement the `RpcResponse` logic. Register the handler instance with `server.register()`. ``` -------------------------------- ### eILCD Process Instance XML Structure Source: https://github.com/greendelta/olca-modules/blob/master/doc/eilcd.md This XML snippet illustrates the structure of a process instance within the eILCD format. It includes a dataSetInternalID, a reference to the process, group memberships, and connections to other process instances. This structure is fundamental for defining the occurrences of processes in a life cycle model. ```xml ... ... ... ... ``` -------------------------------- ### eILCD Process Instance to Group Linking XML Source: https://github.com/greendelta/olca-modules/blob/master/doc/eilcd.md This XML snippet demonstrates how a process instance is linked to a declared group (life cycle stage) in the eILCD format. It uses the 'memberOf' element with the groupId attribute to establish this relationship, allowing for the modeling of processes in different life cycle phases. ```xml ... ... ``` -------------------------------- ### Run SQL Script File with ij Source: https://github.com/greendelta/olca-modules/blob/master/doc/derby_ij.md Executes a SQL script file using the 'run' command within the ij tool. This is useful for automating complex database operations like bulk exports. ```sql run 'csv_export.sql'; ``` -------------------------------- ### Making IPC Method Calls via HTTP POST Source: https://github.com/greendelta/olca-modules/blob/master/olca-ipc/README.md This section explains how to make method calls to the openLCA IPC server using HTTP POST requests, including the use of curl. ```APIDOC ## Making IPC Method Calls via HTTP POST ### Description This endpoint allows you to send JSON-RPC method calls to the openLCA IPC server using an HTTP POST request. The request body should contain the method call details, and the response will contain the result or an error. ### Method POST ### Endpoint `http://localhost:8080` (or the configured server address and port) ### Parameters #### Request Body - **method** (string) - Required - The name of the method to be called (e.g., "my/method"). - **params** (array) - Optional - An array of parameters to be passed to the method. - **id** (string or integer) - Required - A unique identifier for the request. - **jsonrpc** (string) - Required - The version of the JSON-RPC protocol, typically "2.0". ### Request Example ```bash curl -X POST http://localhost:8080 -d @file.json -H "Content-Type: application/json" ``` **file.json content:** ```json { "jsonrpc": "2.0", "method": "my/method", "params": [], "id": 1 } ``` ### Response #### Success Response (200) - **result** (any) - The result returned by the called method. - **id** (string or integer) - The identifier of the request. - **jsonrpc** (string) - The version of the JSON-RPC protocol, typically "2.0". #### Error Response (e.g., 400, 500) - **error** (object) - An object containing error details. - **code** (integer) - The error code. - **message** (string) - A description of the error. - **id** (string or integer) - The identifier of the request. - **jsonrpc** (string) - The version of the JSON-RPC protocol, typically "2.0". #### Response Example (Success) ```json { "jsonrpc": "2.0", "result": "Works!", "id": 1 } ``` #### Response Example (Error) ```json { "jsonrpc": "2.0", "error": { "code": -32601, "message": "Method not found" }, "id": 1 } ``` ``` -------------------------------- ### Manage Core Model Entities in openLCA (Java) Source: https://context7.com/greendelta/olca-modules/llms.txt This Java code illustrates how to interact with the openLCA data model, including creating and managing units, unit groups, flow properties, product flows, processes, impact categories, and impact methods within a Derby database. ```java import org.openlca.core.database.Derby; import org.openlca.core.model.*; Derby db = new Derby(new java.io.File("database")); // Create a unit group and unit UnitGroup massUnits = new UnitGroup(); massUnits.name = "Mass units"; massUnits.refId = java.util.UUID.randomUUID().toString(); Unit kg = new Unit(); kg.name = "kg"; kg.conversionFactor = 1.0; massUnits.units.add(kg); massUnits.referenceUnit = kg; Unit g = new Unit(); g.name = "g"; g.conversionFactor = 0.001; massUnits.units.add(g); db.insert(massUnits); // Create a flow property FlowProperty mass = new FlowProperty(); mass.name = "Mass"; mass.refId = java.util.UUID.randomUUID().toString(); mass.unitGroup = massUnits; mass.flowPropertyType = FlowPropertyType.PHYSICAL; db.insert(mass); // Create a product flow Flow steel = new Flow(); steel.name = "Steel"; steel.refId = java.util.UUID.randomUUID().toString(); steel.flowType = FlowType.PRODUCT_FLOW; FlowPropertyFactor factor = new FlowPropertyFactor(); factor.flowProperty = mass; factor.conversionFactor = 1.0; steel.flowPropertyFactors.add(factor); steel.referenceFlowProperty = mass; db.insert(steel); // Create a process Process steelProduction = new Process(); steelProduction.name = "Steel production"; steelProduction.refId = java.util.UUID.randomUUID().toString(); steelProduction.processType = ProcessType.UNIT_PROCESS; // Add output exchange (product) Exchange output = new Exchange(); output.flow = steel; output.flowPropertyFactor = factor; output.unit = kg; output.amount = 1.0; output.isInput = false; steelProduction.exchanges.add(output); steelProduction.quantitativeReference = output; db.insert(steelProduction); // Create impact category ImpactCategory gwp = new ImpactCategory(); gwp.name = "Climate change"; gwp.refId = java.util.UUID.randomUUID().toString(); gwp.referenceUnit = "kg CO2-eq"; db.insert(gwp); // Create impact method ImpactMethod method = new ImpactMethod(); method.name = "My LCIA Method"; method.refId = java.util.UUID.randomUUID().toString(); method.impactCategories.add(gwp); db.insert(method); db.close(); ``` -------------------------------- ### Making IPC Calls with curl Source: https://github.com/greendelta/olca-modules/blob/master/olca-ipc/README.md Demonstrates how to send a POST request to the openLCA IPC server using curl. This method is useful for testing or simple interactions with the server. ```bash curl -X POST http://localhost:8080 -d @file.json -H "Content-Type: application/json" ``` -------------------------------- ### Derby Database Management in Java Source: https://context7.com/greendelta/olca-modules/llms.txt Manages persistent LCA data storage using embedded Derby databases. Supports file-based and in-memory databases, automatic schema creation, entity insertion, querying, backup, and export. Requires Java 21+ and the org.openlca.core.database.Derby class. ```java import org.openlca.core.database.Derby; import org.openlca.core.model.Flow; import org.openlca.core.model.FlowType; import java.io.File; // Create a new file-based Derby database File dbFolder = new File("path/to/my-database"); Derby db = new Derby(dbFolder); // Create an in-memory database for testing Derby memDb = Derby.createInMemory(); // Restore in-memory database from backup folder Derby restoredDb = Derby.restoreInMemory("/path/to/backup"); // Insert a new entity Flow steel = new Flow(); steel.name = "Steel"; steel.flowType = FlowType.PRODUCT_FLOW; steel.refId = java.util.UUID.randomUUID().toString(); db.insert(steel); // Query entities Flow found = db.get(Flow.class, steel.refId); System.out.println("Found flow: " + found.name); // Get all flows var allFlows = db.getAll(Flow.class); System.out.println("Total flows: " + allFlows.size()); // Backup and export database db.dump("/path/to/backup"); Derby.zip(dbFolder, new File("database-export.zolca")); // Always close when done db.close(); ``` -------------------------------- ### Calculate LCA Directly from a Process Source: https://context7.com/greendelta/olca-modules/llms.txt Computes LCA results directly from a single process without the need to construct a full product system. This method is useful for analyzing individual processes. It retrieves a process from the database, sets up calculation parameters, and then performs the calculation, providing access to scaling factors and total requirements. ```java import org.openlca.core.database.Derby; import org.openlca.core.model.*; import org.openlca.core.results.LcaResult; Derby db = new Derby(new java.io.File("my-database")); // Get a process directly Process process = db.get(Process.class, "process-ref-id"); // Create setup for process calculation CalculationSetup setup = CalculationSetup.of(process) .withAmount(100) .withAllocation(AllocationMethod.NONE); // Calculate using static factory method LcaResult result = LcaResult.of(db, setup); // Get scaling factors for each tech flow var scalingFactors = result.getScalingFactors(); for (var sf : scalingFactors) { System.out.printf("Process %s: scaling = %.6f%n", sf.techFlow().provider().name, sf.value()); } // Get total requirements var requirements = result.getTotalRequirements(); for (var req : requirements) { System.out.printf("Requirement for %s: %.4f%n", req.techFlow().flow().name, req.value()); } result.dispose(); db.close(); ```