Compare commits

..

No commits in common. "develop" and "v1-alpha1" have entirely different histories.

382 changed files with 10496 additions and 20872 deletions

View file

@ -1,117 +0,0 @@
name: "⚠️ Bug report"
about: "Report a bug in the engine."
title: "bug: "
labels:
- "Bug/New"
body:
- type: "markdown"
id: "text-introduction"
attributes:
value: |
Hey there! Thank you for taking the time to report a bug to us. \
This means a lot to us, as that's the only way to get better... and many people don't file bug reports. \
Anyway, please answer the following questions accurately, otherwise we may not be able to diagnose the issue. \
\
**Please check if the same bug report already exists. If so, participate in that one instead. If another issue is similar, make sure to mention the related issues.** \
**Please don't censor anything *except* sensitive information. You don't need to be embarrased about your username. You censor your bug report, we censor our answers.**
- type: "textarea"
id: "bug-description"
attributes:
label: "Bug description"
description: "Explain what the bug is about. Include as many details as possible."
placeholder: "My cat spontaneously explodes when I try to download from `https://yourdick.zip`."
validations:
required: true
- type: "textarea"
id: "bug-log"
attributes:
label: "Bug log"
description: |
Please insert the ENTIRE log output here, so we can understand the problem at hand. \
You must give us `DIAGNOSTIC` level logs (pass `-Dsosengine.base.loggerLevel=diagnostic` to the JVM) with the default log template.
**This field can be left empty if the bug does not involve/require log output.**
placeholder: "Your log file here..."
value: |
```plain
Your log file here...
```
validations:
required: false
- type: "textarea"
id: "bug-snippet"
attributes:
label: "Bug snippet"
description: |
Please insert a snippet of the (application and/or engine) code which you think is causing the issue.
**This field can be left empty if you intend on supplying a reproduction project.**
value: |
```java
Your code snippet here...
```
validations:
required: false
- type: "textarea"
id: "bug-reproduce"
attributes:
label: "Bug reproduction guide"
description: |
Explain how we can reproduce this bug as easy as possible, step by step.
**This field can be left empty if the bug does not involve/require a reproduction guide.**
placeholder: |
1. Pass "-Dsosengine.base.optimizeLogging=false" to the JVM
2. Override logging implementation
2. Initialize engine
4. The nearest cat should explode in the next few seconds
validations:
required: false
- type: "input"
id: "bug-reproduce-project"
attributes:
label: "Bug reproduction project"
description: |
Drop a link to some repository or zip file of an example project showcasing the bug.
**Only supply a repro project if the bug is a bit more advanced, needs specific timing, etc..** \
**Also please make sure that the bug actually occurs in the example project!**"
placeholder: "https://your.reproduction.project/download/url/here"
validations:
required: false
- type: "input"
id: "engine-version"
attributes:
label: "Full engine version"
description: |
Input the full engine version here.
Simply copy the `Initialized sos!engine v<version> (commit <commit>-<branch>, dirty <dirty>) in <inittime>ms` message here.
placeholder: "Example: sos!engine v1-alpha4 (commit 05b9644eba5263809b6655dabb92669523a95805-develop, dirty true)"
validations:
required: true
- type: "dropdown"
id: "jvm-java"
attributes:
label: "Java version"
description: "Which Java version is your application compiled against?"
options:
- "20 and lower"
- "21"
- "22"
- "23"
validations:
required: true
- type: "input"
id: "os"
attributes:
label: "Operating system"
description: "Name the operating system, version (if applicable) and CPU architecture the error occurs on. This may be some Linux distribution, Android or Windoze on `amd64`/`aarch64`/`ppc64`/etc.."
placeholder: "Example: Debian trixie (amd64)"
validations:
required: true
- type: "markdown"
id: "text-tysm"
attributes:
value: |
Thank you for filling out this bug report.
Please check your answers for *mistaeks* or sensitive information before sending this report.

View file

@ -1,5 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: "📚 Documentation"
about: "Visit the documentation. Maybe you just skipped something important or just haven't found the page you're looking for yet."
url: "https://engine.staropensource.de"

View file

@ -1,20 +0,0 @@
name: "👾 Empty"
about: "A clean slate. Only use this one for specific, special cases."
title: "empty: "
labels:
- "Empty"
body:
- type: "markdown"
id: "introduction"
attributes:
value: |
This issue template is meant for specific, special cases, where an empty issue template may be wanted.
You should *NOT* use this template to write bug reports, feature or help requests.
This issue template should ideally only be used by the repository maintainer.
- type: "textarea"
id: "content"
attributes:
label: "Issue content"
description: "Write your issue content here."
validations:
required: true

View file

@ -1,61 +0,0 @@
name: "✨ Feature Request"
about: "Request a feature to be implemented in the engine."
title: "feat: "
labels:
- "FeatureRequest/New"
body:
- type: "markdown"
id: "text-introduction"
attributes:
value: |
Hey there! Thank you for taking the time to request a feature to us. \
Before filling any of this out, please think for one minute if the feature is really important and necessary enough to implement in the engine. If you're unsure, continue. \
Please answer the following questions accurately, or we may not be able to implement the feature as you requested it. \
\
**Please check if the same feature request already exists. If so, participate in that one instead. If another issue is similar, make sure to mention the related issues.** \
**Please don't censor anything *except* sensitive information. You don't need to be embarrased about your username. You censor your bug report, we censor our answers.** \
**Submitting a feature request will *not* gurantee it's inclusion into the engine. By submitting a feature request, you are at the grace of the community to pick up your suggestion.**
- type: "textarea"
id: "feature-description"
attributes:
label: "Feature description"
description: "Explain *what* you want added. Include as many details as possible."
placeholder: |
Example:
I want to do X in my project, which would simplify doing Y.
validations:
required: true
- type: "textarea"
id: "feature-implementation"
attributes:
label: "Feature implementation"
description: |
Explain *how* you want it added. Include as many details as possible.
Also explore alternative ways of implementing the feature in the engine (if possible).
placeholder: |
Example:
I would propose to <some description on how to implement your feature>.
I've also thought on simply <some other description on how to implement your feature>.
validations:
required: true
- type: "textarea"
id: "feature-alternatives"
attributes:
label: "Feature alternatives"
description: |
Explain how to implement the feature without building it into the engine directly. Include as many details as possible.
**Leave empty if it can't simply be solved by creating a subsystem.**
placeholder: |
Example:
I've considered writing a subsystem for this feature.
Otherwise it would be possible to use <link to some project> with some configuration.
I've also considered using the normal way of doing it by <how to do it using the normal way>.
validations:
required: false
- type: "markdown"
id: "text-tysm"
attributes:
value: |
Thank you for filling out this feature request form.
Please check your answers for *mistaeks* before sending this report.

View file

@ -1,89 +0,0 @@
name: "💬 Help"
about: "Request help."
title: "help: "
labels:
- "Help/Wanted"
body:
- type: "markdown"
id: "text-introduction"
attributes:
value: |
Hey there! Seems like you have some kind of issue with the StarOpenSource Engine. \
Please answer the following questions accurately, otherwise we may not be able to help you. \
\
**Please check if the same help request already exists. If so, participate in that one instead. If another issue is similar, make sure to mention the related issues.** \
**Please don't censor anything *except* sensitive information. You don't need to be embarrased about your username. You censor your stuff, we censor our answers.**
- type: "textarea"
id: "help-description"
attributes:
label: "Problem description"
description: "Explain what your problem is as detailed as possible."
placeholder: "How can I create a custom LoggerImplementation implementation?"
validations:
required: true
- type: "textarea"
id: "help-log"
attributes:
label: "Log"
description: |
Please insert the ENTIRE log output here, so we can understand the problem at hand. \
You must give us `DIAGNOSTIC` level logs (pass `-Dsosengine.base.loggerLevel=diagnostic` to the JVM) with the default log template.
*This field can be left empty if the problem you are faciing does not involve/require log output.**
placeholder: "Your log file here..."
value: |
```plain
Your log file here...
```
validations:
required: false
- type: "textarea"
id: "help-snippet"
attributes:
label: "Code snippet"
description: |
Please insert a snippet of the application code which you think is causing the issue.
**This field can be left empty if the problem you are faciing does not involve/require code.**
value: |
```java
Your code snippet here...
```
validations:
required: false
- type: "input"
id: "engine-version"
attributes:
label: "Full engine version"
description: |
Input the full engine version here.
Simply copy the `Initialized sos!engine v<version> (commit <commit>-<branch>, dirty <dirty>) in <inittime>ms` message here.
placeholder: "Example: sos!engine v1-alpha4 (commit 05b9644eba5263809b6655dabb92669523a95805-develop, dirty true)"
validations:
required: true
- type: "dropdown"
id: "jvm-java"
attributes:
label: "Java version"
description: "Which Java version is your application compiled against?"
options:
- "20 and lower"
- "21"
- "22"
- "23"
validations:
required: true
- type: "input"
id: "os"
attributes:
label: "Operating system"
description: "Name the operating system, version (if applicable) and CPU architecture the error occurs on. This may be some Linux distribution, Android or Windoze on `amd64`/`aarch64`/`ppc64`/etc.."
placeholder: "Example: Debian trixie (amd64)"
validations:
required: true
- type: "markdown"
id: "text-tysm"
attributes:
value: |
Thank you for filling out this help form.
Please check your answers for *mistaeks* or sensitive information before sending this help request.

View file

@ -1,12 +0,0 @@
---
name: 'Pull Request'
about: 'Submit a pull request.'
title: 'new: '
ref: 'develop'
labels:
- 'PRStatus/Open'
- 'PR/New'
---
<!--
Please list your changes here.
-->

View file

@ -1,125 +0,0 @@
name: build-and-test
on:
- pull_request
- push
jobs:
build:
runs-on: docker
container:
image: git.staropensource.de/staropensource/actions-docker:java
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Restore Gradle cache
uses: actions/cache/restore@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Compile
run: ./gradlew --no-daemon jar javadocJar sourceJar
- name: Save Gradle cache
uses: actions/cache/save@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Upload library JARs
uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with:
name: jars-libraries
path: |
**/build/libs/*.jar
!**/build/libs/*-javadoc.jar
!**/build/libs/*-sources.jar
if-no-files-found: error
- name: Upload API documentation JARs
uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with:
name: jars-apidocs
path: |
**/build/libs/*-javadoc.jar
if-no-files-found: error
- name: Upload source JARs
uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with:
name: jars-sources
path: |
**/build/libs/*-sources.jar
if-no-files-found: error
generate-javadoc:
runs-on: docker
container:
image: git.staropensource.de/staropensource/actions-docker:java
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Restore Gradle cache
uses: actions/cache/restore@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Generate javadoc
run: ./gradlew --no-daemon javadoc javadocAll
- name: Save Gradle cache
uses: actions/cache/save@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Upload separate javadoc
uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with:
name: javadoc-separate
path: |
**/build/docs/javadoc/*
if-no-files-found: error
- name: Upload combined javadoc
uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with:
name: javadoc-combined
path: |
build/docs/javadoc/*
if-no-files-found: error
test:
runs-on: docker
container:
image: git.staropensource.de/staropensource/actions-docker:java
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Restore Gradle cache
uses: actions/cache/restore@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Run tests
run: ./gradlew --no-daemon test
- name: Save Gradle cache
uses: actions/cache/save@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-

View file

@ -1,60 +0,0 @@
name: build-and-test
on:
- pull_request
jobs:
generate-javadoc:
runs-on: docker
container:
image: git.staropensource.de/staropensource/actions-docker:java
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Restore Gradle cache
uses: actions/cache/restore@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Generate javadoc
run: ./gradlew --no-daemon javadoc
- name: Save Gradle cache
uses: actions/cache/save@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
test:
runs-on: docker
container:
image: git.staropensource.de/staropensource/actions-docker:java
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Restore Gradle cache
uses: actions/cache/restore@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-
- name: Run tests
run: ./gradlew --no-daemon test
- name: Save Gradle cache
uses: actions/cache/save@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
gradle-${{ runner.os }}-

15
.gitattributes vendored
View file

@ -1,15 +0,0 @@
# Documentation
*.md linguist-documentation
docs/* linguist-documentation
# Licensing information
COPYING linguist-documentation
LICENSE linguist-documentation
# Javadoc
*.html linguist-documentation
*.css linguist-documentation
# Gradle configuration
*.properties linguist-configuration
*.gradle linguist-configuration

4
.gitignore vendored
View file

@ -1,7 +1,6 @@
### Gradle ### ### Gradle ###
.gradle .gradle
build/ build/
run/
!gradle/wrapper/gradle-wrapper.jar !gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/ !**/src/main/**/build/
!**/src/test/**/build/ !**/src/test/**/build/
@ -42,6 +41,3 @@ bin/
### Mac OS ### ### Mac OS ###
.DS_Store .DS_Store
### Java ###
hs_err_pid*.log

View file

@ -1,7 +1,7 @@
<component name="CopyrightManager"> <component name="CopyrightManager">
<copyright> <copyright>
<option name="allowReplaceRegexp" value="Copyright .* The StarOpenSource Engine Authors" /> <option name="allowReplaceRegexp" value="Copyright .* The StarOpenSource Engine Contributors" />
<option name="notice" value="STAROPENSOURCE ENGINE SOURCE FILE&#10;Copyright (c) &amp;#36;today.year The StarOpenSource Engine Authors&#10;Licensed under the GNU Affero General Public License v3&#10;&#10;This program is free software: you can redistribute it and/or modify&#10;it under the terms of the GNU Affero General Public License as&#10;published by the Free Software Foundation, either version 3 of the&#10;License, or (at your option) any later version.&#10;&#10;This program is distributed in the hope that it will be useful,&#10;but WITHOUT ANY WARRANTY; without even the implied warranty of&#10;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the&#10;GNU Affero General Public License for more details.&#10;&#10;You should have received a copy of the GNU Affero General Public License&#10;along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;." /> <option name="notice" value="STAROPENSOURCE ENGINE SOURCE FILE&#10;Copyright (c) &amp;#36;today.year The StarOpenSource Engine Contributors&#10;Licensed under the GNU Affero General Public License v3&#10;&#10;This program is free software: you can redistribute it and/or modify&#10;it under the terms of the GNU Affero General Public License as&#10;published by the Free Software Foundation, either version 3 of the&#10;License, or (at your option) any later version.&#10;&#10;This program is distributed in the hope that it will be useful,&#10;but WITHOUT ANY WARRANTY; without even the implied warranty of&#10;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the&#10;GNU Affero General Public License for more details.&#10;&#10;You should have received a copy of the GNU Affero General Public License&#10;along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;." />
<option name="myName" value="sos!engine" /> <option name="myName" value="sos!engine" />
</copyright> </copyright>
</component> </component>

661
COPYING Normal file
View file

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

685
LICENSE
View file

@ -1,661 +1,24 @@
GNU AFFERO GENERAL PUBLIC LICENSE The software in this package is distributed under the GNU Affero
Version 3, 19 November 2007 General Public License (with a special exception described below).
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> A copy of the GNU Affero General Public License (AGPL) is included in this distribution,
Everyone is permitted to copy and distribute verbatim copies in the file COPYING. If you do not have the source code, it is available at:
of this license document, but changing it is not allowed.
https://git.staropensource.de/StarOpenSource/Engine
Preamble
Linking this library statically or dynamically with other modules is
The GNU Affero General Public License is a free, copyleft license for making a combined work based on this library. Thus, the terms and
software and other kinds of works, specifically designed to ensure conditions of the GNU Affero General Public License cover the whole
cooperation with the community in the case of network server software. combination.
The licenses for most software and other practical works are designed As a special exception, the copyright holders of this library give you
to take away your freedom to share and change the works. By contrast, permission to link this library with independent modules to produce an
our General Public Licenses are intended to guarantee your freedom to executable, regardless of the license terms of these independent
share and change all versions of a program--to make sure it remains free modules, and to copy and distribute the resulting executable under
software for all its users. terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
When we speak of free software, we are referring to freedom, not module. An independent module is a module which is not derived from
price. Our General Public Licenses are designed to make sure that you or based on this library. If you modify this library, you may extend
have the freedom to distribute copies of free software (and charge for this exception to your version of the library, but you are not
them if you wish), that you receive source code or can get it if you obligated to do so. If you do not wish to do so, delete this
want it, that you can change the software or use pieces of it in new exception statement from your version.
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View file

@ -1,44 +1,35 @@
# StarOpenSource Engine # StarOpenSource Engine
The StarOpenSource Engine (or sos!engine for short) is a modular, extensible and easy to use Java game and application engine. The StarOpenSource Engine (or sos!engine for short) is a modular, extensible and easy to use Java game and application engine.
## WARNING
The StarOpenSource Engine is under heavy development and is extremely unstable. Code will break often, prepare for potential major refactors when trying the engine out.
## Index ## Index
- [About](#about) - [About](#about)
- [... the engine](#-the-engine) - [About the engine](#about-the-engine)
- [... the repository](#-the-repository) - [About the repository](#about-the-repository)
- [Priorities](#priorities) - [Priorities](#priorities)
- [Documentation](#documentation) - [Documentation](#documentation)
- [Contributing](#contributing) - [Contributing](#contributing)
- [Requirements](#requirements) - [Requirements](#requirements)
- [What IDE to use?](#what-ide-to-use) - [What IDE to use?](#what-ide-to-use)
- [Code style](#code-style) - [Code style](#code-style)
- [Pull request guidelines](#pull-request-guidelines) - [Read this before creating a pull request](#read-this-before-creating-a-pull-request)
- [Making your first contribution](#making-your-first-contribution) - [Making your first contribution](#making-your-first-contribution)
- [Gradle properties](#gradle-properties)
## About ## About
### ... the engine ### About the engine
The StarOpenSource Engine is a modular and extensible framework for building applications and games written in [one of the multiple JVM programming languages](https://en.wikipedia.org/wiki/List_of_JVM_languages). The sos!engine is a modular and extensible framework for building applications and games, written in the Java programming language.
The engine consists of various subsystems, each separate and responsible for only a few closely-related tasks. The engine consists of various subsystems, each separate and responsible for only one thing. The engine also houses various useful utilities and classes making development fun, and all that while being lightweight.
\ ### About the repository
Not only that. The engine also features various useful classes, interfaces and methods making development fun and simpler, while being lightweight. The sos!engine repository is a monorepo, consisting of [the core engine](https://git.staropensource.de/StarOpenSource/Engine/src/branch/develop/base), official subsystems and [their documentation](https://git.staropensource.de/StarOpenSource/Engine/src/branch/develop/docs).
### ... the repository
The sos!engine repository is a monorepo, consisting of [the core engine](https://git.staropensource.de/StarOpenSource/Engine/src/branch/develop/base), multiple official subsystems and [their documentation](https://git.staropensource.de/StarOpenSource/Engine/src/branch/develop/docs).
### Priorities ### Priorities
These are in no particular order. - modular
- configurable
- [do one thing and do it well](https://en.wikipedia.org/wiki/Unix_philosophy) (subsystems concept)
- fast
- few runtime dependencies (note: we will cut down on some of them during development)
- modular & extensible
- small & lightweight - small & lightweight
- fast
- [do one thing and do it well](https://en.wikipedia.org/wiki/Unix_philosophy) (subsystems concept)
- have as few runtime dependencies as possible (note: we will cut down on some of them during development)
## Documentation ## Documentation
You can view the engine documentation at [engine.staropensource.de](https://engine.staropensource.de). It provides information, guides and tutorials about the core engine and subsystems. The official documentation for the StarOpenSource Engine is not yet available, but is planned.
If you want the API reference, you can [visit the Javadoc](https://jd.engine.staropensource.de) for the engine and it's subsystems. You can however [visit the Javadocs](https://jd.engine.staropensource.de).
## Contributing ## Contributing
### Requirements ### Requirements
@ -46,44 +37,15 @@ You need the following things to be able to contribute code to the StarOpenSourc
- knowledge of Java - knowledge of Java
- knowledge about the internals of engine - knowledge about the internals of engine
### What IDE to use? ### What IDE to use?
We recommend and are using [IntelliJ IDEA Community Edition](https://github.com/JetBrains/intellij-community) for development because it is flexible, extendable, customizable, provides good completions and error detection. It's also open source. We use and recommend using [IntelliJ IDEA Community Edition](https://github.com/JetBrains/intellij-community) for development because it is flexible, extendable, customizable, provides good completions and error detection. It's also open source.
### Code style ### Code style
We recommend looking at existing classes and code for a good understanding on how we'd like code to be written. We recommend looking at existing classes.
Here's a quick rundown on the most important things: ### Read this before creating a pull request
- Document EVERYTHING. Every single class, field and method, even if private. Before creating a pull request, make sure you've
- Make comments about your code, unless it's extremely simple and easy to understand. - created tests for the functionality you added, changed or removed (if applicable),
- Make sure to add and update `@since` in javadoc comments (update if the javadoc changes a good amount).
- Keep stuff simple, no need to elaborate what a logger is. Though remember to not make it *too* simple.
- Make sure every field and method has a newline to separate it.
- Files must end with a newline or cats might get angry.
- Use your brain.
### Pull request guidelines
Before creating a pull request, make sure you've:
- created tests for the functionality you've added, changed or removed (if applicable),
- tested your changes, - tested your changes,
- made sure that everything works, - made sure that everything works,
- is compatible with other code in the monorepo, and - is compatible with other code in the monorepo, and
- is compatible with other applications. If not, tell us in your pull request description. - is compatible with other applications. If not, tell us in your pull request description.
### Making your first contribution ### Making your first contribution
TODO TODO
### Gradle properties
Gradle's behaviour can be changed by changing gradle project properties.
To change them, simply append `-P<property>` or `-P<property>=<value>`, like this: `./gradlew -Pjobs=4 test`.
#### Parallelism
Use the `jobs` property to control how many jobs will get executed simultaneously.
On Linux, specify `-Pjobs=$(nproc)`. Defaults to `8`.
#### JVM Home
You can use the `graalHome` property to specify the `$JAVA_HOME` of your local GraalVM installation.
Only used in the `nativeImage` task. Useful if you aren't using GraalVM as your primary JDK.
#### Testing
You can use the following properties to modify the behaviour of the `test`-task:
- `test.control.mode` (default *empty*)
- `force-enable`: Disables all test classes except the ones specified
- `force-disable`: Enables all test classes except the ones specified
- *everything else*: Enables all test classes
- `test.control.classes` (default *empty*): A comma-separated, case-sensitive list of test classes
which (depending on `test.control.mode`'s value) enable or disable the specified classes.
Example: `-Ptest.control.mode=MiscellaneousTest,DependencyResolverTest,EngineConfigurationTest`
- `test.control.warning` (default `false`): If `true`, will emit a warning before a restricted test method exits
- `test.loggerLevel` (default `silent_warning`): Will set `UnitLogger`'s logger level.
Works like `-Dsosengine.base.loggerLevel`. See `UnitLogger#loggerLevel` for more information

View file

@ -1,61 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.ansi;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.implementable.LoggingAdapter;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import org.jetbrains.annotations.NotNull;
/**
* Prints colored log output using the Jansi library.
*
* @see Logger
* @see LoggingAdapter
* @since v1-alpha2
*/
public class AnsiLoggingAdapter implements LoggingAdapter {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha2
*/
public AnsiLoggingAdapter() {}
/** {@inheritDoc} */
@Override
@SuppressWarnings({ "resource" }) // Using try-with-resources will cause issues here
public void print(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message, @NotNull String format) {
// Convert to Ansi
Ansi output = new AnsiShortcodeParser(format, true).getAnsi();
// Print message
if (level == LogLevel.ERROR || level == LogLevel.CRASH)
if (EngineConfiguration.getInstance().isLogForceStandardOutput())
AnsiConsole.out().println(output);
else
AnsiConsole.err().println(output);
else
AnsiConsole.out().println(output);
}
}

View file

@ -1,107 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.ansi;
import de.staropensource.engine.base.implementable.ShortcodeParser;
import de.staropensource.engine.base.exception.ParserException;
import org.fusesource.jansi.Ansi;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
/**
* Implementation of the {@link ShortcodeParser} class
* with ANSI support using the Jansi library.
*
* @see ShortcodeParser
* @since v1-alpha8
*/
public final class AnsiShortcodeParser extends ShortcodeParser {
/**
* Creates and initializes an instance of this class.
*
* @param string string to convert
* @param ignoreInvalidEscapes will ignore invalid escapes and print treat them like regular text
* @throws ParserException when parsing failed
* @since v1-alpha2
*/
public AnsiShortcodeParser(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
super(string, ignoreInvalidEscapes);
}
/**
* Returns the parsed string as an {@link Ansi} sequence.
*
* @return {@link Ansi} sequence
* @since v1-alpha2
*/
public @NotNull Ansi getAnsi() {
Ansi ansi = Ansi.ansi();
Set<@NotNull String> status = new HashSet<>();
for (String component : components)
if (component.equals("RESET")) {
ansi.a(Ansi.Attribute.RESET);
status.clear();
} else if (component.startsWith("TEXT:"))
ansi.a(component.substring(5));
else if (component.startsWith("COLOR:"))
if (component.startsWith("COLOR:FOREGROUND:"))
ansi.fg(Ansi.Color.valueOf(component.substring(17)));
else if (component.startsWith("COLOR:BACKGROUND:"))
ansi.bg(Ansi.Color.valueOf(component.substring(17)));
else if (component.startsWith("ATTRIBUTE:"))
if (component.startsWith("ATTRIBUTE:BLINK")) {
if (status.contains("ATTRIBUTE:BLINK"))
continue;
ansi.a(Ansi.Attribute.BLINK_SLOW);
status.add("ATTRIBUTE:BLINK");
} else if (component.startsWith("ATTRIBUTE:BOLD")) {
if (status.contains("ATTRIBUTE:BOLD"))
continue;
ansi.a(Ansi.Attribute.INTENSITY_BOLD);
status.add("ATTRIBUTE:BOLD");
} else if (component.startsWith("ATTRIBUTE:ITALIC")) {
if (status.contains("ATTRIBUTE:ITALIC"))
continue;
ansi.a(Ansi.Attribute.ITALIC);
status.add("ATTRIBUTE:ITALIC");
} else if (component.startsWith("ATTRIBUTE:STRIKETHROUGH")) {
if (status.contains("ATTRIBUTE:STRIKETHROUGH"))
continue;
ansi.a(Ansi.Attribute.STRIKETHROUGH_ON);
status.add("ATTRIBUTE:STRIKETHROUGH");
} else if (component.startsWith("ATTRIBUTE:UNDERLINE")) {
if (status.contains("ATTRIBUTE:UNDERLINE"))
continue;
ansi.a(Ansi.Attribute.UNDERLINE);
status.add("ATTRIBUTE:UNDERLINE");
}
return ansi;
}
}

View file

@ -1,86 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.ansi;
import de.staropensource.engine.base.annotation.EngineSubsystem;
import de.staropensource.engine.base.implementable.SubsystemClass;
import de.staropensource.engine.base.utility.information.EngineInformation;
import de.staropensource.engine.base.implementation.versioning.StarOpenSourceVersioningSystem;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.DependencyVector;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
/**
* Main class of the ANSI Compatibility subsystem.
*
* @since v1-alpha2
*/
@EngineSubsystem
@SuppressWarnings({ "JavadocDeclaration" })
public final class AnsiSubsystem extends SubsystemClass {
/**
* Contains the class instance.
*
* @since v1-alpha2
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless the subsystem is uninitialized
* @since v1-alpha2
*/
@Getter
private static AnsiSubsystem instance = null;
/**
* Initializes this subsystem.
*
* @since v1-alpha2
*/
public AnsiSubsystem() {
// Check if subsystem has already initialized
if (instance == null)
instance = this;
else
Logger.crash("Only one instance of this class is allowed, use getInstance() instead of creating a new instance");
}
/** {@inheritDoc} */
@Override
public @NotNull String getName() {
return "ansi";
}
/** {@inheritDoc} */
@Override
public void initializeSubsystem() {
Logger.setLoggingAdapter(new AnsiLoggingAdapter());
}
/** {@inheritDoc} */
@Override
public @NotNull DependencyVector getDependencyVector() {
return new DependencyVector.Builder()
.setIdentifier("ansi")
.setVersioningSystem(StarOpenSourceVersioningSystem.class)
.setVersion(EngineInformation.getVersioningString())
.build();
}
}

View file

@ -1,23 +0,0 @@
/**
* The ANSI subsystem, allowing the engine to
* use ANSI escape codes using the Jansi library.
*
* @since v1-alpha2
*/
module sosengine.ansi {
// Dependencies
// -> Java
requires transitive java.management;
// -> Engine
requires transitive sosengine.base;
// -> Libraries
requires transitive static lombok;
requires transitive org.jetbrains.annotations;
requires org.fusesource.jansi;
// API access
exports de.staropensource.engine.ansi;
// Reflection access
opens de.staropensource.engine.ansi;
}

View file

@ -1,23 +0,0 @@
<!--
~ STAROPENSOURCE ENGINE SOURCE FILE
~ Copyright (c) 2024 The StarOpenSource Engine Authors
~ Licensed under the GNU Affero General Public License v3
~
~ This program is free software: you can redistribute it and/or modify
~ it under the terms of the GNU Affero 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 Affero General Public License for more details.
~
~ You should have received a copy of the GNU Affero General Public License
~ along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
<body>
<p>Welcome to the sos!engine API documentation!<br/>
You are currently in the documentation for the <b>ansi</b> subsystem, allowing ANSI escape sequences to be used using Jansi.</p>
</body>

View file

@ -1,6 +1,6 @@
/* /*
* STAROPENSOURCE ENGINE SOURCE FILE * STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors * Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3 * Licensed under the GNU Affero General Public License v3
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -18,6 +18,9 @@
*/ */
import java.nio.file.Files import java.nio.file.Files
// Plugins // Plugins
plugins { plugins {
id("java") id("java")
@ -26,9 +29,9 @@ plugins {
id("maven-publish") id("maven-publish")
} }
// Dependencies // Project dependencies
dependencies { dependencies {
// -> Runtime // -> Runtime <-
// Lombok // Lombok
compileOnly("org.projectlombok:lombok:${dependencyLombok}") compileOnly("org.projectlombok:lombok:${dependencyLombok}")
annotationProcessor("org.projectlombok:lombok:${dependencyLombok}") annotationProcessor("org.projectlombok:lombok:${dependencyLombok}")
@ -36,10 +39,13 @@ dependencies {
// JetBrains Annotations // JetBrains Annotations
compileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}") compileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}")
// ANSI support
implementation("org.fusesource.jansi:jansi:${dependencyJansi}")
// Reflections // Reflections
implementation("org.reflections:reflections:${dependencyReflections}") implementation("org.reflections:reflections:${dependencyReflections}")
// -> Testing // -> Testing <-
// Jetbrains Annotations // Jetbrains Annotations
testCompileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}") testCompileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}")
@ -48,90 +54,31 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter") testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
// Project // jOOR
testImplementation(project(":testing")) testImplementation("org.jooq:joor:${dependencyJoor}")
} }
// Javadoc configuration // Fix delombok task
javadoc { delombok.doFirst {
outputs.upToDateWhen { false } // Force task execution File target = file("${project.projectDir}/src/main/module-info.java")
dependsOn(delombok) // Make sure the source is delomboked first File source = file("${project.projectDir}/src/main/java/module-info.java")
javadoc { target.delete()
setClasspath(files(project.sourceSets.main.compileClasspath)) // Include dependencies source.renameTo(target)
}
delombok.doLast {
File target = file("${project.projectDir}/src/main/java/module-info.java")
File source = file("${project.projectDir}/src/main/module-info.java")
options { target.delete()
if (new File(projectDir, "src/main/javadoc/theme.css").exists()) source.renameTo(target)
stylesheetFile = new File(projectDir, "src/main/javadoc/theme.css") // Theming is cool :3
setMemberLevel(JavadocMemberLevel.PUBLIC) // Only display public stuff
setOverview("src/main/javadoc/overview.html") // We want a custom overview page to greet the visitor
setLocale("en_US") //
addStringOption("Xwerror", "-quiet") // Fail build on warning
setJFlags([
"-Duser.language=en_US" // See above
])
}
}
}
// Unit testing configuration
test {
useJUnitPlatform()
// Pass test configuration to test VMs
Map<String, String> testConfiguration = new HashMap<>();
for (String property : project.properties.keySet())
if (property.startsWith("test."))
testConfiguration.put(property, project.properties.get(property).toString())
systemProperties(testConfiguration)
setMaxParallelForks(project.hasProperty("jobs") ? Integer.parseInt((String) project.property("jobs")) : 8)
setForkEvery(1)
setFailFast(true)
testLogging {
events("passed", "skipped", "failed")
}
}
// Include javadoc and source jar during publishing
java {
withJavadocJar()
withSourcesJar()
}
// Build publishing configuration
// Note: You can safely ignore any errors or warnings thrown by your IDE here
publishing {
repositories {
maven {
name = "staropensource"
url = uri("https://mvn.staropensource.de/engine")
credentials(org.gradle.api.credentials.PasswordCredentials)
authentication {
//noinspection GroovyAssignabilityCheck
basic (BasicAuthentication)
}
}
}
publications {
//noinspection GroovyAssignabilityCheck
maven (MavenPublication) {
groupId = group
artifactId = project.getName()
version = version
//noinspection GroovyAssignabilityCheck
from components.java
}
}
} }
// Copy gradle.properties file // Copy gradle.properties file
// for inclusion in final build // for inclusion in final build
tasks.register("copyGradleProperties") { tasks.register("copyGradleProperties") {
doFirst { doFirst {
File target = file("${project.projectDir}/src/main/resources/sosengine-gradle.properties") File target = file("${project.projectDir}/src/main/resources/gradle.properties")
File source = file(project(":").projectDir.getPath() + "/gradle.properties") File source = file(project(":").projectDir.getPath() + "/gradle.properties")
target.delete() target.delete()
Files.copy(source.toPath(), target.toPath()) Files.copy(source.toPath(), target.toPath())
@ -154,7 +101,7 @@ gitProperties {
tasks.register("writeGitProperties") { // This task's only purpose is to copy the git.properties from our git properties plugin to the resources directory so it's included in the final build tasks.register("writeGitProperties") { // This task's only purpose is to copy the git.properties from our git properties plugin to the resources directory so it's included in the final build
doLast { doLast {
File target = file("${project.projectDir}/src/main/resources/sosengine-git.properties") File target = file("${project.projectDir}/src/main/resources/git.properties")
File source = file("${project.projectDir}/build/resources/main/git.properties") File source = file("${project.projectDir}/build/resources/main/git.properties")
target.delete() target.delete()
@ -166,18 +113,58 @@ tasks.register("writeGitProperties") { // This task's only purpose is to copy t
generateGitProperties.outputs.upToDateWhen({ false }) // Force task execution generateGitProperties.outputs.upToDateWhen({ false }) // Force task execution
processResources.dependsOn(writeGitProperties) // Ensure git.properties file is present processResources.dependsOn(writeGitProperties) // Ensure git.properties file is present
// Fix delombok task // Javadoc configuration
delombok.doFirst { javadoc {
File target = file("${project.projectDir}/src/main/module-info.java") outputs.upToDateWhen { false } // Force task execution
File source = file("${project.projectDir}/src/main/java/module-info.java") dependsOn(delombok) // Make sure the source is delomboked first
target.delete() javadoc {
source.renameTo(target) setClasspath(files(project.sourceSets.main.compileClasspath)) // Include dependencies
}
delombok.doLast {
File target = file("${project.projectDir}/src/main/java/module-info.java")
File source = file("${project.projectDir}/src/main/module-info.java")
target.delete() options {
source.renameTo(target) if (new File(projectDir, "src/main/javadoc/theme.css").exists())
stylesheetFile = new File(projectDir, "src/main/javadoc/theme.css") // Theming is cool :3
setMemberLevel(JavadocMemberLevel.PUBLIC) // Only display public stuff
setOverview("src/main/javadoc/overview.html") // We want a custom overview page to greet the visitor
setLocale("en_US") //
setJFlags([
"-Duser.language=en_US" // See above
])
}
}
}
// Unit testing configuration
test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
// Build publishing configuration
// Note: You can safely ignore any errors or warnings thrown by your IDE here
publishing {
repositories {
maven {
name = "staropensource"
url = uri("https://mvn.staropensource.de/sosengine")
credentials(org.gradle.api.credentials.PasswordCredentials)
authentication {
//noinspection GroovyAssignabilityCheck
basic (BasicAuthentication)
}
}
}
publications {
//noinspection GroovyAssignabilityCheck
maven (MavenPublication) {
groupId = group
artifactId = "base"
version = version
//noinspection GroovyAssignabilityCheck
from components.java
}
}
} }

View file

@ -1,618 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base;
import de.staropensource.engine.base.annotation.EngineSubsystem;
import de.staropensource.engine.base.event.*;
import de.staropensource.engine.base.exception.IllegalAccessException;
import de.staropensource.engine.base.exception.dependency.UnmetDependenciesException;
import de.staropensource.engine.base.implementable.ShutdownHandler;
import de.staropensource.engine.base.implementable.SubsystemClass;
import de.staropensource.engine.base.implementable.helper.EventHelper;
import de.staropensource.engine.base.implementation.versioning.StarOpenSourceVersioningSystem;
import de.staropensource.engine.base.event.InternalEngineShutdownEvent;
import de.staropensource.engine.base.internal.type.DependencySubsystemVector;
import de.staropensource.engine.base.logging.PrintStreamService;
import de.staropensource.engine.base.logging.*;
import de.staropensource.engine.base.logging.backend.async.LoggingQueue;
import de.staropensource.engine.base.logging.backend.async.LoggingThread;
import de.staropensource.engine.base.type.DependencyVector;
import de.staropensource.engine.base.type.EngineState;
import de.staropensource.engine.base.type.immutable.ImmutableLinkedList;
import de.staropensource.engine.base.utility.DependencyResolver;
import de.staropensource.engine.base.utility.FileAccess;
import de.staropensource.engine.base.utility.Miscellaneous;
import de.staropensource.engine.base.utility.PlaceholderEngine;
import de.staropensource.engine.base.utility.information.EngineInformation;
import de.staropensource.engine.base.utility.information.JvmInformation;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import java.util.*;
/**
* Main class of the sos!engine.
*
* @see EngineConfiguration
* @since v1-alpha0
*/
@SuppressWarnings({ "JavadocDeclaration" })
public final class Engine extends SubsystemClass {
/**
* Contains the class instance.
*
* @since v1-alpha0
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless {@link Engine} is uninitialized
* @since v1-alpha0
*/
@Getter
private static Engine instance = null;
/**
* Contains the thread group of the engine.
*
* @since v1-alpha2
* -- GETTER --
* Returns the thread group of the engine.
*
* @return engine thread group
* @since v1-alpha2
*/
@Getter
private static final ThreadGroup threadGroup = new ThreadGroup("sos!engine");
/**
* Contains the engine state.
*
* @since v1-alpha2
* -- GETTER --
* Returns the engine state.
*
* @return shutdown state
* @since v1-alpha2
*/
@Getter
private @NotNull EngineState state;
/**
* Contains a list of all registered subsystems.
* The list is sorted after initialization order.
*
* @since v1-alpha1
* -- GETTER --
* Returns a list of all registered subsystems.
* The list is sorted after initialization order.
*
* @return subsystem list
* @since v1-alpha1
*/
@Getter
private @NotNull ImmutableLinkedList<@NotNull DependencySubsystemVector> subsystems = new ImmutableLinkedList<>();
/**
* Contains the engine's shutdown handler.
* The shutdown handler is responsible for
* shutting down the JVM safely.
*
* @see ShutdownHandler
* @since v1-alpha2
* -- GETTER --
* Returns the engine's shutdown handler.
* The shutdown handler is responsible for
* shutting down the JVM safely.
*
* @return shutdown handler
* @see ShutdownHandler
* @since v1-alpha2
* -- SETTER --
* Sets the engine's shutdown handler.
* The shutdown handler is responsible for
* shutting down the JVM safely.
*
* @param shutdownHandler new shutdown handler
* @see ShutdownHandler
* @since v1-alpha2
*/
@Getter(value = AccessLevel.MODULE)
@Setter(value = AccessLevel.MODULE)
private @NotNull ShutdownHandler shutdownHandler = new Engine.JvmShutdownHandler();
/**
* Contains the JVM shutdown hook thread,
* which ensures that the engine is fully shut
* down before the JVM exits.
*
* @see EngineInternals#installSafetyShutdownHook(boolean)
* @since v1-alpha4
*/
@Getter(AccessLevel.MODULE)
private final @NotNull Thread safetyShutdownHook = Thread.ofPlatform()
.name("Engine shutdown thread")
.group(getThreadGroup())
.unstarted(() -> {
// Check if already shutting down
switch (state) {
case UNKNOWN, SHUTDOWN, CRASHED -> {
return;
}
}
// Print warning about shutdown
Logger.warn("Trying to shut down engine using shutdown hook.\nThis approach to shutting down the engine and JVM is NOT RECOMMENDED, please use Engine#shutdown() instead.");
// Shutdown
Engine.getInstance().shutdown();
// Print last message
Logger.warn("Engine successfully shut down using shutdown hook. PLEASE USE Engine#shutdown() INSTEAD OF System#exit() or Runtime#exit()!");
});
/**
* Initializes the StarOpenSource Engine.
*
* @throws RuntimeException for all exceptions thrown by this constructor
* @since v1-alpha8
*/
private Engine() throws RuntimeException {
try {
instance = this;
state = EngineState.EARLY_STARTUP;
// For measuring the initialization time
long initTimeEarly = System.currentTimeMillis();
long initTimeLate = initTimeEarly;
// Check for incompatible JVM implementations
checkJvmIncompatibilities();
// Display that the engine is initializing
Logger.verb("Initializing engine");
// Start the logging thread
Logger.diag("Starting logging infrastructure");
LoggingThread.startThread(false);
PrintStreamService.initializeStreams();
// Initialize EngineInternals
Logger.diag("Initializing EngineInternals class");
new EngineInternals();
// Load engine configuration
Logger.diag("Loading engine configuration");
new EngineConfiguration();
EngineConfiguration.getInstance().loadConfiguration();
// Load engine build information
Logger.diag("Loading engine build information");
EngineInformation.update();
// Check for reflective classpath scanning compatibility
checkReflectiveClasspathScanningCompatibility();
// Check for Java version incompatibilities
checkJavaVersion();
// Initialize PlaceholderEngine
Logger.diag("Initializing PlaceholderEngine");
PlaceholderEngine.initialize();
// Initialize static FileAccess instances
Logger.diag("Initializing static FileAccess instances");
FileAccess.initializeInstances();
// Install the safety shutdown hook
Logger.diag("Installing safety shutdown hook");
EngineInternals.getInstance().installSafetyShutdownHook(true);
// Cache events
Logger.diag("Caching event listeners");
cacheEvents();
// Complete early initialization stage
Logger.verb("Completing early initialization stage");
state = EngineState.STARTUP;
initTimeEarly = System.currentTimeMillis() - initTimeEarly;
// Perform automatic subsystem initialization
if (EngineConfiguration.getInstance().isInitialPerformSubsystemInitialization()) {
// Collect all subsystems
Logger.diag("Collecting subsystems");
collectSubsystems();
// Initialize subsystems
try {
initializeSubsystems();
} catch (Exception exception) {
Logger.error("Subsystem dependency resolution failed");
}
}
// Complete late initialization stage
Logger.verb("Completing late initialization stage");
state = EngineState.RUNNING;
initTimeLate = System.currentTimeMillis() - initTimeLate;
// Print welcome message
Logger.info(
"""
Welcome to the StarOpenSource Engine "%engine_version_codename%" %engine_version%!
Running commit %engine_git_commit_id_long% (dirty %engine_git_dirty%).
Initialization took %init_time_total%ms (early %init_time_early%ms, late %init_time_late%ms).
Copyright (c) 2024 The StarOpenSource Engine Authors
Licensed under the GNU Affero General Public License v3"""
.replace("%init_time_total%", String.valueOf(initTimeEarly + initTimeLate))
.replace("%init_time_early%", String.valueOf(initTimeEarly))
.replace("%init_time_late%", String.valueOf(initTimeLate))
);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
/**
* Initializes the StarOpenSource
* Engine, if it isn't already.
*
* @throws IllegalStateException when running in an incompatible environment
* @throws RuntimeException on engine initialization failure
* @since v1-alpha6
*/
public static void initialize() throws RuntimeException {
try {
if (instance == null)
new Engine();
} catch (RuntimeException exception) {
Logger.error("Engine initialization failed");
Logger.error(Miscellaneous.getStackTraceHeader(exception.getCause()));
for (String line : Miscellaneous.getStackTraceAsString(exception.getCause(), true).split("\n"))
Logger.error(line);
throw new RuntimeException("Engine initialization failed", exception.getCause());
}
}
/**
* Checks if the running JVM implementation is not supported by the engine.
*
* @since v1-alpha8
*/
private void checkJvmIncompatibilities() {
if (System.getProperties().getProperty("sosengine.base.allowUnsupportedJVMInitialization", "false").equals("true")) {
Logger.warn("Skipping JVM implementation incompatibilities check");
return;
}
// Substrate VM (GraalVM Community)
if (JvmInformation.getImplementationName().equals("Substrate VM") && JvmInformation.getImplementationVendor().equals("GraalVM Community")) {
Logger.error("##############################################################################################");
Logger.error("## Running in Substrate VM, which is the name of the JVM used by GraalVM native-image. ##");
Logger.error("## The StarOpenSource Engine does not support native-image as using reflection in a certain ##");
Logger.error("## way seems to cause the Substrate JVM to crash. Workarounds have failed. ##");
Logger.error("## This has already been noted in issue #3, which you can view here: ##");
Logger.error("## https://git.staropensource.de/StarOpenSource/Engine/issues/3 ##");
Logger.error("## ##");
Logger.error("## While this is sad, we unfortunately can't do anything against it unless we introduce ##");
Logger.error("## annoying and stupid changes into the engine, which we don't want to do. ##");
Logger.error("## ##");
Logger.error("## We're truly sorry for this inconvenience. The sos!engine will now terminate. ##");
Logger.error("##############################################################################################");
Runtime.getRuntime().exit(255);
}
}
/**
* Checks if reflective classpath scanning is supported.
*
* @since v1-alpha8
*/
private void checkReflectiveClasspathScanningCompatibility() {
// Check if reflective classpath scanning is supported
if (System.getProperties().getProperty("sosengine.base.considerEnvironmentUnfriendlyToClasspathScanning", "false").equals("true")) {
Logger.warn("Running in an classpath scanning-unfriendly environment, disabling classpath scanning support.");
Logger.warn("If shit doesn't work and is expected to be discovered by annotations, you'll need to");
Logger.warn("either register it first or have to update some engine configuration setting.");
Logger.warn("Please consult sos!engine's documentation for more information about this issue.");
EngineInternals.getInstance().overrideReflectiveClasspathScanning(false);
}
}
/**
* Checks and warns if the Java version of the
* running JVM is higher than the engine supports.
*
* @since v1-alpha8
*/
private void checkJavaVersion() {
if (JvmInformation.getJavaVersion() > EngineInformation.getJavaSource())
Logger.warn("The StarOpenSource Engine is running on an untested Java version.\nThings may not work as expected or features which can improve performance, stability, compatibility or ease of use may be missing.\nIf you encounter issues, try running a JVM implementing Java " + EngineInformation.getJavaSource());
}
/**
* Caches all base engine events.
*
* @since v1-alpha0
*/
private void cacheEvents() {
EventHelper.cacheEvent(EngineCrashEvent.class);
EventHelper.cacheEvent(EngineShutdownEvent.class);
EventHelper.cacheEvent(EngineSoftCrashEvent.class);
EventHelper.cacheEvent(InternalEngineShutdownEvent.class);
EventHelper.cacheEvent(LogEvent.class);
EventHelper.cacheEvent(ThrowableCatchEvent.class);
}
/**
* Collects all subsystems by their {@link EngineSubsystem} annotation.
*
* @since v1-alpha1
*/
private void collectSubsystems() {
ArrayList<@NotNull DependencySubsystemVector> subsystemsMutable = new ArrayList<>();
Object initializedClassRaw;
SubsystemClass initializedClass;
// Check and initialize all classes, get dependency vector and check version, then add to 'subsystemsMutable'
for (Class<?> clazz : getRawSubsystemClasses())
try {
// Create new instance
initializedClassRaw = clazz.getDeclaredConstructor().newInstance();
initializedClass = null;
// Check if class implements SubsystemMainClass
if (initializedClassRaw instanceof SubsystemClass)
initializedClass = (SubsystemClass) initializedClassRaw;
else
Logger.crash("Failed to initialize subsystem " + clazz.getName() + ": Does not implement " + SubsystemClass.class.getName());
//noinspection DataFlowIssue // the crash call will prevent a NullPointerException
subsystemsMutable.add(new DependencySubsystemVector(initializedClass.getDependencyVector(), initializedClass));
} catch (Exception exception) {
if (exception.getClass() == IllegalStateException.class && exception.getMessage().startsWith("The version string is invalid: "))
Logger.crash("Failed to initialize subsystem " + clazz.getName() + ": Invalid version string: " + exception.getMessage().replace("The version string is invalid: ", ""));
Logger.crash("Failed to initialize subsystem " + clazz.getName() + ": Method invocation error", exception);
}
// Update 'subsystems'
subsystems = new ImmutableLinkedList<>(subsystemsMutable);
}
/**
* Returns a list of classes which are potentially
* eligible for subsystem initialization.
*
* @return potential subsystem classes
* @since v1-alpha5
*/
private Set<@NotNull Class<?>> getRawSubsystemClasses() {
Set<@NotNull Class<?>> classes = new HashSet<>();
if (EngineInternals.getInstance().getReflectiveClasspathScanning()) {
// Scan entire classpath using the Reflections library
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
.setScanners(Scanners.TypesAnnotated)
);
// Get annotated methods
classes = reflections.getTypesAnnotatedWith(EngineSubsystem.class);
} else
for (String path : EngineConfiguration.getInstance().getInitialIncludeSubsystemClasses())
try {
Logger.diag("Resolving class " + path);
classes.add(Class.forName(path));
} catch (ClassNotFoundException exception) {
Logger.error("Failed loading subsystem class " + path + ": Class not found");
}
return classes;
}
/**
* Initializes all subsystems.
*
* @throws Exception exceptions thrown by the {@link DependencyResolver}
* @since v1-alpha1
*/
private void initializeSubsystems() throws Exception {
DependencyResolver resolver = new DependencyResolver();
LinkedList<DependencySubsystemVector> order = new LinkedList<>();
// Add vectors
resolver.addVector(getDependencyVector());
resolver.addVectors(subsystems);
// Resolve dependencies and get order
Logger.diag("Resolving subsystem dependencies");
try {
for (DependencyVector vector : resolver.resolve().getOrder()) // smol workaround
order.add((DependencySubsystemVector) vector);
} catch (Throwable throwable) {
if (throwable instanceof UnmetDependenciesException exception) {
List<@NotNull String> unmetDependencies = exception.getUnmetDependencies();
StringBuilder list = new StringBuilder();
for (String error : unmetDependencies)
list
.append("\n")
.append("- ")
.append(error);
Logger.crash("Found unresolved dependencies:" + list, throwable);
return;
}
Logger.crash("An error occurred trying to resolve subsystem dependencies: " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage()));
throw throwable;
}
// Initialize subsystems
Logger.diag("Initializing engine subsystems");
long initTime;
for (DependencySubsystemVector vector : subsystems) {
Logger.diag("Initializing subsystem '" + vector.getSubsystemClass().getName() + "' (" + vector.getSubsystemClass().getClass().getName() + ")");
try {
initTime = Miscellaneous.measureExecutionTime(() -> vector.getSubsystemClass().initializeSubsystem());
} catch (Throwable throwable) {
Logger.crash("An error occurred trying to initialize subsystem " + vector.getSubsystemClass().getName() + " (" + vector.getSubsystemClass().getClass().getName() + "): " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage()));
throw throwable;
}
Logger.diag("Initialized subsystem '" + vector.getSubsystemClass().getName() + "' (" + vector.getSubsystemClass().getClass().getName() + ") in " + initTime + "ms");
}
// Update 'subsystems'
subsystems = new ImmutableLinkedList<>(order);
}
/**
* Shuts the engine down.
*
* @param exitCode code to exit with, from 0-255
* @since v1-alpha0
*/
public synchronized void shutdown(@Range(from = 0, to = 255) int exitCode) {
if (state == EngineState.UNKNOWN || state == EngineState.SHUTDOWN)
return;
Logger.info("Shutting engine down");
if (state != EngineState.CRASHED)
state = EngineState.SHUTDOWN;
// Make engine single-threaded
Properties properties = new Properties();
properties.setProperty("sosengine.base.optimizeLogging", "false");
properties.setProperty("sosengine.base.optimizeEvents", "false");
EngineConfiguration.getInstance().loadConfiguration(properties);
// Flush log messages
LoggingQueue.flush();
// Disable safety shutdown hook
try {
Runtime.getRuntime().removeShutdownHook(safetyShutdownHook);
} catch (Exception ignored) {}
// Send events
Logger.verb("Notifying classes about shutdown");
new EngineShutdownEvent().callEvent();
Logger.verb("Notifying subsystems about shutdown");
new InternalEngineShutdownEvent().callEvent();
// Delete scheduled files
FileAccess.deleteScheduled();
// Invoke shutdown handler
Logger.verb("Invoking shutdown handler (code " + exitCode + ")");
shutdownHandler.shutdown((short) exitCode);
}
/**
* Shuts the engine down.
*
* @since v1-alpha0
*/
public void shutdown() {
if (instance != null)
instance.shutdown(0);
}
/** {@inheritDoc} */
@Override
public @NotNull String getName() {
return "base";
}
/**
* This method does nothing.
*
* @since v1-alpha1
*/
@Override
public void initializeSubsystem() {}
/** {@inheritDoc} */
@Override
public @NotNull DependencyVector getDependencyVector() {
return new DependencyVector.Builder()
.setIdentifier("engine")
.setVersioningSystem(StarOpenSourceVersioningSystem.class)
.setVersion(EngineInformation.getVersioningString())
.build();
}
/**
* Sets the engine state.
*
* @param state new state
* @throws IllegalAccessException if the caller class is unauthorized
* @since v1-alpha2
*/
public void setState(@NotNull EngineState state) throws IllegalAccessException {
if (!Thread.currentThread().getStackTrace()[2].getClassName().startsWith("de.staropensource.engine.base."))
throw new IllegalAccessException("Only classes inside the \"de.staropensource.engine.base\" package are allowed to call this method.");
this.state = state;
}
/**
* The default shutdown handler, which causes the JVM to exit.
*
* @see ShutdownHandler
* @see System#exit(int)
* @since v1-alpha2
*/
public static final class JvmShutdownHandler implements ShutdownHandler {
/**
* Constructs this class.
*
* @since v1-alpha2
*/
public JvmShutdownHandler() {}
/** {@inheritDoc} */
@Override
public void shutdown(short exitCode) {
// Check if already shutting down
try {
Thread thread = Thread.ofVirtual().unstarted(() -> {});
Runtime.getRuntime().addShutdownHook(thread);
Runtime.getRuntime().removeShutdownHook(thread);
} catch (IllegalStateException exception) {
Logger.warn("Terminating JVM: Already shutting down, skipping");
return;
}
Logger.warn("Terminating JVM");
Runtime.getRuntime().exit(exitCode);
}
}
}

View file

@ -1,524 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base;
import de.staropensource.engine.base.annotation.EngineSubsystem;
import de.staropensource.engine.base.event.LogEvent;
import de.staropensource.engine.base.implementable.Configuration;
import de.staropensource.engine.base.implementable.ShortcodeParser;
import de.staropensource.engine.base.implementable.SubsystemClass;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.logging.backend.async.LoggingThread;
import de.staropensource.engine.base.type.EngineState;
import de.staropensource.engine.base.type.logging.LogLevel;
import de.staropensource.engine.base.type.vector.Vec2f;
import de.staropensource.engine.base.type.vector.Vec2i;
import de.staropensource.engine.base.utility.PropertiesReader;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* Provides the base engine configuration.
* <p>
* This class does not only provide engine settings but is also
* responsible for loading them into memory from {@link Properties} objects.
* <p>
* Now you might ask why we didn't go with the string-based approach.
* The answer is simple: It's a maintenance burden.
* Having various settings strings scattered across many classes will cause
* trouble at some point, which will cause some strings to be undocumented
* or have an inconsistent naming scheme. Containing settings as variables in
* one centralized place mitigates this.
*
* @since v1-alpha0
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration" })
public final class EngineConfiguration extends Configuration {
/**
* Contains the class instance.
*
* @since v1-alpha0
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless {@link Engine} is uninitialized
* @since v1-alpha0
*/
@Getter
private static EngineConfiguration instance;
/**
* Contains the configuration prefix.
*
* @since v1-alpha0
* -- GETTER --
* Returns the configuration prefix.
*
* @return property group
* @since v1-alpha0
*/
private final @NotNull String group = "sosengine.base.";
/**
* Contains if debugging options should be allowed.
* All debugging options will be forcefully set to
* {@code false} if this option is set to {@code false}.
*
* @since v1-alpha0
* -- GETTER --
* Returns if debugging options should be allowed.
* All debugging options will be forcefully set to
* {@code false} if this option is set to {@code false}.
*
* @return debugging enabled?
* @since v1-alpha0
*/
private boolean debug;
/**
* Contains whether or not to log
* events being emitted.
* <p>
* This will cause all events to
* be logged, with the exception
* of the {@link LogEvent}.
*
* @since v1-alpha0
* -- GETTER --
* Returns whether or not to log
* events being emitted.
* <p>
* This will cause all events to
* be logged, with the exception
* of the {@link LogEvent}.
*
* @return detailed event logging enabled?
* @since v1-alpha0
*/
private boolean debugEvents;
/**
* Contains whether or not to automatically discover
* and initialize any class extending {@link SubsystemClass}
* whilst being annotated with {@link EngineSubsystem}.
* <p>
* This mechanism may fail in certain situations, where
* manual subsystem initialization may be desired. Make
* sure to disable this setting before engine startup
* and then initialize all subsystems manually.
*
* @see Engine
* @since v1-alpha5
* -- GETTER --
* Returns whether or not to automatically discover
* and initialize any class extending {@link SubsystemClass}
* whilst being annotated with {@link EngineSubsystem}.
* <p>
* This mechanism may fail in certain situations, where
* manual subsystem initialization may be desired. Make
* sure to disable this setting before engine startup
* and then initialize all subsystems manually.
*
* @return automatically discover and initialize subsystems?
* @since v1-alpha5
*/
private boolean initialPerformSubsystemInitialization;
/**
* Contains a set of class names to try to load
* and initialize as subsystems. Will only take effect
* if {@link #initialPerformSubsystemInitialization} is
* turned off.
*
* @since v1-alpha5
* -- GETTER --
* Returns a set of class names to try to load
* and initialize as subsystems. Will only take effect
* if {@link #getInitialIncludeSubsystemClasses()} is
* turned off.
*
* @return set of class names to try and initialize as subsystems
* @since v1-alpha5
*/
private Set<@NotNull String> initialIncludeSubsystemClasses;
/**
* Contains whether or not to complain about invalid
* shortcodes.
* <p>
* Requires the active log level to be set at least
* to {@link LogLevel#SILENT_WARNING} to have effect.
*
* @see #logLevel
* @since v1-alpha0
* -- GETTER --
* Returns whether or not to complain about invalid
* shortcodes.
* <p>
* Requires the active log level to be set at least
* to {@link LogLevel#SILENT_WARNING} to have effect.
*
* @return complain about invalid shortcodes?
* @see #getLogLevel()
* @since v1-alpha0
*/
private boolean errorShortcodeParser;
/**
* Contains if to log asynchronously.
* <p>
* If enabled, will cause a logging thread
* to spawn. All log messages will be queued
* and printed after a set delay
* ({@link #logPollingSpeed}).
* Highly recommended to keep enabled, or
* the performance of your application will
* very likely suffer.
*
* @see #logPollingSpeed
* @since v1-alpha0
* -- GETTER --
* Returns if to log asynchronously.
* <p>
* If enabled, will cause a logging thread
* to spawn. All log messages will be queued
* and printed after a set delay
* ({@link #getLogPollingSpeed()}).
* Highly recommended to keep enabled, or
* the performance of your application will
* very likely suffer.
*
* @return log asynchronously?
* @see #getLogPollingSpeed()
* @since v1-alpha0
*/
private boolean optimizeLogging;
/**
* Contains whether or not to emit events
* asynchronously.
* <p>
* This will cause a
* <a href="https://openjdk.org/jeps/444">VirtualThread</a>
* to spawn every time an event is emitted.
*
* @since v1-alpha0
* -- GETTER --
* Contains whether or not to emit events
* asynchronously.
* <p>
* This will cause a
* <a href="https://openjdk.org/jeps/444">VirtualThread</a>
* to spawn every time an event is emitted.
*
* @return emit events asynchronously?
* @since v1-alpha0
*/
private boolean optimizeEvents;
/**
* Contains the minimum allowed log level.
* <p>
* The priority list is as follows (from high to low priority):
* <ul>
* <li>{@link LogLevel#CRASH}</li>
* <li>{@link LogLevel#ERROR}</li>
* <li>{@link LogLevel#WARNING}</li>
* <li>{@link LogLevel#INFORMATIONAL}</li>
* <li>{@link LogLevel#SILENT_WARNING}</li>
* <li>{@link LogLevel#VERBOSE}</li>
* <li>{@link LogLevel#DIAGNOSTIC}</li>
* </ul>
*
* @since v1-alpha0
* -- GETTER --
* Returns the minimum allowed log level.
* <p>
* The priority list is as follows (from high to low priority):
* <ul>
* <li>{@link LogLevel#CRASH}</li>
* <li>{@link LogLevel#ERROR}</li>
* <li>{@link LogLevel#WARNING}</li>
* <li>{@link LogLevel#INFORMATIONAL}</li>
* <li>{@link LogLevel#SILENT_WARNING}</li>
* <li>{@link LogLevel#VERBOSE}</li>
* <li>{@link LogLevel#DIAGNOSTIC}</li>
* </ul>
*
* @return minimum allowed log level
* @since v1-alpha0
*/
private LogLevel logLevel;
/**
* Contains a comma-separated list of optional
* features to add to the final log output.
* <p>
* Available features (in order of appearance):
* <ul>
* <li><code>formatting</code></li>
* <li><code>runtime</code></li>
* <li><code>date</code></li>
* <li><code>time</code></li>
* <li><code>shortIssuerClass</code></li>
* <li><code>moduleName</code></li>
* <li><code>moduleVersion</code> (requires <code>moduleName</code>)</li>
* <li><code>methodName</code></li>
* <li><code>lineNumber</code></li>
* </ul>
*
* @since v1-alpha8
* -- GETTER --
* Returns a comma-separated list of optional
* features to add to the final log output.
* <p>
* Available features (in order of appearance):
* <ul>
* <li><code>formatting</code></li>
* <li><code>runtime</code></li>
* <li><code>date</code></li>
* <li><code>time</code></li>
* <li><code>shortIssuerClass</code></li>
* <li><code>moduleName</code></li>
* <li><code>moduleVersion</code> (requires <code>moduleName</code>)</li>
* <li><code>methodName</code></li>
* <li><code>lineNumber</code></li>
* </ul>
*
* @return optional features to enable
* @since v1-alpha8
*/
private Set<@NotNull String> logFeatures;
/**
* Contains how fast the logging thread will
* poll for queued messages in milliseconds.
* This also causes messages to be buffered.
* <p>
* Only applies if {@code optimizeLogging} is turned on.
* Values below {@code 1} will poll for queued messages
* as fast as it can. This however has pretty much no
* benefit. Leave it at {@code 5}, it works quite well.
*
* @see #optimizeLogging
* @since v1-alpha4
* -- GETTER --
* Contains how fast the logging thread will
* poll for queued messages, in milliseconds.
* This also causes messages to be buffered.
* <p>
* Only applies if {@code optimizeLogging} is turned on.
* Values below {@code 1} will poll for queued messages
* as fast as it can. This however has pretty much no
* benefit. Leave it at {@code 5}, it works quite well.
*
* @return logging thread polling speed in milliseconds
* @see #isOptimizeLogging()
* @since v1-alpha4
*/
private int logPollingSpeed;
/**
* Contains whether or not to forcefully write
* to the standard output instead of the
* standard error stream.
* <p>
* This only applies to the {@link LogLevel#ERROR} and
* {@link LogLevel#CRASH} log levels, as these use
* the standard error stream by default.
*
* @see <a href="https://man7.org/linux/man-pages/man3/stderr.3.html">man page about standard streams</a>
* @since v1-alpha0
* -- GETTER --
* Contains whether or not to forcefully write
* to the standard output instead of the
* standard error stream.
* <p>
* This only applies to the {@link LogLevel#ERROR} and
* {@link LogLevel#CRASH} log levels, as these use
* the standard error stream by default.
*
* @return force use stdout?
* @see <a href="https://man7.org/linux/man-pages/man3/stderr.3.html">man page about standard streams</a>
* @since v1-alpha0
*/
private boolean logForceStandardOutput;
/**
* Contains if to truncate the full path
* of a class when invoking using their
* {@link #toString()} method.
* <p>
* Here's an example: Lets say that you have a
* {@link Vec2f} instance and want to convert
* it to a String. You can do that by using
* {@link Vec2f}'s {@link Vec2f#toString()}
* method. With this flag disabled it will
* return
* {@code de.staropensource.engine.base.types.vectors.}{@link Vec2i}{@code (x=64 y=64)}.
* With this flag enabled however the method will return
* {@link Vec2i}{@code (x=64 y=64)},
* which is much smaller.
*
* @since v1-alpha2
* -- GETTER --
* Returns if to truncate the full path
* of a class when invoking using their
* {@link #toString()} method.
* <p>
* Here's an example: Lets say that you have a
* {@link Vec2f} instance and want to convert
* it to a String. You can do that by using
* {@link Vec2f}'s {@link Vec2f#toString()}
* method. With this flag disabled it will
* return
* {@code de.staropensource.engine.base.types.vectors.}{@link Vec2i}{@code (x=64 y=64)}.
* With this flag enabled however the method will return
* {@link Vec2i}{@code (x=64 y=64)},
* which is much smaller.
*
* @return truncate class paths?
* @since v1-alpha2
*/
private boolean hideFullTypePath;
/**
* Constructs this class.
*
* @see Engine
* @since v1-alpha6
*/
EngineConfiguration() {
super();
instance = this;
// Load default configuration
loadDefaultConfiguration();
}
/** {@inheritDoc} */
@Override
protected void matchProperty(@NotNull PropertiesReader parser, @NotNull String property) {
try {
switch (property) {
case "debug" -> debug = parser.getBoolean(group + property);
case "debugEvents" -> debugEvents = parser.getBoolean(group + property);
case "initialPerformSubsystemInitialization" -> initialPerformSubsystemInitialization = parser.getBoolean(group + property);
case "initialIncludeSubsystemClasses" -> {
initialIncludeSubsystemClasses = new HashSet<>();
initialIncludeSubsystemClasses.addAll(Arrays.stream(parser.getString(group + property).split(",")).toList());
}
case "errorShortcodeParser" -> errorShortcodeParser = parser.getBoolean(group + property);
case "optimizeLogging" -> {
optimizeLogging = parser.getBoolean(group + property);
// Start logging thread automatically
if (optimizeLogging && Engine.getInstance().getState() == EngineState.RUNNING) {
LoggingThread.startThread(false);
}
}
case "optimizeEvents" -> optimizeEvents = parser.getBoolean(group + property);
case "logLevel" -> {
try {
logLevel = LogLevel.valueOf(parser.getString(group + property).toUpperCase());
} catch (IllegalArgumentException ignored) {
Logger.error("The log level '" + parser.getString(group + property) + "' is not valid");
}
}
case "logFeatures" -> logFeatures = Set.copyOf(Arrays.stream(parser.getString(group + property).split(",")).toList());
case "logPollingSpeed" -> logPollingSpeed = parser.getInteger(group + property, true);
case "logForceStandardOutput" -> logForceStandardOutput = parser.getBoolean(group + property);
case "hideFullTypePath" -> hideFullTypePath = parser.getBoolean(group + property);
}
} catch (NullPointerException ignored) {}
}
/** {@inheritDoc} */
@Override
protected void processSettings(@NotNull PropertiesReader parser) {
// Disable all debugging switches if 'debug' is disabled
if (!debug) {
debugEvents = false;
}
}
/** {@inheritDoc} */
@Override
public void loadDefaultConfiguration() {
debug = false;
debugEvents = false;
initialPerformSubsystemInitialization = true;
initialIncludeSubsystemClasses = new HashSet<>();
errorShortcodeParser = true;
optimizeLogging = true;
optimizeEvents = true;
logLevel = LogLevel.INFORMATIONAL;
logFeatures = Set.of("formatting", "time", "methodName", "lineNumber");
logPollingSpeed = 5;
logForceStandardOutput = false;
hideFullTypePath = false;
}
/** {@inheritDoc} */
@Override
public @Nullable Object getSetting(@NotNull String setting) {
return switch (setting) {
case "debug" -> debug;
case "debugEvents" -> debugEvents;
case "initialPerformSubsystemInitialization" -> initialPerformSubsystemInitialization;
case "initialIncludeSubsystemClasses" -> initialIncludeSubsystemClasses;
case "errorShortcodeParser" -> errorShortcodeParser;
case "optimizeLogging" -> optimizeLogging;
case "optimizeEvents" -> optimizeEvents;
case "logLevel" -> logLevel;
case "logFeatures" -> logFeatures;
case "logPollingSpeed" -> logPollingSpeed;
case "logForceStandardOutput" -> logForceStandardOutput;
case "hideFullTypePath" -> hideFullTypePath;
default -> null;
};
}
}

View file

@ -1,226 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base;
import de.staropensource.engine.base.exception.IllegalAccessException;
import de.staropensource.engine.base.implementable.EventListenerCode;
import de.staropensource.engine.base.implementable.ShutdownHandler;
import de.staropensource.engine.base.implementable.helper.EventHelper;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.EventPriority;
import de.staropensource.engine.base.type.InternalAccessArea;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Class which allows access to the internals
* and changing the behaviour of the engine.
*
* @since v1-alpha4
*/
@SuppressWarnings({ "JavadocDeclaration" })
public final class EngineInternals {
/**
* Contains the class instance.
*
* @since v1-alpha4
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless the engine is uninitialized
* @since v1-alpha4
*/
@Getter
private static EngineInternals instance;
/**
* Contains all disabled internal access areas.
*
* @since v1-alpha4
* -- GETTER --
* Returns all disabled internal access areas.
*
* @return restricted areas
* @since v1-alpha4
*/
@Getter
private final @NotNull List<@NotNull InternalAccessArea> restrictedAreas = new ArrayList<>();
/**
* Contains whether the engine should reflectively
* search the classpath for events or other annotations.
* <p>
* If disabled, code will either have to manually call
* registration methods or certain classes have to
* be created in a certain package, depending on the
* use case and application.
*
* @see EventHelper#registerEvent(Class, EventListenerCode)
* @see EventHelper#registerEvent(Class, EventListenerCode, EventPriority)
* @since v1-alpha5
*/
private boolean reflectiveClasspathScanning = true;
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha6
*/
EngineInternals() {
// Only allow one instance
if (instance == null && Engine.getInstance() != null)
instance = this;
else
Logger.crash("Only one instance of this class is allowed, use getInstance() instead of creating a new instance");
}
/**
* Determines whether access to the specified area is allowed.
*
* @param area internal access area to check
* @throws IllegalAccessException when restricted
* @since v1-alpha4
*/
private void isRestricted(@NotNull InternalAccessArea area) throws IllegalAccessException {
if (restrictedAreas.contains(area))
throw new IllegalAccessException("The internal access area " + area.name() + " has been restricted");
}
/**
* Restricts access to certain areas of this class.
*
* @param area area to restrict
* @since v1-alpha4
*/
public void restrictAccess(@NotNull InternalAccessArea area) {
switch (area) {
case ALL -> {
List<@NotNull InternalAccessArea> areas = new ArrayList<>(List.of(InternalAccessArea.values()));
areas.remove(InternalAccessArea.ALL);
areas.remove(InternalAccessArea.ALL_READ);
areas.remove(InternalAccessArea.ALL_WRITE);
areas.remove(InternalAccessArea.ALL_READ_ESSENTIAL);
restrictedAreas.addAll(areas);
}
case ALL_WRITE -> restrictedAreas.addAll(Arrays.stream(InternalAccessArea.valuesWriteOnly()).toList());
case ALL_READ -> restrictedAreas.addAll(Arrays.stream(InternalAccessArea.valuesReadOnly()).toList());
case ALL_READ_ESSENTIAL -> restrictedAreas.addAll(Arrays.stream(InternalAccessArea.valuesEssentialReadOnly()).toList());
default -> restrictedAreas.add(area);
}
}
/**
* Installs or uninstalls the JVM shutdown
* hook, which prevents the JVM from exiting
* before the engine has fully shut down.
* Highly recommended to keep enabled.
*
* @param status {@code true} to install, {@code false} otherwise
* @throws IllegalAccessException when restricted ({@link InternalAccessArea#SAFETY_SHUTDOWN_HOOK_UPDATE})
* @since v1-alpha4
*/
public void installSafetyShutdownHook(boolean status) throws IllegalAccessException {
isRestricted(InternalAccessArea.SAFETY_SHUTDOWN_HOOK_UPDATE);
try {
if (status)
Runtime.getRuntime().addShutdownHook(Engine.getInstance().getSafetyShutdownHook());
else
Runtime.getRuntime().removeShutdownHook(Engine.getInstance().getSafetyShutdownHook());
} catch (IllegalArgumentException | IllegalStateException ignored) {}
}
/**
* Gets the engine's shutdown handler.
* The shutdown handler is responsible for
* shutting down the JVM safely.
*
* @return shutdown handler
* @throws IllegalAccessException when restricted ({@link InternalAccessArea#SHUTDOWN_HANDLER_GET})
* @since v1-alpha4
*/
public @NotNull ShutdownHandler getShutdownHandler() throws IllegalAccessException {
isRestricted(InternalAccessArea.SHUTDOWN_HANDLER_GET);
return Engine.getInstance().getShutdownHandler();
}
/**
* Sets the engine's shutdown handler.
* The shutdown handler is responsible for
* shutting down the JVM safely.
*
* @param shutdownHandler new shutdown handler
* @throws IllegalAccessException when restricted ({@link InternalAccessArea#SHUTDOWN_HANDLER_UPDATE})
* @since v1-alpha4
*/
public void setShutdownHandler(@NotNull ShutdownHandler shutdownHandler) throws IllegalAccessException {
isRestricted(InternalAccessArea.SHUTDOWN_HANDLER_UPDATE);
Engine.getInstance().setShutdownHandler(shutdownHandler);
}
/**
* Returns whether the engine should reflectively
* search the classpath for events or other annotations.
* <p>
* If disabled, code will either have to manually call
* registration methods or certain classes have to
* be created in a certain package, depending on the
* use case and application.
*
* @return reflective classpath scanning flag state
* @throws IllegalAccessException when restricted ({@link InternalAccessArea#REFLECTIVE_CLASSPATH_SCANNING_GET})
* @see EventHelper#registerEvent(Class, EventListenerCode)
* @see EventHelper#registerEvent(Class, EventListenerCode, EventPriority)
* @since v1-alpha5
*/
public boolean getReflectiveClasspathScanning() throws IllegalAccessException {
isRestricted(InternalAccessArea.REFLECTIVE_CLASSPATH_SCANNING_GET);
return reflectiveClasspathScanning;
}
/**
* Overrides whether the engine should reflectively
* search the classpath for events or other annotations.
* <p>
* If disabled, code will either have to manually call
* registration methods or certain classes have to
* be created in a certain package, depending on the
* use case and application.
* <p>
* Enabling reflective classpath scanning in an unsupported
* environment may cause minor to extreme side effects,
* including but not limited to <b>bugs, exceptions, engine
* or even whole JVM crashes</b>. <i>You have been warned!</i>
*
* @param reflectiveClasspathScanning new reflective classpath scanning
* @throws IllegalAccessException when restricted ({@link InternalAccessArea#REFLECTIVE_CLASSPATH_SCANNING_OVERRIDE})
* @see EventHelper#registerEvent(Class, EventListenerCode)
* @see EventHelper#registerEvent(Class, EventListenerCode, EventPriority)
* @since v1-alpha5
*/
public void overrideReflectiveClasspathScanning(boolean reflectiveClasspathScanning) throws IllegalAccessException {
isRestricted(InternalAccessArea.REFLECTIVE_CLASSPATH_SCANNING_OVERRIDE);
this.reflectiveClasspathScanning = reflectiveClasspathScanning;
}
}

View file

@ -1,64 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.event;
import de.staropensource.engine.base.implementable.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Called before a new log message is printed.
*
* @since v1-alpha0
*/
public final class LogEvent implements Event {
/**
* Creates and initializes an instance of this event.
*
* @since v1-alpha0
*/
public LogEvent() {}
/**
* {@inheritDoc}
*
* @deprecated use the {@code callEvent} method with arguments
* @see #callEvent(LogLevel, Class, String, String, String)
*/
@Deprecated
@Override
public void callEvent() {}
/**
* Emits the event and calls all event listeners.
*
* @param level level
* @param issuerClass issuer class
* @param issuerOrigin issuer origin
* @param issuerMetadata issuer metadata
* @param message message
* @since v1-alpha0
*/
public void callEvent(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message) {
EventHelper.invokeAnnotatedMethods(getClass(), level, issuerClass, issuerOrigin, issuerMetadata, message);
}
}

View file

@ -1,46 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception;
import org.jetbrains.annotations.NotNull;
/**
* Thrown the throwing method is not allowed to be called.
*
* @since v1-alpha4
*/
public class IllegalAccessException extends RuntimeException {
/**
* Creates and initializes an instance of this exception.
*
* @since v1-alpha2
*/
public IllegalAccessException() {}
/**
* Creates and initializes an instance of this exception.
*
* @param message message
* @since v1-alpha2
*/
public IllegalAccessException(@NotNull String message) {
super(message);
}
}

View file

@ -1,42 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception;
import de.staropensource.engine.base.type.Tristate;
/**
* Thrown when converting a {@link Tristate} into a {@link Boolean} fails.
* <p>
* This exception inherits {@link RuntimeException} on purpose,
* as sometimes you may sure/have already validated that the
* {@link Tristate} is not {@link Tristate#UNSET}.
*
* @since v1-alpha2
*/
public class TristateConversionException extends RuntimeException {
/**
* Creates and initializes an instance of this exception.
*
* @since v1-alpha2
*/
public TristateConversionException() {
super("Tristate.UNSET cannot be converted into a boolean");
}
}

View file

@ -1,48 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when a sequence of if checks or switch cases fail unexpectedly.
*
* @since v1-alpha2
*/
public class UnexpectedCheckEndException extends RuntimeException {
/**
* Creates and initializes an instance of this exception.
*
* @param checkOccurrence the sequence of checks that failed
* @since v1-alpha2
*/
public UnexpectedCheckEndException(@NotNull String checkOccurrence) {
super("A sequence of if checks or switch cases failed unexpectedly while " + checkOccurrence);
}
/**
* Creates and initializes an instance of this exception.
*
* @since v1-alpha2
*/
public UnexpectedCheckEndException() {
super("A sequence of if checks or switch cases failed unexpectedly");
}
}

View file

@ -1,53 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import de.staropensource.engine.base.type.reflection.ClassType;
import de.staropensource.engine.base.utility.ListFormatter;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when the invoked method does not apply to the type of the class.
*
* @since v1-alpha2
*/
public class IncompatibleTypeException extends RuntimeException {
/**
* Creates and initializes an instance of this exception.
*
* @param methodName name of the method that failed
* @param requiredClassType class type received by the method
* @param compatibleTypes class types the method is compatible with
*/
public IncompatibleTypeException(@NotNull String methodName, @NotNull ClassType requiredClassType, @NotNull ClassType @NotNull [] compatibleTypes) {
super("The method ReflectionClass#" + methodName + " only applies to type(s) " + ListFormatter.formatArray(compatibleTypes) + ", not " + requiredClassType.name());
}
/**
* Creates and initializes an instance of this exception.
*
* @param methodName name of the method that failed
* @param requiredClassType class type received by the method
* @param compatibleType class type the method is compatible with
*/
public IncompatibleTypeException(@NotNull String methodName, @NotNull ClassType requiredClassType, @NotNull ClassType compatibleType) {
super("The method ReflectionClass#" + methodName + " only applies to type(s) " + ListFormatter.formatArray(new ClassType[]{ compatibleType }) + ", not " + requiredClassType.name());
}
}

View file

@ -1,39 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when trying to call an instance (non-static) method from a static context.
*
* @since v1-alpha2
*/
public class InstanceMethodFromStaticContextException extends Exception {
/**
* Creates and initializes an instance of this exception.
*
* @param methodName name of the method
* @since v1-alpha2
*/
public InstanceMethodFromStaticContextException(@NotNull String methodName) {
super("Method " + methodName + " could not be called as the method is non-static and was called from a static context");
}
}

View file

@ -1,40 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import de.staropensource.engine.base.reflection.ReflectionClass;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when a field could not be found.
*
* @since v1-alpha2
*/
public class InvalidFieldException extends Exception {
/**
* Creates and initializes an instance of this exception.
*
* @param clazz caller {@link ReflectionClass}
* @param fieldName name of the invalid field
*/
public InvalidFieldException(@NotNull ReflectionClass clazz, @NotNull String fieldName) {
super("Invalid field name \"" + fieldName + "\" in class " + clazz.getPath());
}
}

View file

@ -1,40 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import de.staropensource.engine.base.reflection.ReflectionClass;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when a method could not be found.
*
* @since v1-alpha2
*/
public class InvalidMethodException extends Exception {
/**
* Creates and initializes an instance of this exception.
*
* @param clazz caller {@link ReflectionClass}
* @param fieldName name of the invalid method
*/
public InvalidMethodException(@NotNull ReflectionClass clazz, @NotNull String fieldName) {
super("Invalid method name \"" + fieldName + "\" in class " + clazz.getPath());
}
}

View file

@ -1,40 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import org.jetbrains.annotations.NotNull;
/**
* Thrown if access to some class, method or field has been denied.
*
* @since v1-alpha2
*/
public class NoAccessException extends Exception {
/**
* Creates and initializes an instance of this exception.
*
* @param type {@code class}, {@code method} or {@code field}
* @param name class, method or field name
* @since v1-alpha2
*/
public NoAccessException(@NotNull String type, @NotNull String name) {
super("Access to " + type + " " + name + " has been denied");
}
}

View file

@ -1,54 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.exception.reflection;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when an exception is thrown by a static initializer.
*
* @since v1-alpha2
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration" })
public class StaticInitializerException extends Exception {
/**
* Contains the throwable thrown by the static initializer.
*
* @since v1-alpha2
* -- GETTER --
* Returns the throwable thrown by the static initializer.
*
* @return throwable thrown by the static initializer
* @since v1-alpha2
*/
private final @NotNull Throwable throwable;
/**
* Creates and initializes an instance of this exception.
*
* @param throwable throwable thrown by the static initializer
* @since v1-alpha2
*/
public StaticInitializerException(@NotNull Throwable throwable) {
this.throwable = throwable;
}
}

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Exceptions thrown by implementations of {@link de.staropensource.engine.base.implementable.VersioningSystem}s.
*
* @see de.staropensource.engine.base.implementable.VersioningSystem
* @since v1-alpha1
*/
package de.staropensource.engine.base.exception.versioning;

View file

@ -1,132 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.utility.PropertiesReader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Properties;
/**
* Interface for implementing configuration classes.
* <p>
* Configuration classes use {@link Properties} objects to modify
* their settings as they can be supplied to the JVM's arguments
* and can be written to and read from during runtime.
*
* @since v1-alpha2
*/
public abstract class Configuration {
/**
* Creates and initializes an instance of this abstract class.
*
* @since v1-alpha2
*/
protected Configuration() {
// Load default configuration
loadDefaultConfiguration();
}
/**
* Loads all settings from the specified {@link Properties} object.
* Unless you want to override settings, consider invoking {@link #loadDefaultConfiguration()} first.
*
* @param properties {@link Properties} to read from
* @see #loadDefaultConfiguration()
* @since v1-alpha2
*/
public void loadConfiguration(@NotNull Properties properties) {
PropertiesReader parser = new PropertiesReader(properties);
// Loop through all properties
for (String property : properties.stringPropertyNames()) {
// Check if property name starts with group
if (!property.startsWith(getGroup()))
continue;
// Remove group
property = property.substring(getGroup().length());
// Overwrite matching settings
try {
matchProperty(parser, property);
} catch (NullPointerException ignored) {}
}
processSettings(parser);
}
/**
* Loads all settings from the system properties.
* Useful if you want to allow the user to modify settings at startup.
*
* @see #loadConfiguration(Properties)
* @see System#getProperties()
* @since v1-alpha2
*/
public void loadConfiguration() {
loadConfiguration(System.getProperties());
}
/**
* Returns prefix properties must begin with.
*
* @return property group
* @since v1-alpha2
*/
public abstract @NotNull String getGroup();
/**
* Loads the default subsystem configuration.
*
* @see #loadConfiguration()
* @see #loadConfiguration(Properties)
* @since v1-alpha0
*/
public abstract void loadDefaultConfiguration();
/**
* Matches the given {@code property} against all settings.
* If a match has been found, the setting will be overwritten with the property's value.
*
* @param parser matching {@link PropertiesReader}
* @param property property to match
* @since v1-alpha2
*/
protected abstract void matchProperty(@NotNull PropertiesReader parser, @NotNull String property);
/**
* Allows the implementor to process all settings and potentially
* modify them before {@link #loadConfiguration(Properties)} returns.
*
* @param parser matching {@link PropertiesReader}
* @since v1-alpha2
*/
protected abstract void processSettings(@NotNull PropertiesReader parser);
/**
* Returns a configuration setting.
*
* @param setting setting name
* @return setting's value or {@code null} if not found
*/
public abstract @Nullable Object getSetting(@NotNull String setting);
}

View file

@ -1,59 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.implementable.helper.EventHelper;
import de.staropensource.engine.base.type.EventPriority;
import org.jetbrains.annotations.NotNull;
/**
* Used by {@link EventHelper} to execute event listeners.
*
* @see Runnable
* @since v1-alpha5
*/
public abstract class EventListenerCode {
/**
* Contains the priority of this
* event listener.
* <p>
* Set automatically by {@link EventHelper},
* do not change this manually.
*
* @since v1-alpha5
*/
public @NotNull EventPriority priority = EventPriority.DEFAULT;
/**
* Creates and initializes an instance of this abstract class.
*
* @since v1-alpha5
*/
protected EventListenerCode() {}
/**
* Invokes the event listener.
*
* @param arguments arguments passed along by the event
* @throws Exception exceptions thrown
* @since v1-alpha5
*/
public abstract void run(Object... arguments) throws Exception;
}

View file

@ -1,43 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
/**
* Interface for implementing custom logger implementations.
*
* @see Logger#setLoggingAdapter(LoggingAdapter)
* @since v1-alpha0
*/
public interface LoggingAdapter {
/**
* Prints a log message.
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message raw message
* @param format processed log call output (print this!)
* @since v1-alpha2
*/
void print(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message, @NotNull String format);
}

View file

@ -1,218 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.exception.ParserException;
import de.staropensource.engine.base.logging.Logger;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.util.LinkedList;
import java.util.Locale;
/**
* Base class for implementing a shortcode parser.
* <p>
* This class parses a string and converts it into a list of
* components, which can then be in turn be converted to something
* else, for example, ANSI escape codes.
* <p>
* The following shortcodes are available and can be used:
* <ul>
* <li>reset</li>
* <li>fg:[black,red,green,yellow,blue,magenta,cyan,white]</li>
* <li>bg:[black,red,green,yellow,blue,magenta,cyan,white]</li>
* <li>bold</li>
* <li>italic</li>
* <li>strikethrough</li>
* <li>underline</li>
* </ul>
*
* @since v1-alpha1
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration" })
public abstract class ShortcodeParser {
/**
* Contains a list of components the parsed text is made out of.
*
* @since v1-alpha1
* -- GETTER --
* Returns a list of components the parsed text is made out of.
*
* @return component list
* @since v1-alpha1
*/
protected final @NotNull LinkedList<String> components;
/**
* Creates and initializes an instance of this abstract class.
*
* @param string string to parse
* @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text
* @throws ParserException on error
* @since v1-alpha2
*/
protected ShortcodeParser(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
components = parse(string, ignoreInvalidEscapes);
}
/**
* Parses the input string and returns a list
* of components the text is made out of.
*
* @param string string to parse
* @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text
* @return list of components
* @throws ParserException on error
* @see EngineConfiguration#errorShortcodeParser
* @since v1-alpha2
*/
protected @NotNull LinkedList<@NotNull String> parse(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
LinkedList<String> components = new LinkedList<>(); // List of components
boolean tagActive = false; // Indicates that a tag is being parsed
boolean escape = false; // Indicates whether the last character was a \ character
StringBuilder part = new StringBuilder(); // Temporary string. May be a tag, may be regular text
// Iterate through every character
for (char character : string.toCharArray()) {
// Escaping
if (escape) {
if (character == '\\' || character == '<')
part.append(character);
else if (!(character == 'r' || character == 'n'))
if (ignoreInvalidEscapes)
part.append("\\").append(character);
else
throw new ParserException("Invalid escape \\" + character);
escape = false;
continue;
}
if (character == '\\') {
escape = true;
continue;
}
if (tagActive) {
// A tag is being parsed
if (character == '>') {
// Tag is ending, disable tag parsing
tagActive = false;
// fg:*
if (part.toString().startsWith("fg:"))
if (isValidColor(part.substring(3).toUpperCase()))
components.add("COLOR:FOREGROUND:" + part.substring(3).toUpperCase());
else {
// Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser())
Logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text
components.add("TEXT:" + "<" + part + ">");
}
// bg:*
else if (part.toString().startsWith("bg:"))
if (isValidColor(part.substring(3).toUpperCase()))
components.add("COLOR:BACKGROUND:" + part.substring(3).toUpperCase());
else {
// Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser())
Logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text
components.add("TEXT:" + "<" + part + ">");
}
// bold
else if (part.toString().equals("bold"))
components.add("ATTRIBUTE:BOLD");
// italic
else if (part.toString().equals("italic"))
components.add("ATTRIBUTE:ITALIC");
// strikethrough
else if (part.toString().equals("strikethrough"))
components.add("ATTRIBUTE:STRIKETHROUGH");
// underline
else if (part.toString().equals("underline"))
components.add("ATTRIBUTE:UNDERLINE");
// blink
else if (part.toString().equals("blink"))
components.add("ATTRIBUTE:BLINK");
// reset
else if (part.toString().equals("reset"))
components.add("RESET");
// error case
else {
// Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser())
Logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text
components.add("TEXT:" + "<" + part + ">");
}
// Empty 'part'
part = new StringBuilder();
} else
// Tag has not ended yet, add character to 'part'
// It bloats the code to do it with StringBuilder
part.append(character);
} else {
// Regular text is being parsed
if (character == '<') {
if (!part.isEmpty()) {
// Tag is starting, insert previous text
components.add("TEXT:" + part);
part = new StringBuilder();
}
tagActive = true; // Enable tag processing
} else
// Regular text, add character to 'part'
// It bloats the code to do it with StringBuilder
part.append(character);
}
}
// Processing ended, insert leftover text
if (!part.isEmpty())
components.add("TEXT:" + part);
return components;
}
/**
* Returns if the specified color is valid
*
* @return {@code true} if valid, {@code false} otherwise
* @since v1-alpha2
*/
private boolean isValidColor(@NotNull String color) {
return switch (color.toLowerCase(Locale.ROOT)) {
case "black", "white", "red",
"green", "blue", "yellow",
"magenta", "cyan" -> true;
default -> false;
};
}
}

View file

@ -1,42 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.Engine;
import org.jetbrains.annotations.Range;
/**
* Interface for custom shutdown handlers.
* <p>
* Shutdown handlers are responsible for shutting down
* the platform safely after the engine has shut down.
*
* @see Engine#setShutdownHandler(ShutdownHandler)
* @since v1-alpha2
*/
public interface ShutdownHandler {
/**
* Executes the shutdown handler.
*
* @param exitCode exit code
* @since v1-alpha2
*/
void shutdown(@Range(from = 0, to = 255) short exitCode);
}

View file

@ -1,79 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable;
import de.staropensource.engine.base.Engine;
import de.staropensource.engine.base.annotation.EngineSubsystem;
import de.staropensource.engine.base.annotation.EventListener;
import de.staropensource.engine.base.event.InternalEngineShutdownEvent;
import de.staropensource.engine.base.type.DependencyVector;
import org.jetbrains.annotations.NotNull;
/**
* Abstract class for building subsystem main classes.
*
* @see EngineSubsystem
* @since v1-alpha0
*/
public abstract class SubsystemClass {
/**
* Creates and initializes an instance of this abstract class.
*
* @since v1-alpha2
*/
protected SubsystemClass() {}
/**
* Returns the name of the subsystem.
*
* @return subsystem name
* @since v1-alpha2
*/
public abstract @NotNull String getName();
/**
* Initializes the subsystem.
*
* @since v1-alpha1
*/
public abstract void initializeSubsystem();
/**
* Returns a matching {@link DependencyVector}.
* Used for dependency resolution during startup.
*
* @return matching {@link DependencyVector} for the subsystem
* @throws IllegalStateException when building the DependencyVector fails, see {@link DependencyVector.Builder#build()}
* @see DependencyVector
* @since v1-alpha4
*/
public abstract @NotNull DependencyVector getDependencyVector() throws IllegalStateException;
/**
* Called on engine shutdown.
*
* @see Engine#shutdown()
* @see Engine#shutdown(int)
* @since v1-alpha0
*/
@EventListener(event = InternalEngineShutdownEvent.class)
@SuppressWarnings({ "unused" })
protected static void shutdownSubsystem() {}
}

View file

@ -1,257 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementable.helper;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.EngineInternals;
import de.staropensource.engine.base.annotation.EventListener;
import de.staropensource.engine.base.event.LogEvent;
import de.staropensource.engine.base.exception.reflection.InstanceMethodFromStaticContextException;
import de.staropensource.engine.base.exception.reflection.InvalidMethodSignatureException;
import de.staropensource.engine.base.exception.reflection.NoAccessException;
import de.staropensource.engine.base.exception.reflection.StaticInitializerException;
import de.staropensource.engine.base.implementable.Event;
import de.staropensource.engine.base.implementable.EventListenerCode;
import de.staropensource.engine.base.internal.implementation.EventListenerMethod;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.EventPriority;
import de.staropensource.engine.base.utility.ListFormatter;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Simplifies event logging and calling.
*
* @since v1-alpha0
*/
@Getter
public final class EventHelper {
/**
* Holds all cached events.
*
* @since v1-alpha5
*/
private static final @NotNull Map<@NotNull Class<? extends Event>, LinkedList<@NotNull EventListenerCode>> cachedEventListeners = new HashMap<>();
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha0
*/
private EventHelper() {}
/**
* Registers a new {@link Event}.
* <p>
* This method does nothing if classpath searching is disabled.
*
* @param event {@link Event} to register for
* @param eventListener {@link EventListenerCode} to register
* @param priority priority of the listener
* @see EngineInternals#getReflectiveClasspathScanning()
* @since v1-alpha5
*/
public static synchronized void registerEvent(@NotNull Class<? extends Event> event, @NotNull EventListenerCode eventListener, @NotNull EventPriority priority) {
if (EngineInternals.getInstance().getReflectiveClasspathScanning())
return;
// Update 'eventListener' priority
eventListener.priority = priority;
// Check if event already exists in map
// If not, create entry with a LinkedList
if (cachedEventListeners.containsKey(event))
if (cachedEventListeners.get(event).contains(eventListener))
return;
else
cachedEventListeners.get(event).add(eventListener);
else {
LinkedList<@NotNull EventListenerCode> list = new LinkedList<>();
list.add(eventListener);
cachedEventListeners.put(event, list);
}
Logger.diag("Registered event listener " + eventListener + " for event " + event + " with priority " + priority.name());
}
/**
* Registers a new {@link Event}.
* <p>
* This method does nothing if classpath searching is disabled.
*
* @param event {@link Event} to register for
* @param eventListener {@link EventListenerCode} to register
* @see EngineInternals#getReflectiveClasspathScanning()
* @since v1-alpha5
*/
public static void registerEvent(@NotNull Class<? extends Event> event, @NotNull EventListenerCode eventListener) {
registerEvent(event, eventListener, EventPriority.DEFAULT);
}
/**
* (Re-)Caches all event listeners for some {@link Event}.
* <p>
* This method does nothing if classpath searching is enabled.
*
* @param event event to (re-)cache. Set to {@code null} to recompute all cached events
* @see EngineInternals#getReflectiveClasspathScanning()
* @since v1-alpha5
*/
public static synchronized void cacheEvent(@Nullable Class<? extends Event> event) {
if (!EngineInternals.getInstance().getReflectiveClasspathScanning())
return;
if (event == null)
for (Class<? extends Event> cachedEvent : cachedEventListeners.keySet())
cacheEvent(cachedEvent);
else {
LinkedList<@NotNull EventListenerCode> annotatedMethods = getAnnotatedMethods(event);
if (cachedEventListeners.containsKey(event))
cachedEventListeners.replace(event, annotatedMethods);
else
cachedEventListeners.put(event, annotatedMethods);
}
}
/**
* Removes an event from the event listener cache.
* <p>
* This method does nothing if classpath searching is enabled.
*
* @param event event to uncache. Set to {@code null} to clear the entire cache
* @see EngineInternals#getReflectiveClasspathScanning()
* @since v1-alpha5
*/
public static synchronized void uncacheEvent(@Nullable Class<? extends Event> event) {
if (!EngineInternals.getInstance().getReflectiveClasspathScanning())
return;
if (event == null)
cachedEventListeners.clear();
else
cachedEventListeners.remove(event);
}
/**
* Invokes all event listeners.
*
* @param event event class
* @param arguments arguments to pass to event listeners
* @since v1-alpha5
*/
public static void invokeAnnotatedMethods(@NotNull Class<? extends Event> event, Object... arguments) {
if (event != LogEvent.class && EngineConfiguration.getInstance().isDebugEvents())
if (arguments.length == 0)
Logger.diag("Event " + event.getName() + " was emitted");
else
Logger.diag("Event " + event.getName() + " was emitted, passing arguments " + ListFormatter.formatArray(arguments));
Runnable eventCode = () -> {
for (EventListenerCode eventListener : getAnnotatedMethods(event)) {
try {
eventListener.run(arguments);
} catch (NoAccessException exception) {
Logger.warn("Event listener " + eventListener + " could not be called as the method could not be accessed");
} catch (InvalidMethodSignatureException exception) {
Logger.warn("Event listener " + eventListener + " has an invalid method signature");
} catch (InvocationTargetException exception) {
Logger.crash("Event listener " + eventListener + " threw a throwable", exception.getTargetException(), true);
} catch (InstanceMethodFromStaticContextException exception) {
Logger.warn("Event listener " + eventListener + " is not static. Event listener methods must be static for them to be called.");
} catch (StaticInitializerException exception) {
Logger.crash("Event listener " + eventListener + " could not be called as the static initializer failed", exception.getThrowable(), true);
} catch (Exception exception) {
Logger.crash("Event listener " + eventListener + " could not be called as an error occurred during reflection", exception, true);
}
}
};
if (EngineConfiguration.getInstance().isOptimizeEvents())
Thread
.ofVirtual()
.name("Event " + event.getName())
.start(eventCode);
else
eventCode.run();
}
/**
* Returns all {@link EventListener}s listening on some event.
* The classpath will be scanned for listeners, unless cached results exist and {@code !forceScanning}.
*
* @param event event class
* @param forceScanning forces scanning the classpath for listeners. not recommended due to a huge performance penalty
* @return list of event listeners
* @see #cacheEvent(Class)
* @since v1-alpha5
*/
public static @NotNull LinkedList<EventListenerCode> getAnnotatedMethods(@NotNull Class<? extends Event> event, boolean forceScanning) {
LinkedList<EventListenerCode> eventListeners = new LinkedList<>();
if (!EngineInternals.getInstance().getReflectiveClasspathScanning())
return Objects.requireNonNullElse(cachedEventListeners.get(event), eventListeners);
if (forceScanning || !cachedEventListeners.containsKey(event)) {
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
.setScanners(Scanners.MethodsAnnotated)
);
// Get annotated methods
Set<@NotNull Method> annotatedMethods = reflections.getMethodsAnnotatedWith(EventListener.class);
// Sort event listeners not listening for the specified event out
for (Method method : annotatedMethods)
if (method.getAnnotation(EventListener.class).event() == event)
eventListeners.add(new EventListenerMethod(method));
// Sort list after event priority
eventListeners.sort(Comparator.comparing(method -> Objects.requireNonNull(((EventListenerMethod) method).getAnnotation(EventListener.class)).priority()));
} else
// Event listeners are cached and !forceScanning, return cached results
eventListeners = cachedEventListeners.get(event);
return eventListeners;
}
/**
* Returns all {@link EventListener}s listening on some event.
* The classpath will be scanned for listeners, unless cached results exist.
*
* @param event event class
* @return list of event listeners
* @since v1-alpha5
*/
public static @NotNull LinkedList<EventListenerCode> getAnnotatedMethods(@NotNull Class<? extends Event> event) {
return getAnnotatedMethods(event, false);
}
}

View file

@ -1,56 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementation.logging;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.implementable.LoggingAdapter;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.logging.LogLevel;
import de.staropensource.engine.base.implementation.shortcode.EmptyShortcodeParser;
import org.jetbrains.annotations.NotNull;
/**
* Prints log messages to the console, without any fancy colors or formatting.
*
* @see Logger
* @see LoggingAdapter
* @since v1-alpha1
*/
public class PlainLoggingAdapter implements LoggingAdapter {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha1
*/
public PlainLoggingAdapter() {}
/** {@inheritDoc} */
@Override
public void print(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message, @NotNull String format) {
format = new EmptyShortcodeParser(format, true).getClean();
if (level == LogLevel.ERROR || level == LogLevel.CRASH)
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isLogForceStandardOutput())
System.out.println(format);
else
System.err.println(format);
else
System.out.println(format);
}
}

View file

@ -1,44 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementation.logging;
import de.staropensource.engine.base.implementable.LoggingAdapter;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* An implementation of {@link LoggingAdapter}, which does nothing.
* Useful if you want to silence engine startup messages.
*
* @since v1-alpha4
*/
public class QuietLoggingAdapter implements LoggingAdapter {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha4
*/
public QuietLoggingAdapter() {}
/** {@inheritDoc} */
@Override
public void print(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message, @NotNull String format) {}
}

View file

@ -1,56 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.implementation.logging;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.implementable.LoggingAdapter;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Prints log messages to the console, without performing any message changes.
* Will reveal shortcodes as they will not be replaced.
*
* @see Logger
* @see LoggingAdapter
* @since v1-alpha1
*/
public class RawLoggingAdapter implements LoggingAdapter {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha1
*/
public RawLoggingAdapter() {}
/** {@inheritDoc} */
@Override
public void print(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message, @NotNull String format) {
if (level == LogLevel.ERROR || level == LogLevel.CRASH)
if (EngineConfiguration.getInstance().isLogForceStandardOutput())
System.out.println(format);
else
System.err.println(format);
else
System.out.println(format);
}
}

View file

@ -1,25 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* A set of built-in {@link de.staropensource.engine.base.implementable.LoggingAdapter}s.
*
* @since v1-alpha1
*/
package de.staropensource.engine.base.implementation.logging;

View file

@ -1,83 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.internal.implementation;
import de.staropensource.engine.base.implementable.EventListenerCode;
import de.staropensource.engine.base.reflection.Reflect;
import de.staropensource.engine.base.reflection.ReflectionMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* Interface specifically for executing event listener methods.
*
* @since v1-alpha5
*/
public final class EventListenerMethod extends EventListenerCode {
/**
* Contains the method to call and get.
*
* @since v1-alpha5
*/
private final @NotNull ReflectionMethod method;
/**
* Creates and initializes an instance of this class.
*
* @param method method to execute
* @since v1-alpha5
*/
public EventListenerMethod(@NotNull Method method) {
this.method = Reflect.reflectOn(method);
}
/** {@inheritDoc} */
@Override
public void run(@Nullable Object @NotNull [] arguments) throws Exception {
method.invoke(arguments);
}
/**
* Forwards {@link ReflectionMethod#getAnnotation(Class)}
* to the internal {@link ReflectionMethod} instance.
*
* @param <T> annotation
* @param annotation annotation to get
* @return annotation or {@code null} on error
* @see ReflectionMethod#getAnnotation(Class)
* @since v1-alpha5
*/
public <T extends Annotation> @Nullable T getAnnotation(@NotNull Class<T> annotation) {
try {
return method.getAnnotation(annotation);
} catch (NullPointerException exception) {
return null;
}
}
/** {@inheritDoc} */
@Override
public String toString() {
return "method " + method.getMethod().getDeclaringClass().getName() + "#" + method.getName();
}
}

View file

@ -1,25 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Interfaces and abstract classes which can be used for implementing classes.
*
* @since v1-alpha5
*/
package de.staropensource.engine.base.internal.implementation;

View file

@ -1,46 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.internal.implementation.placeholder;
import de.staropensource.engine.base.implementable.Placeholder;
import de.staropensource.engine.base.utility.information.EngineInformation;
import org.jetbrains.annotations.NotNull;
/**
* Implements the {@code engine_version_codename} placeholder.
*
* @see Placeholder
* @since v1-alpha8
*/
@SuppressWarnings({ "unused" })
public final class EngineVersionCodename implements Placeholder {
/**
* Creates and initializes an instance of this event.
*
* @since v1-alpha8
*/
public EngineVersionCodename() {}
/** {@inheritDoc} */
@Override
public @NotNull String replace(@NotNull String text) {
return text.replace("%engine_version_codename%", EngineInformation.getVersioningCodename());
}
}

View file

@ -1,30 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Built-in placeholders for various things.
* <p>
* Placeholder classes in subpackages may only be targeted for
* specific use cases.
*
* @see de.staropensource.engine.base.utility.PlaceholderEngine
* @see de.staropensource.engine.base.implementable.Placeholder
* @since v1-alpha0
*/
package de.staropensource.engine.base.internal.implementation.placeholder;

View file

@ -1,205 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.internal.reflection;
import de.staropensource.engine.base.exception.reflection.NoAccessException;
import de.staropensource.engine.base.reflection.ReflectionField;
import de.staropensource.engine.base.reflection.ReflectionMethod;
import java.lang.reflect.*;
/**
* Utility class for widening access permissions on reflection objects.
*
* @since v1-alpha2
*/
public final class ReflectionAccessWidener {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha2
*/
private ReflectionAccessWidener() {}
/**
* Allows access to an {@link AccessibleObject}.
* <p>
* Stolen from <a href="https://github.com/jOOQ/jOOR">the jOOR library</a>.
* All credits to them.
*
* @param <T> extender of {@link AccessibleObject}
* @param accessible object to allow access to
*/
public static <T extends AccessibleObject> void allowAccess(T accessible) {
if (accessible == null)
return;
if (accessible instanceof Member member)
if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers()))
return;
//noinspection deprecation // no, it's what we want
if (!accessible.isAccessible())
accessible.setAccessible(true);
}
/**
* Unlocks modifications to some field.
*
* @param reflectionField {@link ReflectionField} to unlock
* @return updated modifiers. pass those to {@link #lockModifications(ReflectionField, int)} to lock the field again
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the field has been denied
* @see #lockModifications(ReflectionField, int)
* @since v1-alpha2
*/
public static int unlockModifications(ReflectionField reflectionField) throws NoSuchFieldException, NoAccessException {
int updatedModifiers = 0;
Field field = reflectionField.getField();
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
modifiersField.setAccessible(true);
if ((field.getModifiers() & Modifier.FINAL) == Modifier.FINAL)
updatedModifiers = ~Modifier.FINAL;
if ((field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
updatedModifiers = updatedModifiers & ~Modifier.STATIC;
try {
modifiersField.setInt(field, field.getModifiers() & ~updatedModifiers);
} catch (IllegalAccessException exception) {
throw new NoAccessException("field", field.getName());
}
return updatedModifiers;
}
/**
* Unlocks modifications to some method.
*
* @param reflectionMethod {@link ReflectionMethod} to unlock
* @return updated modifiers. pass those to {@link #lockModifications(ReflectionMethod, int)} to lock the method again
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the method has been denied
* @see #lockModifications(ReflectionMethod, int)
* @since v1-alpha2
*/
public static int unlockModifications(ReflectionMethod reflectionMethod) throws NoSuchFieldException, NoAccessException {
Method method = reflectionMethod.getMethod();
int updatedModifiers = method.getModifiers();
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
modifiersField.setAccessible(true);
if (Modifier.isFinal(method.getModifiers()))
updatedModifiers = ~Modifier.FINAL;
if (Modifier.isStatic(method.getModifiers()))
updatedModifiers = updatedModifiers & ~Modifier.STATIC;
if (!Modifier.isPublic(method.getModifiers())) {
if (Modifier.isProtected(method.getModifiers()))
updatedModifiers = updatedModifiers & ~Modifier.PROTECTED;
if (Modifier.isPrivate(method.getModifiers()))
updatedModifiers = updatedModifiers & ~Modifier.PRIVATE;
updatedModifiers = updatedModifiers & ~Modifier.PUBLIC;
}
try {
modifiersField.setInt(method, method.getModifiers() & ~updatedModifiers);
} catch (IllegalAccessException exception) {
throw new NoAccessException("method", method.getName());
}
return updatedModifiers;
}
/**
* Locks modifications to some field.
*
* @param reflectionField {@link ReflectionField} to lock
* @param updatedModifiers original modifiers
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the field has been denied
* @see #unlockModifications(ReflectionField)
* @since v1-alpha2
*/
public static void lockModifications(ReflectionField reflectionField, int updatedModifiers) throws NoSuchFieldException, NoAccessException {
Field field = reflectionField.getField();
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
modifiersField.setAccessible(true);
try {
modifiersField.setInt(field, field.getModifiers() & ~updatedModifiers);
} catch (IllegalAccessException exception) {
throw new NoAccessException("field", field.getName());
}
modifiersField.setAccessible(false);
}
/**
* Locks modifications to some method.
*
* @param reflectionMethod {@link ReflectionMethod} to lock
* @param updatedModifiers original modifiers
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the method has been denied
* @see #unlockModifications(ReflectionMethod)
* @since v1-alpha2
*/
public static void lockModifications(ReflectionMethod reflectionMethod, int updatedModifiers) throws NoSuchFieldException, NoAccessException {
Method method = reflectionMethod.getMethod();
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
modifiersField.setAccessible(true);
try {
modifiersField.setInt(method, method.getModifiers() & ~updatedModifiers);
} catch (IllegalAccessException exception) {
throw new NoAccessException("method", method.getName());
}
modifiersField.setAccessible(false);
}
}

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Utility classes used during reflection.
*
* @see de.staropensource.engine.base.reflection.Reflect
* @since v1-alpha2
*/
package de.staropensource.engine.base.internal.reflection;

View file

@ -1,61 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.internal.type;
import de.staropensource.engine.base.implementable.SubsystemClass;
import de.staropensource.engine.base.type.DependencyVector;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
/**
* Represents a dependency vector with an additional {@code mainClass} field.
* Used during the subsystem initialization process to easily determine the
* initialization order without much extra code and performance loss.
*
* @since v1-alpha1
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration" })
public final class DependencySubsystemVector extends DependencyVector {
/**
* Contains the associated {@link SubsystemClass}.
*
* @since v1-alpha1
* -- GETTER --
* Returns the associated {@link SubsystemClass}.
*
* @return associated {@link SubsystemClass}
* @since v1-alpha1
*/
private final SubsystemClass subsystemClass;
/**
* Creates and initializes an instance of this class.
* Reuses an existing {@link DependencyVector}.
*
* @param vector existing dependency vector to reuse
* @param subsystemClass {@link SubsystemClass} to associate
* @since v1-alpha1
*/
public DependencySubsystemVector(@NotNull DependencyVector vector, @NotNull SubsystemClass subsystemClass) {
super(subsystemClass.getName(), vector.getVersioningSystem(), vector.getVersion(), vector.getDependencies(), vector.getProvides());
this.subsystemClass = subsystemClass;
}
}

View file

@ -1,43 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.internal.type;
import de.staropensource.engine.base.logging.backend.async.LoggingThread;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
/**
* Represents a queued log call.
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @see LoggingThread
* @since v1-alpha8
*/
@SuppressWarnings({ "unused" })
public record QueuedLogCall(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message) {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha8
*/
public QueuedLogCall {}
}

View file

@ -1,416 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.implementable.LoggingAdapter;
import de.staropensource.engine.base.implementation.logging.PlainLoggingAdapter;
import de.staropensource.engine.base.internal.type.QueuedLogCall;
import de.staropensource.engine.base.logging.backend.CrashHandler;
import de.staropensource.engine.base.logging.backend.Filterer;
import de.staropensource.engine.base.logging.backend.Processor;
import de.staropensource.engine.base.logging.backend.async.LoggingQueue;
import de.staropensource.engine.base.type.immutable.ImmutableArrayList;
import de.staropensource.engine.base.type.logging.LogLevel;
import lombok.Getter;
import lombok.Setter;
import org.intellij.lang.annotations.RegExp;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* The frontend class for sos!engine's logging system.
*
* @since v1-alpha8
*/
@SuppressWarnings({ "JavadocDeclaration" })
public final class Logger {
/**
* Refers to the active {@link LoggingAdapter} that is used to process and print log messages.
*
* @see LoggingAdapter
* @since v1-alpha0
* -- GETTER --
* Returns the active {@link LoggingAdapter}.
*
* @return active {@link LoggingAdapter}
* @see LoggingAdapter
* @since v1-alpha0
* -- SETTER --
* Sets the active {@link LoggingAdapter}.
*
* @param loggingAdapter new active {@link LoggingAdapter}
* @see LoggingAdapter
* @since v1-alpha0
*/
@Getter
@Setter
private static @NotNull LoggingAdapter loggingAdapter = new PlainLoggingAdapter();
/**
* Creates and initializes an instance of this class
*
* @since v1-alpha8
*/
private Logger() {}
// -----> Internal management methods
// These methods forward calls to internal methods so
// these can be accessed without exporting a whole package.
/**
* Handles incoming log calls and either
* processes them directly or queues them in.
* <p>
* **This is an internal method. Use with care.**
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @since v1-alpha8
*/
public static void handle(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message) {
Processor.handle(level, issuer, message);
}
/**
* Flushes the logging queue.
* <p>
* **This is an internal method. Use with care.**
*
* @since v1-alpha8
*/
public static void flush() {
LoggingQueue.flush();
}
/**
* Disallows one or multiple classes.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowClass(@RegExp @NotNull String regex) {
Filterer.disallowClass(regex);
}
/**
* Disallows one or multiple modules.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowModule(@RegExp @NotNull String regex) {
Filterer.disallowModule(regex);
}
/**
* Disallows one or multiple messages.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowMessage(@RegExp @NotNull String regex) {
Filterer.disallowMessage(regex);
}
// -----> Redirection methods
/**
* Redirects regular log messages.
*
* @param level level of the log call
* @param message message
* @since v1-alpha8
*/
public static void redirectCall(@NotNull LogLevel level, @NotNull String message) {
Processor.handle(level, Thread.currentThread().getStackTrace()[3], message);
}
/**
* Redirects crash calls.
*
* @param message message
* @param throwable {@link Throwable} which caused the error
* @param fatal if to terminate the engine
* @since v1-alpha8
*/
public static void redirectCall(@NotNull String message, @Nullable Throwable throwable, boolean fatal) {
CrashHandler.handleCrash(Thread.currentThread().getStackTrace()[3], message, throwable, fatal);
}
// -----> Frontend methods
/**
* Logs a diagnostic message.
*
* @param message message to log
* @since v1-alpha8
*/
public static void diag(@NotNull String message) {
redirectCall(LogLevel.DIAGNOSTIC, message);
}
/**
* Logs a verbose message.
*
* @param message message to log
* @since v1-alpha8
*/
public static void verb(@NotNull String message) {
redirectCall(LogLevel.VERBOSE, message);
}
/**
* Logs a silent warning.
*
* @param message message to log
* @since v1-alpha8
*/
public static void sarn(@NotNull String message) {
redirectCall(LogLevel.SILENT_WARNING, message);
}
/**
* Logs an informational message.
*
* @param message message to log
* @since v1-alpha8
*/
public static void info(@NotNull String message) {
redirectCall(LogLevel.INFORMATIONAL, message);
}
/**
* Logs a warning.
*
* @param message message to log
* @since v1-alpha8
*/
public static void warn(@NotNull String message) {
redirectCall(LogLevel.WARNING, message);
}
/**
* Logs an error.
*
* @param message message to log
* @since v1-alpha8
*/
public static void error(@NotNull String message) {
redirectCall(LogLevel.ERROR, message);
}
/**
* Prints a crash report and optionally crashes the engine.
*
* @param message message to log
* @param throwable {@link Throwable} which caused the crash
* @param fatal terminates the engine if {@code true}
* @since v1-alpha8
*/
public static void crash(@NotNull String message, @NotNull Throwable throwable, boolean fatal) {
redirectCall(message, throwable, fatal);
}
/**
* Prints a crash report and optionally crashes the engine.
*
* @param message message to log
* @param throwable {@link Throwable} which caused the crash
* @since v1-alpha8
*/
public static void crash(@NotNull String message, @NotNull Throwable throwable) {
redirectCall(message, throwable, true);
}
/**
* Prints a crash report and optionally crashes the engine.
*
* @param message message to log
* @param fatal terminates the engine if {@code true}
* @since v1-alpha8
*/
public static void crash(@NotNull String message, boolean fatal) {
redirectCall(message, null, fatal);
}
/**
* Prints a crash report and optionally crashes the engine.
*
* @param message message to log
* @since v1-alpha8
*/
public static void crash(@NotNull String message) {
redirectCall(message, null, true);
}
// -----> Legacy frontend methods
// This improves compatibility with old code
// still using the old logger frontend.
/**
* Prints a diagnostic message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #diag(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void diag(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.DIAGNOSTIC, message);
}
/**
* Prints a verbose message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #verb(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void verb(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.VERBOSE, message);
}
/**
* Prints a silent warning message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #sarn(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void sarn(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.SILENT_WARNING, message);
}
/**
* Prints an informational message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #info(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void info(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.INFORMATIONAL, message);
}
/**
* Prints a warning message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #warn(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void warn(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.WARNING, message);
}
/**
* Prints an error message.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #error(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void error(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(LogLevel.ERROR, message);
}
/**
* Crashes the entire engine.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @param throwable the throwable that caused this crash
* @param handled declares the throwable has handled, not causing the engine to shutdown
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #crash(String, Throwable, boolean)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void crash(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message, @NotNull Throwable throwable, boolean handled) {
redirectCall(message, throwable, !handled);
}
/**
* Crashes the entire engine.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @param throwable the throwable that caused this crash
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #crash(String, Throwable)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void crash(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message, @NotNull Throwable throwable) {
redirectCall(message, throwable, true);
}
/**
* Crashes the entire engine.
*
* @param ignoredIssuerClass class of the issuer
* @param ignoredIssuerOrigin origin of the issuer
* @param ignoredIssuerMetadata metadata about the issuer
* @param message message
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see #crash(String)
* @since v1-alpha0
*/
@Deprecated(forRemoval = true)
public static void crash(@NotNull Class<?> ignoredIssuerClass, @NotNull String ignoredIssuerOrigin, @Nullable String ignoredIssuerMetadata, @NotNull String message) {
redirectCall(message, null, true);
}
}

View file

@ -1,264 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Legacy frontend.
* <p>
* This improves compatibility with old code
* still using the old logger frontend.
*
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see Logger
* @since v1-alpha8
*/
@Getter
@Deprecated(forRemoval = true)
public final class LoggerInstance {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha8
*/
private LoggerInstance() {}
/**
* Prints a diagnostic message.
*
* @param message message
* @since v1-alpha0
*/
public void diag(@NotNull String message) {
Logger.diag(message);
}
/**
* Prints a verbose message.
*
* @param message message
* @since v1-alpha0
*/
public void verb(@NotNull String message) {
Logger.verb(message);
}
/**
* Prints a silent warning message.
*
* @param message message
* @since v1-alpha0
*/
public void sarn(@NotNull String message) {
Logger.sarn(message);
}
/**
* Prints an informational message.
*
* @param message message
* @since v1-alpha0
*/
public void info(@NotNull String message) {
Logger.info(message);
}
/**
* Prints a warning message.
*
* @param message message
* @since v1-alpha0
*/
public void warn(@NotNull String message) {
Logger.warn(message);
}
/**
* Prints an error message.
*
* @param message message
* @since v1-alpha0
*/
public void error(@NotNull String message) {
Logger.error(message);
}
/**
* Crashes the entire engine.
*
* @param message message
* @param throwable throwable that caused the crash
* @param handled declares the throwable has handled
* @since v1-alpha0
*/
public void crash(@NotNull String message, @NotNull Throwable throwable, boolean handled) {
Logger.crash(message, throwable, !handled);
}
/**
* Crashes the entire engine.
*
* @param message message
* @param throwable throwable that caused the crash
* @since v1-alpha0
*/
public void crash(@NotNull String message, @NotNull Throwable throwable) {
Logger.crash(message, throwable);
}
/**
* Crashes the entire engine.
*
* @param message message
* @since v1-alpha0
*/
public void crash(@NotNull String message) {
Logger.crash(message);
}
/**
* Provides an API for building {@link LoggerInstance}s more easily.
*
* @deprecated The old logging system has been deprecated and replaced by a new one
* @see Logger
* @since v1-alpha8
*/
@Deprecated(forRemoval = true)
@SuppressWarnings({ "unused" })
public static final class Builder {
/**
* Contains the class of the issuer.
*
* @since v1-alpha8
*/
private @Nullable Class<?> clazz = null;
/**
* Contains the origin of the issuer.
*
* @since v1-alpha8
*/
private @Nullable String origin = null;
/**
* Contains metadata about the issuer.
*
* @since v1-alpha8
*/
private @Nullable String metadata = null;
/**
* Constructs this class.
*
* @since v1-alpha2
*/
public Builder() {}
/**
* Builds a new {@link LoggerInstance} instance.
*
* @return new {@link LoggerInstance} instance
* @throws IllegalStateException if {@link #clazz} is unset
* @since v1-alpha2
*/
public LoggerInstance build() throws IllegalStateException {
// Check for required fields
if (clazz == null)
throw new IllegalStateException("The class is unset");
// Set defaults
if (origin == null || origin.isBlank())
origin = "APPLICATION";
if (metadata == null || metadata.isBlank())
metadata = null;
return new LoggerInstance();
}
/**
* Returns the class of the issuer.
*
* @return class of the issuer
* @since v1-alpha2
*/
public @Nullable Class<?> getClazz() {
return clazz;
}
/**
* Returns the origin of the issuer.
*
* @return origin of the issuer
* @since v1-alpha2
*/
public @Nullable String getOrigin() {
return origin;
}
/**
* Returns metadata about the issuer.
*
* @return metadata about the issuer
* @since v1-alpha2
*/
public @Nullable String getMetadata() {
return metadata;
}
/**
* Sets the class of the issuer.
*
* @param clazz new class of the issuer
* @return builder instance
* @since v1-alpha2
*/
public @NotNull Builder setClazz(@Nullable Class<?> clazz) {
this.clazz = clazz;
return this;
}
/**
* Sets the origin of the issuer.
*
* @param origin new origin of the issuer
* @return builder instance
* @since v1-alpha2
*/
public @NotNull Builder setOrigin(@Nullable String origin) {
this.origin = origin;
return this;
}
/**
* Sets the metadata about the issuer.
*
* @param metadata new metadata about the issuer
* @return builder instance
* @since v1-alpha2
*/
public @NotNull Builder setMetadata(@Nullable String metadata) {
this.metadata = metadata;
return this;
}
}
}

View file

@ -1,283 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging;
import de.staropensource.engine.base.Engine;
import de.staropensource.engine.base.type.EngineState;
import de.staropensource.engine.base.type.logging.LogLevel;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
/**
* Contains {@link PrintStream}s for the standard
* output and standard error streams, which redirect
* their input into the engine's logging infrastructure.
*
* @since v1-alpha4
*/
@SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class PrintStreamService {
/**
* Contains the diagnostic stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the diagnostic stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @return diagnostic stream
* @since v1-alpha4
*/
@Getter
private static PrintStream diag = null;
/**
* Contains the verbose stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the verbose stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @return verbose stream
* @since v1-alpha4
*/
@Getter
private static PrintStream verb = null;
/**
* Contains the silent warning stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the silent warning stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @return silent warning stream
* @since v1-alpha4
*/
@Getter
private static PrintStream sarn = null;
/**
* Contains the informational stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the informational stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @return informational stream
* @since v1-alpha4
*/
@Getter
private static PrintStream info = null;
/**
* Contains the warning stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the warning stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @return warning stream
* @since v1-alpha4
*/
@Getter
private static PrintStream warn = null;
/**
* Contains the error stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the error stream.
* Anything sent will be redirected to
* {@link Logger#info(String)}
*
* @return error stream
* @since v1-alpha4
*/
@Getter
private static PrintStream error = null;
/**
* Contains the crash stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @since v1-alpha4
* -- GETTER --
* Returns the crash stream.
* Anything sent will be redirected to
* {@link Logger#error(String)}
*
* @return crash stream
* @since v1-alpha4
*/
@Getter
private static PrintStream crash = null;
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha4
*/
private PrintStreamService() {}
/**
* Initializes all {@link PrintStream}s offered by this class.
* <p>
* Only works during early engine startup.
*
* @since v1-alpha8
*/
public static void initializeStreams() {
if (Engine.getInstance() == null || Engine.getInstance().getState() != EngineState.EARLY_STARTUP)
return;
// Create streams
diag = LogStream.createPrintStream(LogLevel.DIAGNOSTIC);
verb = LogStream.createPrintStream(LogLevel.VERBOSE);
sarn = LogStream.createPrintStream(LogLevel.SILENT_WARNING);
info = LogStream.createPrintStream(LogLevel.INFORMATIONAL);
warn = LogStream.createPrintStream(LogLevel.WARNING);
error = LogStream.createPrintStream(LogLevel.ERROR);
crash = LogStream.createPrintStream(LogLevel.CRASH);
}
/**
* Returns the standard output stream.
*
* @return standard output stream
* @since v1-alpha4
*/
public static @NotNull PrintStream getStdOut() {
return info;
}
/**
* Returns the standard error stream.
*
* @return standard error stream
* @since v1-alpha4
*/
public static @NotNull PrintStream getStdErr() {
return error;
}
/**
* Extends {@link PrintStream} to allow for redirecting log messages.
*
* @since v1-alpha4
*/
private static final class LogStream extends OutputStream {
/**
* Contains the current sequence of characters written.
*
* @since v1-alpha4
*/
private @NotNull StringBuilder sequence = new StringBuilder();
/**
* Contains the {@link LogLevel} to write log messages in.
*
* @since v1-alpha4
*/
private final @NotNull LogLevel level;
/**
* Constructs this class.
*
* @param level level to write log messages in
* @since v1-alpha4
*/
public LogStream(@NotNull LogLevel level) {
this.level = level;
}
/**
* Creates a new {@link LogStream} and returns a {@link PrintStream}
* using the newly created {@link LogStream} instance.
*
* @param level level to write log messages in
* @return {@link PrintStream} using a newly created {@link LogStream} instance
* @since v1-alpha4
*/
public static @NotNull PrintStream createPrintStream(@NotNull LogLevel level) {
//noinspection resource // obvious why
return new LogStream(level).toPrintStream();
}
/**
* Returns a new {@link PrintStream} using this {@link LogStream} instance.
*
* @return {@link PrintStream} using this instance
* @since v1-alpha4
*/
public @NotNull PrintStream toPrintStream() {
return new PrintStream(this, true, StandardCharsets.UTF_8);
}
/** {@inheritDoc} */
@Override
public synchronized void write(int byteChar) {
// Convert to String and append to 'sequence'
sequence.append(new String(new byte[]{ (byte) byteChar }, StandardCharsets.UTF_8));
// Check for newline
if (sequence.indexOf("\n") != -1) {
switch (level) {
case DIAGNOSTIC -> Logger.diag(sequence.toString());
case VERBOSE -> Logger.verb(sequence.toString());
case SILENT_WARNING -> Logger.sarn(sequence.toString());
case INFORMATIONAL -> Logger.info(sequence.toString());
case WARNING -> Logger.warn(sequence.toString());
case ERROR -> Logger.error(sequence.toString());
case CRASH -> Logger.crash(sequence.toString());
}
sequence = new StringBuilder();
}
}
}
}

View file

@ -1,338 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging.backend;
import de.staropensource.engine.base.Engine;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.EngineInternals;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.logging.LogLevel;
import de.staropensource.engine.base.utility.Math;
import de.staropensource.engine.base.utility.Miscellaneous;
import de.staropensource.engine.base.utility.information.EngineInformation;
import de.staropensource.engine.base.utility.information.JvmInformation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static de.staropensource.engine.base.logging.backend.Processor.isFeatureEnabled;
/**
* Handles crashes.
*
* @since v1-alpha8
*/
public final class CrashHandler {
/**
* Contains all random witty comments.
*
* @since v1-alpha8
*/
public static final @NotNull String[] WITTYCOMMENTS = new String[]{
"Who fucked up here?",
"What is it now?",
":neofox_woozy:",
"Oh no!",
"my engine brokey brokey",
"weird",
"Is this a feature?",
"$ git blame",
};
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha8
*/
private CrashHandler() {}
/**
* Handles crash reports.
*
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @param throwable {@link Throwable} which caused the error
* @param fatal if to terminate the engine
* @since v1-alpha8
*/
public static void handleCrash(@NotNull StackTraceElement issuer, @NotNull String message, @Nullable Throwable throwable, boolean fatal) {
StringBuilder output = new StringBuilder();
String outputFinal;
// Header
output
.append("==== sos!engine crash report ====")
.append("\nDear user: The application or game you just used seems to have run into a problem.")
.append("\n Please be so kind and report this crash report to the developers so they can fix the issue.")
.append("\nDear developer: FIX YOUR SHIT. If the engine is at fault here, please report the crash")
.append("\n to StarOpenSource here: https://git.staropensource.de/StarOpenSource/Engine/issues")
.append("\n\n// ")
.append(WITTYCOMMENTS[new Random().nextInt(WITTYCOMMENTS.length)])
.append("\n\n");
// Information about the crash
output
.append("---- Crash Information ----\n")
.append("Issuer: ")
.append(issuer.getClassName())
.append("@")
.append(issuer.getModuleName())
.append("#")
.append(issuer.getMethodName())
.append("~")
.append(issuer.getLineNumber())
.append("\nFatal: ")
.append(fatal);
if (throwable == null)
output
.append("\nCaused by:")
.append("\nNo throwable has been passed.");
else
output
.append("\n")
.append(Miscellaneous.getStackTraceHeader(throwable))
.append("\n")
.append(Miscellaneous.getStackTraceAsString(throwable, true))
.append("\n");
output.append("\nMessage: \n")
.append(message)
.append("\n\n");
// Environment information
output
.append("---- Environment ----")
.append("\nTime and date: ")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.DAY_OF_MONTH), 2))
.append(".")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.MONTH), 2))
.append(".")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.YEAR), 4))
.append(" ")
.append(de.staropensource.engine.base.utility.Math.padNumbers(Calendar.getInstance().get(Calendar.HOUR_OF_DAY), 2))
.append(":")
.append(de.staropensource.engine.base.utility.Math.padNumbers(Calendar.getInstance().get(Calendar.MINUTE), 2))
.append(":")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.SECOND), 2))
.append(" [")
.append(TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT, Locale.US))
.append("]")
.append("\nUNIX Epoch: ")
.append(Math.padNumbers(System.currentTimeMillis(), String.valueOf(Long.MAX_VALUE).length()))
.append("\nOperating system: ")
.append(System.getProperty("os.name"))
.append("\nCPU architecture: ")
.append(System.getProperty("os.arch"))
.append("\nMemory: ")
.append(JvmInformation.getMemoryUsed() / 1024)
.append(" MiB")
.append("/")
.append(JvmInformation.getMemoryLimit() / 1024)
.append(" MiB")
.append(" (stack ")
.append(JvmInformation.getMemoryStack().getUsed() / 1024)
.append(" MiB")
.append("/")
.append(JvmInformation.getMemoryStack().getMax() == -1 ? "" : JvmInformation.getMemoryStack().getMax() / 1024)
.append(" MiB")
.append(", heap ")
.append(JvmInformation.getMemoryHeap().getUsed() / 1024)
.append(" MiB")
.append("/")
.append(JvmInformation.getMemoryHeap().getMax() == -1 ? "" : JvmInformation.getMemoryStack().getMax() / 1024)
.append(" MiB)")
.append("\nJVM: ")
.append(JvmInformation.getImplementationName())
.append(" ")
.append(JvmInformation.getImplementationVersion())
.append(" @ ")
.append(JvmInformation.getJavaVersion())
.append(" by ")
.append(JvmInformation.getImplementationVendor())
.append("\nJVM arguments: ");
for (String argument : JvmInformation.getArguments())
output
.append("\n- '")
.append(argument)
.append("'");
output.append("\n\n");
// Engine
output.append("---- sos!engine ----\n");
if (EngineInformation.getVersioningString() == null)
output.append("EngineInformation is not yet initialized");
else
output
.append("Version: ")
.append(EngineInformation.getVersioningString())
.append("\nCommit: ")
.append(EngineInformation.getGitCommitIdentifierLong())
.append("\nDirty: ")
.append(EngineInformation.isGitDirty());
output.append("\n\n");
// Engine configuration
output.append("---- sos!engine configuration ----\n");
if (EngineConfiguration.getInstance() == null)
output.append("EngineConfiguration is not yet initialized");
else
output
.append("EngineConfiguration#debug='")
.append(EngineConfiguration.getInstance().isDebug())
.append("'\n")
.append("EngineConfiguration#debugEvents='")
.append(EngineConfiguration.getInstance().isDebugEvents())
.append("'\n")
.append("EngineConfiguration#initialPerformSubsystemInitialization='")
.append(EngineConfiguration.getInstance().isInitialPerformSubsystemInitialization())
.append("'\n")
.append("EngineConfiguration#initialIncludeSubsystemClasses='")
.append(EngineConfiguration.getInstance().getInitialIncludeSubsystemClasses())
.append("'\n")
.append("EngineConfiguration#errorShortcodeParser='")
.append(EngineConfiguration.getInstance().isErrorShortcodeParser())
.append("'\n")
.append("EngineConfiguration#optimizeLogging='")
.append(EngineConfiguration.getInstance().isOptimizeLogging())
.append("'\n")
.append("EngineConfiguration#optimizeEvents='")
.append(EngineConfiguration.getInstance().isOptimizeEvents())
.append("'\n")
.append("EngineConfiguration#logLevel='")
.append(EngineConfiguration.getInstance().getLogLevel().name())
.append("'\n")
.append("EngineConfiguration#logSettings='")
.append(EngineConfiguration.getInstance().getLogFeatures())
.append("'\n")
.append("EngineConfiguration#logPollingSpeed='")
.append(EngineConfiguration.getInstance().getLogPollingSpeed())
.append("'\n")
.append("EngineConfiguration#logForceStandardOutput='")
.append(EngineConfiguration.getInstance().isLogForceStandardOutput())
.append("'\n")
.append("EngineConfiguration#hideFullTypePath='")
.append(EngineConfiguration.getInstance().isHideFullTypePath());
output.append("'\n\n");
// System properties
output.append("---- System properties ----");
for (String property : System.getProperties().stringPropertyNames().stream().sorted().toList())
output
.append("\n")
.append(property)
.append("='")
.append(System.getProperties().getProperty(property).replace("\n", "\\n"))
.append("'");
output.append("\n\n");
// Stacktraces of all threads
output.append("---- Stacktraces of all threads ----");
{
Map<Thread, StackTraceElement[]> stacktraces = Thread.getAllStackTraces();
for (Thread thread : stacktraces.keySet())
output
.append("\n")
.append(thread.getName())
.append(" (id=")
.append(thread.threadId())
.append(" priority=")
.append(thread.getPriority())
.append(" group=")
.append(thread.getThreadGroup() == null ? "<unknown>" : thread.getThreadGroup().getName())
.append(" state=")
.append(thread.getState().name())
.append(" daemon=")
.append(thread.isDaemon())
.append("):")
.append("\n")
.append(Miscellaneous.getStackTraceAsString(stacktraces.get(thread), false))
.append("\n");
}
output.append("\n");
// Footer
output
.append("Dear user: The application or game you just used seems to have run into a problem.\n")
.append(" Please be so kind and report this crash report to the developers so they can fix the issue.\n")
.append("Dear developer: FIX YOUR SHIT. If the engine is at fault here, please report the crash\n")
.append(" to StarOpenSource here: https://git.staropensource.de/StarOpenSource/Engine/issues\n")
.append("==== sos!engine crash report ====");
// Formatting
if (isFeatureEnabled("formatting")) {
outputFinal =
"<fg:red><bold>"
+ output
.toString()
.replace("<", "\\<")
+ "<reset>";
} else
outputFinal = output.toString();
// Print
Logger.getLoggingAdapter().print(LogLevel.CRASH, issuer, message, outputFinal);
// Terminate engine
// We do a test on the engine state here
// to prevent bugs and multiple engine shutdowns.
if (fatal)
switch (Engine.getInstance().getState()) {
case UNKNOWN, EARLY_STARTUP, STARTUP -> {
if (EngineInternals.getInstance() == null)
Runtime.getRuntime().exit(69);
else
EngineInternals.getInstance().getShutdownHandler().shutdown((short) 69);
}
case RUNNING -> Engine.getInstance().shutdown(69);
case SHUTDOWN, CRASHED -> {}
}
}
}

View file

@ -1,91 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging.backend;
import org.intellij.lang.annotations.RegExp;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* Responsible for filtering log messages out.
*
* @since v1-alpha8
*/
public final class Filterer {
/**
* Contains a list of all disallowed classes.
*
* @since v1-alpha8
*/
static @NotNull List<@NotNull String> disallowedClasses = new ArrayList<>();
/**
* Contains a list of all disallowed modules.
*
* @since v1-alpha8
*/
static @NotNull List<@NotNull String> disallowedModules = new ArrayList<>();
/**
* Contains a list of all disallowed messages.
*
* @since v1-alpha8
*/
static @NotNull List<@NotNull String> disallowedMessages = new ArrayList<>();
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha8
*/
private Filterer() {}
/**
* Disallows one or multiple classes.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowClass(@RegExp @NotNull String regex) {
disallowedClasses.add(regex);
}
/**
* Disallows one or multiple modules.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowModule(@RegExp @NotNull String regex) {
disallowedModules.add(regex);
}
/**
* Disallows one or multiple messages.
*
* @param regex regex
* @since v1-alpha8
*/
public static void disallowMessage(@RegExp @NotNull String regex) {
disallowedMessages.add(regex);
}
}

View file

@ -1,375 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging.backend;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.implementation.shortcode.EmptyShortcodeParser;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.logging.backend.async.LoggingQueue;
import de.staropensource.engine.base.type.logging.LogLevel;
import de.staropensource.engine.base.utility.Math;
import de.staropensource.engine.base.utility.PlaceholderEngine;
import de.staropensource.engine.base.utility.information.JvmInformation;
import org.jetbrains.annotations.NotNull;
import java.util.Calendar;
/**
* Processes log messages.
*
* @see #handle(LogLevel, StackTraceElement, String)
* @since v1-alpha8
*/
public final class Processor {
/**
* Creates and initializes an instance of this class
*
* @since v1-alpha8
*/
private Processor() {}
/**
* Checks whether the specified feature is enabled.
*
* @param feature feature to check
* @return enabled?
* @since v1-alpha8
*/
public static boolean isFeatureEnabled(@NotNull String feature) {
return EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().getLogFeatures().contains(feature);
}
/**
* Handles incoming log calls and either
* processes them directly or queues them in.
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @since v1-alpha8
*/
public static void handle(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message) {
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isOptimizeLogging())
LoggingQueue.add(level, issuer, message);
else
process(level, issuer, message);
}
/**
* Processes a log call.
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @since v1-alpha8
*/
public static void process(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message) {
StringBuilder output = new StringBuilder();
// Filter out
if (EngineConfiguration.getInstance() == null) {
LogLevel maxLevel = LogLevel.INFORMATIONAL;
try {
maxLevel = LogLevel.valueOf(System.getProperties().getProperty("sosengine.base.logLevel", "informational").toUpperCase());
} catch (IllegalArgumentException ignored) {
Logger.error("The log level '" + System.getProperties().getProperty("sosengine.base.logLevel", "informational") + "' is not valid");
}
if (level.compareTo(maxLevel) < 0)
return;
} else if (level.compareTo(EngineConfiguration.getInstance().getLogLevel()) < 0)
return;
for (String classNameDisallowed : Filterer.disallowedClasses)
if (issuer.getClassName().matches(classNameDisallowed))
return;
for (String moduleNameDisallowed : Filterer.disallowedModules)
if (issuer.getModuleName().matches(moduleNameDisallowed))
return;
for (String messageDisallowed : Filterer.disallowedModules)
if (message.matches(messageDisallowed))
return;
format(output, level);
runtime(output);
if (isFeatureEnabled("date") || isFeatureEnabled("time")) {
output.append("[");
date(output);
if (isFeatureEnabled("date"))
output.append(" ");
time(output);
output.append("] ");
}
output.append("[");
level(output, level);
format(output, level);
output.append(" ");
issuerClass(output, level, issuer);
issuerModule(output, level, issuer);
methodName(output, level, issuer);
lineNumber(output, level, issuer);
output.append("] ");
message(output, message);
format(output, "reset");
// Print
Logger.getLoggingAdapter().print(level, issuer, message, output.toString());
}
// -----> Formatting
/**
* Adds the {@code formatting} feature.
* <p>
* This method will reset and then color the following
* substring in the log level-specific color.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @see #format(StringBuilder, String)
* @since v1-alpha8
*/
private static void format(@NotNull StringBuilder builder, @NotNull LogLevel level) {
format(builder, "reset");
format(builder, switch (level) {
case DIAGNOSTIC, VERBOSE -> "fg:blue";
case SILENT_WARNING, WARNING -> "fg:yellow";
case INFORMATIONAL -> "fg:white";
case ERROR -> "fg:red";
case CRASH -> "you should not see this";
});
}
/**
* Adds the {@code formatting} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @param component formatting component
* @see #format(StringBuilder, LogLevel)
* @since v1-alpha8
*/
private static void format(@NotNull StringBuilder builder, @NotNull String component) {
if (isFeatureEnabled("formatting"))
builder
.append("<")
.append(component)
.append(">");
}
/**
* Adds the {@code formatting} feature.
*
* @param string string to sanitize
* @return sanitized string
* @see #format(StringBuilder, LogLevel)
* @since v1-alpha8
*/
private static @NotNull String sanitizeFormat(@NotNull String string) {
if (isFeatureEnabled("formatting"))
return string.replace("<", "\\<");
else
return string;
}
// -----> Features and components
/**
* Adds the {@code runtime} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @since v1-alpha8
*/
private static void runtime(@NotNull StringBuilder builder) {
if (isFeatureEnabled("runtime"))
builder
.append("[")
.append(JvmInformation.getUptime())
.append("ms")
.append("] ");
}
/**
* Adds the {@code time} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @since v1-alpha8
*/
private static void time(@NotNull StringBuilder builder) {
if (isFeatureEnabled("time"))
builder
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.HOUR_OF_DAY), 2))
.append(":")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.MINUTE), 2))
.append(":")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.SECOND), 2));
}
/**
* Adds the {@code date} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @since v1-alpha8
*/
private static void date(@NotNull StringBuilder builder) {
if (isFeatureEnabled("date"))
builder
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.DAY_OF_MONTH), 2))
.append(".")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.MONTH), 2))
.append(".")
.append(Math.padNumbers(Calendar.getInstance().get(Calendar.YEAR), 4));
}
/**
* Adds the {@code level} component.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @since v1-alpha8
*/
private static void level(@NotNull StringBuilder builder, @NotNull LogLevel level) {
format(builder, "bold");
builder.append(switch (level) {
case DIAGNOSTIC -> "DIAG";
case VERBOSE -> "VERB";
case SILENT_WARNING -> "SARN";
case INFORMATIONAL -> "INFO";
case WARNING -> "WARN";
case ERROR -> "ERR!";
case CRASH -> "CRSH";
});
format(builder, level);
}
/**
* Adds the {@code issuer class} component.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @since v1-alpha8
*/
private static void issuerClass(@NotNull StringBuilder builder, @NotNull LogLevel level, @NotNull StackTraceElement issuer) {
format(builder, "bold");
if (isFeatureEnabled("shortIssuerClass")) {
String[] classNameSplit = issuer.getClassName().split("\\.");
builder.append(classNameSplit[classNameSplit.length - 1]);
} else
builder.append(issuer.getClassName());
format(builder, level);
}
/**
* Adds the {@code moduleName} and {@code moduleVersion} features.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @since v1-alpha8
*/
private static void issuerModule(@NotNull StringBuilder builder, @NotNull LogLevel level, @NotNull StackTraceElement issuer) {
if (isFeatureEnabled("moduleName") && issuer.getModuleName() != null) {
format(builder, "bold");
builder
.append("@")
.append(issuer.getModuleName());
if (isFeatureEnabled("moduleVersion") && issuer.getModuleVersion() != null)
builder
.append("v")
.append(issuer.getModuleVersion());
format(builder, level);
}
}
/**
* Adds the {@code methodName} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @since v1-alpha8
*/
private static void methodName(@NotNull StringBuilder builder, @NotNull LogLevel level, @NotNull StackTraceElement issuer) {
if (isFeatureEnabled("methodName")) {
builder.append("#");
format(builder, "bold");
builder.append(sanitizeFormat(issuer.getMethodName()));
format(builder, level);
}
}
/**
* Adds the {@code lineNumber} feature.
*
* @param builder {@link StringBuilder} instance to append to
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @since v1-alpha8
*/
private static void lineNumber(@NotNull StringBuilder builder, @NotNull LogLevel level, @NotNull StackTraceElement issuer) {
if (isFeatureEnabled("lineNumber")) {
builder.append("~");
format(builder, "bold");
builder.append(issuer.getLineNumber());
format(builder, level);
}
}
/**
* Adds the {@code message} component.
*
* @param builder {@link StringBuilder} instance to append to
* @param message message
* @since v1-alpha8
*/
private static void message(@NotNull StringBuilder builder, @NotNull String message) {
builder.append(sanitizeFormat(handlePlaceholders(
message.replace(
"\n",
"\n" + " ".repeat(new EmptyShortcodeParser(builder.toString(), true).getClean().length())
)
)));
}
// -----> Utility methods
/**
* Uses the {@link PlaceholderEngine} to replace
* all placeholders within a specified string and
* returns it's result. The original string will
* be returned if the {@link PlaceholderEngine}
* is not yet initialized.
*
* @param string string to use
* @return updated string
* @since v1-alpha8
*/
private static @NotNull String handlePlaceholders(@NotNull String string) {
if (PlaceholderEngine.getInstance() == null)
return string;
else
return PlaceholderEngine.getInstance().process(string);
}
}

View file

@ -1,77 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging.backend.async;
import de.staropensource.engine.base.internal.type.QueuedLogCall;
import de.staropensource.engine.base.logging.backend.Processor;
import de.staropensource.engine.base.type.immutable.ImmutableArrayList;
import de.staropensource.engine.base.type.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Handles everything related to the logging queue.
*
* @since v1-alpha8
*/
public final class LoggingQueue {
/**
* Contains the logging queue.
*
* @since v1-alpha8
*/
private static final @NotNull List<@NotNull QueuedLogCall> queue = Collections.synchronizedList(new ArrayList<>());
/**
* Creates and initializes an instance of this class
*
* @since v1-alpha8
*/
private LoggingQueue() {}
/**
* Adds a new entry to the logging queue.
*
* @param level level of the log call
* @param issuer {@link StackTraceElement} of the issuer
* @param message message
* @since v1-alpha8
*/
public static void add(@NotNull LogLevel level, @NotNull StackTraceElement issuer, @NotNull String message) {
queue.add(new QueuedLogCall(level, issuer, message));
}
/**
* Flushes the logging queue.
*
* @since v1-alpha8
*/
public static void flush() {
// Get copy of and clear queue
List<@NotNull QueuedLogCall> queue = new ImmutableArrayList<>(LoggingQueue.queue);
LoggingQueue.queue.clear();
for (QueuedLogCall queuedCall : queue)
Processor.process(queuedCall.level(), queuedCall.issuer(), queuedCall.message());
}
}

View file

@ -1,142 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.logging.backend.async;
import de.staropensource.engine.base.Engine;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.EngineState;
import org.jetbrains.annotations.NotNull;
/**
* Handles the logging thread.
*
* @since v1-alpha8
*/
public final class LoggingThread {
/**
* Contains the logging thread.
*
* @since v1-alpha8
*/
private static Thread thread;
/**
* Contains the code of the logging thread.
*
* @since v1-alpha8
*/
private static final @NotNull Runnable threadCode = () -> {
int pollingSpeed;
while (!(
Thread.currentThread().isInterrupted()
|| !(EngineConfiguration.getInstance() == null || EngineConfiguration.getInstance().isOptimizeLogging())
|| Engine.getInstance().getState() == EngineState.SHUTDOWN
|| Engine.getInstance().getState() == EngineState.CRASHED
)) {
if (EngineConfiguration.getInstance() == null)
pollingSpeed = 5;
else
pollingSpeed = EngineConfiguration.getInstance().getLogPollingSpeed();
// Flush all log messages
LoggingQueue.flush();
// Sleep for whatever has been configured
if (pollingSpeed > 0) {
long sleepDuration = System.currentTimeMillis() + pollingSpeed;
while (System.currentTimeMillis() < sleepDuration)
Thread.onSpinWait();
}
}
};
static {
constructThread();
}
/**
* Creates and initializes an instance of this class
*
* @since v1-alpha8
*/
private LoggingThread() {}
/**
* Constructs the logging thread.
*
* @see #thread
* @since v1-alpha8
*/
private static void constructThread() {
thread = Thread
.ofPlatform()
.daemon()
.name("Logging thread")
.group(Engine.getThreadGroup())
.priority(Thread.MAX_PRIORITY)
.stackSize(10)
.unstarted(threadCode);
}
/**
* (Re-)Starts the logging thread.
*
* @param allowRestart if the logging thread should be restarted if it's stopped
* @since v1-alpha8
*/
public static void startThread(boolean allowRestart) {
if (allowRestart && thread.isAlive()) {
// Executing the restart logic in another thread prevents
// this thread from being fully blocked while still ensuring
// that the logging thread is properly restarted
Thread
.ofVirtual()
.name("Logging thread restart thread")
.start(() -> {
Logger.diag("Restarting the logging thread");
// Interrupt thread
// This let's our thread code know that it should terminate
thread.interrupt();
// Make sure that the logging thread is dead before reconstructing and starting it
while (thread.isAlive())
Thread.onSpinWait();
constructThread();
thread.start();
});
} else
thread.start();
}
/**
* Returns the {@link Thread.State} of the logging thread.
*
* @return logging thread state
* @see Thread.State
* @since v1-alpha8
*/
public static @NotNull Thread.State getState() {
return thread.getState();
}
}

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Everything related to making the logging
* infrastructure asynchronous.
*
* @since v1-alpha8
*/
package de.staropensource.engine.base.logging.backend.async;

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* The engine's logging infrastructure.
*
* @see de.staropensource.engine.base.logging.Logger
* @since v1-alpha0
*/
package de.staropensource.engine.base.logging;

View file

@ -1,86 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.reflection;
import de.staropensource.engine.base.logging.Logger;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Allows getting the classpath as {@link URL}s.
* <p>
* This entire class has been stolen from
* <a href="https://github.com/ronmamo/reflections">the Reflections library</a>.
* All credits to them.
*
* @since v1-alpha2
*/
public final class ClasspathAccess {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha2
*/
private ClasspathAccess() {}
/**
* Returns the classpath as a collection of {@link URL}s.
*
* @return collection of classpath urls
* @since v1-alpha2
*/
public static @NotNull Collection<URL> getClasspathURLs() {
Collection<URL> urls = new ArrayList<>();
String javaClassPath = System.getProperty("java.class.path");
if (javaClassPath != null)
for (String path : javaClassPath.split(File.pathSeparator))
try {
urls.add(new File(path).toURI().toURL());
} catch (Exception exception) {
Logger.crash("Failed converting classpath to URL", exception);
}
return fixURLs(urls);
}
/**
* Fixes slowdowns which {@link URL}s may cause.
* <p>
* Visit <a href="http://michaelscharf.blogspot.co.il/2006/11/javaneturlequals-and-hashcode-make.html">this blog post</a> for more information.
*
* @param urls unfixed urls
* @return fixed urls
* @since v1-alpha2
*/
private static @NotNull Collection<URL> fixURLs(@NotNull Collection<URL> urls) {
Map<String, URL> distinct = new LinkedHashMap<>(urls.size());
for (URL url : urls) {
distinct.put(url.toExternalForm(), url);
}
return distinct.values();
}
}

View file

@ -1,72 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.reflection;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* The class you'd likely want to use for reflection.
*
* @since v1-alpha2
*/
public final class Reflect {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha2
*/
private Reflect() {}
/**
* Reflect on a {@link Class}.
*
* @param clazz class to reflect on
* @return new {@link ReflectionClass}
* @since v1-alpha2
*/
public static @NotNull ReflectionClass reflectOn(@NotNull Class<?> clazz) {
return new ReflectionClass(clazz);
}
/**
* Reflect on a {@link Method}.
*
* @param method method to reflect on
* @return new {@link ReflectionMethod}
* @since v1-alpha2
*/
public static ReflectionMethod reflectOn(@NotNull Method method) {
return new ReflectionMethod(method);
}
/**
* Reflect on a {@link Field}.
*
* @param field field to reflect on
* @return new {@link ReflectionField}
* @since v1-alpha2
*/
public static @NotNull ReflectionField reflectOn(@NotNull Field field) {
return new ReflectionField(field);
}
}

View file

@ -1,202 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.reflection;
import de.staropensource.engine.base.exception.UnexpectedCheckEndException;
import de.staropensource.engine.base.exception.reflection.IncompatibleTypeException;
import de.staropensource.engine.base.exception.reflection.InvalidFieldException;
import de.staropensource.engine.base.exception.reflection.InvalidMethodException;
import de.staropensource.engine.base.type.reflection.ClassType;
import de.staropensource.engine.base.type.reflection.VisibilityModifier;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
/**
* Reflection helper for {@link Class}es.
*
* @param clazz class to reflect on
* @since v1-alpha2
*/
@SuppressWarnings({ "unused" })
public record ReflectionClass(Class<?> clazz) {
/**
* Creates and initializes an instance of this class.
*
* @param clazz class to reflect on
* @since v1-alpha2
*/
public ReflectionClass(@NotNull Class<?> clazz) {
this.clazz = clazz;
}
/**
* Returns the class name.
*
* @return class name
* @since v1-alpha2
*/
public String getName() {
return clazz.getName().replace(getPackage() + ".", "");
}
/**
* Returns the package path.
*
* @return package path
* @since v1-alpha2
*/
public String getPackage() {
return clazz.getPackage().getName();
}
/**
* Returns the full path, including the package and class name.
*
* @return full path
* @since v1-alpha2
*/
public String getPath() {
return clazz.getName();
}
/**
* Returns the type of this class.
*
* @return class type
* @since v1-alpha2
*/
public ClassType getType() {
if (clazz.isLocalClass() || clazz.isMemberClass() || clazz.isAnonymousClass())
return ClassType.CLASS;
else if (clazz.isInterface())
return ClassType.INTERFACE;
else if (clazz.isEnum())
return ClassType.ENUM;
else if (clazz.isRecord())
return ClassType.RECORD;
else {
// Class#isUnnamedClass is in preview, use reflection to invoke method
try {
if ((boolean) clazz.getMethod("isUnnamedClass").invoke(clazz))
return ClassType.CLASS;
} catch (Exception ignored) {
}
}
return ClassType.UNKNOWN;
}
/**
* Returns the class' visibility.
*
* @return class visibility
* @throws UnexpectedCheckEndException if the class is neither public, protected or private (should be impossible)
* @since v1-alpha2
*/
public VisibilityModifier getVisibility() throws UnexpectedCheckEndException {
if (Modifier.isPublic(clazz.getModifiers()))
return VisibilityModifier.PUBLIC;
else if (Modifier.isProtected(clazz.getModifiers()))
return VisibilityModifier.PROTECTED;
else if (Modifier.isPrivate(clazz.getModifiers()))
return VisibilityModifier.PRIVATE;
else
throw new UnexpectedCheckEndException("checking the visibility of a class with modifiers " + clazz.getModifiers());
}
/**
* Checks if the {@code final} modifier is present.
*
* @return presence of the {@code final} modifier
* @since v1-alpha2
*/
public boolean isFinal() throws IncompatibleTypeException {
if (getType() != ClassType.CLASS)
throw new IncompatibleTypeException("isFinal", getType(), new ClassType[]{ ClassType.CLASS });
return Modifier.isFinal(clazz.getModifiers());
}
/**
* Checks if the {@code abstract} modifier is present.
*
* @return presence of the {@code abstract} modifier
* @since v1-alpha2
*/
public boolean isAbstract() throws IncompatibleTypeException {
if (getType() != ClassType.CLASS)
throw new IncompatibleTypeException("isAbstract", getType(), new ClassType[]{ ClassType.CLASS });
return Modifier.isAbstract(clazz.getModifiers());
}
/**
* Returns all annotations this class has.
*
* @return array of all annotations
* @since v1-alpha2
*/
public Annotation @NotNull [] getAnnotations() {
return clazz.getAnnotations();
}
/**
* Returns the specified annotation or {@code null} if not found.
*
* @param annotation class
* @return annotation or {@code null}
* @since v1-alpha2
*/
public Annotation getAnnotation(@NotNull Class<Annotation> annotation) {
return clazz.getAnnotation(annotation);
}
/**
* Returns the specified method.
*
* @param methodName name of the method
* @param methodArguments arguments of the method
* @return new {@link ReflectionMethod} instance
* @throws InvalidMethodException if the method does not exist
* @since v1-alpha2
*/
public ReflectionMethod getMethod(@NotNull String methodName, Class<?>... methodArguments) throws InvalidMethodException {
try {
return new ReflectionMethod(clazz.getDeclaredMethod(methodName, methodArguments));
} catch (NoSuchMethodException exception) {
throw new InvalidMethodException(this, methodName);
}
}
/**
* Returns the specified field.
*
* @param fieldName name of the field
* @return new {@link ReflectionField} instance
* @throws InvalidFieldException if the field does not exist
* @since v1-alpha2
*/
public ReflectionField getField(@NotNull String fieldName) throws InvalidFieldException {
try {
return new ReflectionField(clazz.getField(fieldName));
} catch (NoSuchFieldException exception) {
throw new InvalidFieldException(this, fieldName);
}
}
}

View file

@ -1,367 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.reflection;
import de.staropensource.engine.base.exception.UnexpectedCheckEndException;
import de.staropensource.engine.base.exception.reflection.NoAccessException;
import de.staropensource.engine.base.internal.reflection.ReflectionAccessWidener;
import de.staropensource.engine.base.type.reflection.VisibilityModifier;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* Reflection helper for {@link Field}s.
*
* @since v1-alpha2
*/
@Getter
@SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class ReflectionField {
/**
* Contains a reference to the parent class.
*
* @since v1-alpha2
* -- GETTER --
* Returns a reference to the parent class.
*
* @return parent class reference
* @since v1-alpha2
*/
private final @Nullable Class<?> parentClass;
/**
* Contains a reference to the field to reflect on.
*
* @since v1-alpha2
* -- GETTER --
* Returns a reference to the field to reflect on.
*
* @return field reference
* @since v1-alpha2
*/
private final @NotNull Field field;
/**
* Creates and initializes an instance of this class.
*
* @param field field to reflect on
*/
public ReflectionField(@NotNull Field field) {
parentClass = null;
this.field = field;
}
/**
* Constructs this class.
*
* @param parentClass parent class of field
* @param field field to reflect on
*/
public ReflectionField(@NotNull Class<?> parentClass, @NotNull Field field) {
this.parentClass = parentClass;
this.field = field;
}
/**
* Returns the name of the field.
*
* @return field name
* @since v1-alpha2
*/
public String getName() {
return field.getName();
}
/**
* Returns the field's visibility.
*
* @return field visibility
* @throws UnexpectedCheckEndException if the field is neither public, protected or private (should be impossible)
* @since v1-alpha2
*/
public VisibilityModifier getVisibility() throws UnexpectedCheckEndException {
if (Modifier.isPublic(field.getModifiers()))
return VisibilityModifier.PUBLIC;
else if (Modifier.isProtected(field.getModifiers()))
return VisibilityModifier.PROTECTED;
else if (Modifier.isPrivate(field.getModifiers()))
return VisibilityModifier.PRIVATE;
else
throw new UnexpectedCheckEndException("checking the visibility of a field with modifiers " + field.getModifiers());
}
/**
* Checks if the {@code final} modifier is present.
*
* @return presence of the {@code final} modifier
* @since v1-alpha2
*/
public boolean isFinal() {
return Modifier.isFinal(field.getModifiers());
}
/**
* Checks if the {@code static} modifier is present.
*
* @return presence of the {@code static} modifier
* @since v1-alpha2
*/
public boolean isStatic() {
return Modifier.isStatic(field.getModifiers());
}
/**
* Checks if the {@code transient} modifier is present.
*
* @return presence of the {@code transient} modifier
* @since v1-alpha2
*/
public boolean isTransient() {
return Modifier.isTransient(field.getModifiers());
}
/**
* Checks if the {@code volatile} modifier is present.
*
* @return presence of the {@code volatile} modifier
* @since v1-alpha2
*/
public boolean isVolatile() {
return Modifier.isVolatile(field.getModifiers());
}
/**
* Updates the presence of the {@code final} modifier.
*
* @param newValue new presence of the {@code final} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setFinal(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isFinal() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(field, modifiersField.getInt(field) & ~Modifier.FINAL);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code static} modifier.
*
* @param newValue new presence of the {@code static} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setStatic(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isStatic() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(field, modifiersField.getInt(field) & ~Modifier.STATIC);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code transient} modifier.
*
* @param newValue new presence of the {@code transient} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setTransient(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isTransient() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(field, modifiersField.getInt(field) & ~Modifier.TRANSIENT);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code volatile} modifier.
*
* @param newValue new presence of the {@code volatile} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setVolatile(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isVolatile() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = field.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside field " + field.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(field, modifiersField.getInt(field) & ~Modifier.VOLATILE);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Returns all annotations this field has.
*
* @return array of all annotations
* @since v1-alpha2
*/
public Annotation @NotNull [] getAnnotations() {
return field.getAnnotations();
}
/**
* Returns the specified annotation or {@code null} if not found.
*
* @param annotation class
* @return annotation or {@code null}
* @since v1-alpha2
*/
public Annotation getAnnotation(@NotNull Class<Annotation> annotation) {
return field.getAnnotation(annotation);
}
/**
* Returns the type this field has.
*
* @return field type
* @since v1-alpha2
*/
public Object getType() {
return field.getType();
}
/**
* Returns the generic type this field has.
* <p>
* <a href="https://docs.oracle.com/javase/tutorial/reflect/member/fieldTypes.html">You can read the between {@code getType} and {@code getGenericType} here.</a>
*
* @return field type
* @since v1-alpha2
*/
public Object getGenericType() {
return field.getGenericType();
}
/**
* Updates the field with a new value.
*
* @param newValue new value
* @throws NoAccessException if access to the field has been denied
* @since v1-alpha2
*/
public void setValue(Object newValue) throws NoAccessException {
try {
field.set(parentClass, newValue);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", getName());
}
}
/**
* Updates the field with a new value.
*
* @return field's value
* @throws NoAccessException if access to the field has been denied
* @since v1-alpha2
*/
public Object getValue() throws NoAccessException {
try {
return field.get(parentClass);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", getName());
}
}
}

View file

@ -1,378 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.reflection;
import de.staropensource.engine.base.exception.UnexpectedCheckEndException;
import de.staropensource.engine.base.exception.reflection.InstanceMethodFromStaticContextException;
import de.staropensource.engine.base.exception.reflection.InvalidMethodSignatureException;
import de.staropensource.engine.base.exception.reflection.NoAccessException;
import de.staropensource.engine.base.exception.reflection.StaticInitializerException;
import de.staropensource.engine.base.internal.reflection.ReflectionAccessWidener;
import de.staropensource.engine.base.type.reflection.VisibilityModifier;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Reflection helper for {@link Method}s.
*
* @since v1-alpha2
*/
@Getter
@SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class ReflectionMethod {
/**
* Contains a reference to the parent class.
*
* @since v1-alpha2
* -- GETTER --
* Returns a reference to the parent class.
*
* @return parent class reference
* @since v1-alpha2
*/
private final Class<?> parentClass;
/**
* Contains a reference to the method to reflect on.
*
* @since v1-alpha2
* -- GETTER --
* Returns a reference to the method to reflect on.
*
* @return method reference
* @since v1-alpha2
*/
private final Method method;
/**
* Creates and initializes an instance of this class.
*
* @param method method to reflect on
*/
public ReflectionMethod(@NotNull Method method) {
parentClass = null;
this.method = method;
}
/**
* Creates and initializes an instance of this class.
*
* @param parentClass parent class of method
* @param method method to reflect on
*/
public ReflectionMethod(@NotNull Class<?> parentClass, @NotNull Method method) {
this.parentClass = parentClass;
this.method = method;
}
/**
* Returns the name of the method.
*
* @return method name
* @since v1-alpha2
*/
public String getName() {
return method.getName();
}
/**
* Returns the method's visibility.
*
* @return method visibility
* @throws UnexpectedCheckEndException if the method is neither public, protected or private (should be impossible)
* @since v1-alpha2
*/
public VisibilityModifier getVisibility() throws UnexpectedCheckEndException {
if (Modifier.isPublic(method.getModifiers()))
return VisibilityModifier.PUBLIC;
else if (Modifier.isProtected(method.getModifiers()))
return VisibilityModifier.PROTECTED;
else if (Modifier.isPrivate(method.getModifiers()))
return VisibilityModifier.PRIVATE;
else
throw new UnexpectedCheckEndException("checking the visibility of a method with modifiers " + method.getModifiers());
}
/**
* Checks if the {@code final} modifier is present.
*
* @return presence of the {@code final} modifier
* @since v1-alpha2
*/
public boolean isFinal() {
return Modifier.isFinal(method.getModifiers());
}
/**
* Checks if the {@code static} modifier is present.
*
* @return presence of the {@code static} modifier
* @since v1-alpha2
*/
public boolean isStatic() {
return Modifier.isStatic(method.getModifiers());
}
/**
* Checks if the {@code abstract} modifier is present.
*
* @return presence of the {@code abstract} modifier
* @since v1-alpha2
*/
public boolean isAbstract() {
return Modifier.isAbstract(method.getModifiers());
}
/**
* Checks if the {@code synchronized} modifier is present.
*
* @return presence of the {@code synchronized} modifier
* @since v1-alpha2
*/
public boolean isSynchronized() {
return Modifier.isSynchronized(method.getModifiers());
}
/**
* Updates the presence of the {@code final} modifier.
*
* @param newValue new presence of the {@code final} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setFinal(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isFinal() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(method, modifiersField.getInt(method) & ~Modifier.FINAL);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code static} modifier.
*
* @param newValue new presence of the {@code static} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setStatic(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isStatic() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(method, modifiersField.getInt(method) & ~Modifier.STATIC);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code abstract} modifier.
*
* @param newValue new presence of the {@code abstract} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setAbstract(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isAbstract() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(method, modifiersField.getInt(method) & ~Modifier.ABSTRACT);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Updates the presence of the {@code synchronized} modifier.
*
* @param newValue new presence of the {@code synchronized} modifier
* @throws NoSuchFieldException if the {@code modifiers} field is missing
* @throws NoAccessException if access to the {@code modifiers} field has been denied
* @since v1-alpha2
*/
public void setSynchronized(boolean newValue) throws NoSuchFieldException, NoAccessException {
// Don't do anything if the new value already matches the current value
if (isSynchronized() == newValue)
return;
// Unlock modifications
int modifiedModifiers = ReflectionAccessWidener.unlockModifications(this);
// Get 'modifiers' field
Field modifiersField;
try {
modifiersField = method.getClass().getDeclaredField("modifiers");
} catch (NoSuchFieldException exception) {
throw new NoSuchFieldException("Field \"modifiers\" not present inside method " + method.getName());
}
// Update 'modifiers' field
try {
modifiersField.setInt(method, modifiersField.getInt(method) & ~Modifier.SYNCHRONIZED);
} catch (IllegalAccessException e) {
throw new NoAccessException("field", "modifiers");
}
// Lock modifications
ReflectionAccessWidener.lockModifications(this, modifiedModifiers);
}
/**
* Returns all annotations this method has.
*
* @return array of all annotations
* @since v1-alpha2
*/
public Annotation @NotNull [] getAnnotations() {
return method.getAnnotations();
}
/**
* Returns the specified annotation or {@code null} if not found.
*
* @param <T> annotation class
* @param annotation annotation class
* @return annotation or {@code null}
* @since v1-alpha2
*/
public <T extends Annotation> T getAnnotation(@NotNull Class<T> annotation) {
return method.getAnnotation(annotation);
}
/**
* Returns the method's return type.
*
* @return method return type
* @since v1-alpha2
*/
public @NotNull Class<?> getReturnType() {
return method.getReturnType();
}
/**
* Returns the method's generic return type.
* <p>
* <a href="https://docs.oracle.com/javase/tutorial/reflect/member/fieldTypes.html">You can read the between {@code getReturnType} and {@code getGenericReturnType} here.</a>
*
* @return field type
* @since v1-alpha2
*/
public Object getGenericReturnType() {
return method.getGenericReturnType();
}
/**
* Invokes the method.
*
* @param args arguments to pass
* @return method return value
* @throws NoAccessException if access to the method has been denied
* @throws InvalidMethodSignatureException if the method signature is incorrect
* @throws InvocationTargetException covers exceptions thrown by the method
* @throws InstanceMethodFromStaticContextException when the target method is non-static and called from a static context
* @throws StaticInitializerException when an the static initializer fails
* @since v1-alpha5
*/
public @Nullable Object invoke(Object... args) throws NoAccessException, InvalidMethodSignatureException, InvocationTargetException, InstanceMethodFromStaticContextException, StaticInitializerException {
Object returnValue;
// Allow access to method
ReflectionAccessWidener.allowAccess(method);
// Invoke method
try {
returnValue = method.invoke(parentClass, args);
} catch (IllegalAccessException exception) {
throw new NoAccessException("method", getName());
} catch (IllegalArgumentException exception) {
throw new InvalidMethodSignatureException(getName());
} catch (NullPointerException exception) {
throw new InstanceMethodFromStaticContextException(getName());
} catch (ExceptionInInitializerError exception) {
throw new StaticInitializerException(exception.getCause());
}
// Return return value from method
return returnValue;
}
}

View file

@ -1,27 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Reflection classes, which make reflection
* on classes, methods and fields easy.
*
* @see de.staropensource.engine.base.reflection.Reflect
* @since v1-alpha2
*/
package de.staropensource.engine.base.reflection;

View file

@ -1,301 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type;
import de.staropensource.engine.base.EngineConfiguration;
import de.staropensource.engine.base.utility.Math;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
import java.nio.ByteBuffer;
import java.util.HexFormat;
import java.util.Locale;
/**
* A class dedicated to colors.
* Uses the RGBA format, with conversion methods
* supporting RGB and RGBA &amp; RGB encoded in
* bytes or hex.
*
* @since v1-alpha6
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Color {
/**
* Contains the red color value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the red color value.
*
* @return red color value
* @since v1-alpha6
* -- SETTER --
* Sets the red color value.
*
* @param red new red color value
* @since v1-alpha6
*/
private @Range(from = 0, to = 255) int red;
/**
* Contains the green color value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the green color value.
*
* @return green color value
* @since v1-alpha6
* -- SETTER --
* Sets the green color value.
*
* @param green new green color value
* @since v1-alpha6
*/
private @Range(from = 0, to = 255) int green;
/**
* Contains the blue color value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the blue color value.
*
* @return blue color value
* @since v1-alpha6
* -- SETTER --
* Sets the blue color value.
*
* @param blue new blue color value
* @since v1-alpha6
*/
private @Range(from = 0, to = 255) int blue;
/**
* Contains the alpha channel value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the alpha channel value.
*
* @return alpha channel value
* @since v1-alpha6
* -- SETTER --
* Sets the alpha channel value.
*
* @param alpha new alpha channel value
* @since v1-alpha6
*/
private @Range(from = 0, to = 255) int alpha;
/**
* Creates and initializes an instance of this class.
*
* @param red red color value
* @param green green color value
* @param blue blue color value
* @param alpha alpha channel value
* @since v1-alpha6
*/
private Color(int red, int green, int blue, int alpha) {
this.red = Math.boundNumber(0, 255, red);
this.green = Math.boundNumber(0, 255, green);
this.blue = Math.boundNumber(0, 255, blue);
this.alpha = Math.boundNumber(0, 255, alpha);
}
/**
* Converts the a set of numbers in
* the RGBA format into a new instance.
*
* @param red red color value
* @param blue blue color value
* @param green green color value
* @param alpha alpha color value
* @return new {@link Color} instance
* @since v1-alpha6
*/
public static @NotNull Color fromRGBA(@Range(from = 0, to = 255) int red, @Range(from = 0, to = 255) int green,
@Range(from = 0, to = 255) int blue, @Range(from = 0, to = 255) int alpha) {
return new Color(red, green, blue, alpha);
}
/**
* Converts the an array of numbers in
* the RGBA format into a new instance.
*
* @param intArray integer array
* @return new {@link Color} instance
* @throws IndexOutOfBoundsException if the array contains more or less than four integers
* @since v1-alpha6
*/
public static @NotNull Color fromRGBA(int @NotNull [] intArray) {
if (intArray.length != 4)
throw new StringIndexOutOfBoundsException("Can't contains more or less than four integers");
return new Color(intArray[0], intArray[1], intArray[2], intArray[3]);
}
/**
* Converts the a set of numbers in
* the RGB format into a new instance.
*
* @param red red color value
* @param blue blue color value
* @param green green color value
* @return new {@link Color} instance
* @since v1-alpha6
*/
public static @NotNull Color fromRGB(@Range(from = 0, to = 255) int red, @Range(from = 0, to = 255) int green,
@Range(from = 0, to = 255) int blue) {
return new Color(red, green, blue, 255);
}
/**
* Converts the an array of numbers in
* the RGBA format into a new instance.
*
* @param intArray integer array
* @return new {@link Color} instance
* @throws IndexOutOfBoundsException if the array contains more or less than four integers
* @since v1-alpha6
*/
public static @NotNull Color fromRGB(int @NotNull [] intArray) {
if (intArray.length != 3)
throw new StringIndexOutOfBoundsException("Can't contains more or less than four integers");
return new Color(intArray[0], intArray[1], intArray[2], 255);
}
/**
* Converts an array of bytes into a new instance.
*
* @param bytes byte array
* @return new {@link Color} instance
* @throws IndexOutOfBoundsException if the array contains less than three or more than four bytes
* @since v1-alpha6
*/
public static @NotNull Color fromBytes(byte @NotNull [] bytes) throws IndexOutOfBoundsException {
if (bytes.length == 3)
return new Color(bytes[0] & 0xFF, bytes[1] & 0xFF, bytes[2] & 0xFF, 255);
else if (bytes.length == 4)
return new Color(bytes[0] & 0xFF, bytes[1] & 0xFF, bytes[2] & 0xFF, bytes[3] & 0xFF);
else
throw new StringIndexOutOfBoundsException("Can't contain less than three or more than four bytes");
}
/**
* Converts a hex string into a new instance.
*
* @param hexString hex string
* @return new {@link Color} instance
* @throws IndexOutOfBoundsException if the string contains less than three or more than four bytes
* @since v1-alpha6
*/
public static @NotNull Color fromHex(@NotNull String hexString) throws IndexOutOfBoundsException {
return fromBytes(HexFormat.of().parseHex(hexString));
}
/**
* Creates an identical copy of this instance.
*
* @return identical copy
* @since v1-alpha6
*/
@SneakyThrows
public @NotNull Color clone() {
return (Color) super.clone();
}
/**
* Returns a string representation of this instance.
*
* @return string representation
* @since v1-alpha6
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(r=" + red + " g=" + green + " b=" + blue + " a=" + alpha + ")";
}
/**
* Converts the colors represented by
* this instance into an integer array
* in the RGBA format.
*
* @return {@code int} array with RGBA values
* @since v1-alpha6
*/
public int @NotNull [] toRGBA() {
return new int[]{ red, green, blue, alpha };
}
/**
* Converts the colors represented by
* this instance into an integer array
* in the RGB format.
*
* @return {@code int} array with RGB values
* @since v1-alpha6
*/
public int @NotNull [] toRGB() {
return new int[]{ red, green, blue };
}
/**
* Converts the colors represented by
* this instance into a byte array.
*
* @param includeAlpha whether to include alpha or not
* @return RGBA or RGB format as a byte array
* @since v1-alpha6
*/
public byte @NotNull [] toBytes(boolean includeAlpha) {
ByteBuffer buffer = ByteBuffer.allocate(includeAlpha ? 4 : 3);
buffer
.put((byte) red)
.put((byte) green)
.put((byte) blue);
if (includeAlpha)
buffer.put((byte) alpha);
return buffer.array();
}
/**
* Converts the colors represented by
* this instance into the hex format.
*
* @param includeAlpha whether to include alpha or not
* @return RGBA or RGB format as a hex string
* @since v1-alpha6
*/
public @NotNull String toHex(boolean includeAlpha) {
return HexFormat.of().formatHex(toBytes(includeAlpha)).toUpperCase(Locale.ROOT);
}
}

View file

@ -1,349 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type;
import de.staropensource.engine.base.implementable.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.utility.DependencyResolver;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
/**
* Represents a dependency vector, used by {@link DependencyResolver}.
*
* @since v1-alpha1
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration" })
public class DependencyVector {
/**
* Contains the identifier of this vector.
*
* @since v1-alpha1
* -- GETTER --
* Returns the vector identifier.
*
* @return vector identifier
* @since v1-alpha1
*/
protected @NotNull String identifier;
/**
* Contains which versioning system this vector uses.
*
* @since v1-alpha1
* -- GETTER --
* Returns the versioning system this vector uses.
*
* @return versioning system in use
* @since v1-alpha1
*/
protected @NotNull Class<? extends VersioningSystem> versioningSystem;
/**
* Contains the version of this vector.
*
* @since v1-alpha1
* -- GETTER --
* Returns the vector version.
*
* @return vector version
* @since v1-alpha1
*/
protected @NotNull String version;
/**
* Contains a set of all identifiers and their versions this vector depends on.
*
* @since v1-alpha4
* -- GETTER --
* Contains a set of all identifiers and their versions this vector depends on.
*
* @return dependencies
* @since v1-alpha1
*/
protected @NotNull Set<@NotNull String> dependencies;
/**
* Contains a set of all identifiers and their versions this vector provides.
*
* @since v1-alpha4
* -- GETTER --
* Contains a set of all identifiers and their versions this vector provides.
*
* @return provided vectors
* @since v1-alpha4
*/
protected @NotNull Set<@NotNull String> provides;
/**
* Creates and initializes an instance of this class.
*
* @param identifier identifier (name for example)
* @param versioningSystem versioning system to use
* @param version version
* @param dependencies dependencies in the usual format ({@code dependencyA}, {@code dependencyB=5.1}, {@code dependencyC>3.1}, {@code dependencyD<6.1}, {@code dependencyE>5.3<5.4})
* @param provides vectors this vector provides, in the usual format ({@code identifier=version})
* @since v1-alpha4
*/
protected DependencyVector(@NotNull String identifier, @NotNull Class<? extends VersioningSystem> versioningSystem, @NotNull String version, @NotNull Set<@NotNull String> dependencies, @NotNull Set<@NotNull String> provides) {
this.identifier = identifier;
this.versioningSystem = versioningSystem;
this.version = version;
this.dependencies = dependencies;
this.provides = provides;
}
/**
* Provides an API for building {@link DependencyVector}s more easily.
*
* @since v1-alpha4
*/
@SuppressWarnings({ "unused" })
public static class Builder {
/**
* Contains the identifier of the new vector.
*
* @see DependencyVector#identifier
* @since v1-alpha4
*/
private @Nullable String identifier;
/**
* Contains which versioning system the new vector should use.
*
* @see DependencyVector#versioningSystem
* @since v1-alpha4
*/
private @Nullable Class<? extends VersioningSystem> versioningSystem;
/**
* Contains the version of the new vector.
*
* @see DependencyVector#version
* @since v1-alpha4
*/
private @Nullable String version;
/**
* Contains a set of all identifiers and their versions the new vector should depend on.
*
* @see DependencyVector#dependencies
* @since v1-alpha4
*/
private @Nullable Set<@NotNull String> dependencies;
/**
* Contains a set of all identifiers and their versions the new vector should provide.
*
* @see DependencyVector#provides
* @since v1-alpha4
*/
private @Nullable Set<@NotNull String> provides;
/**
* Constructs this class.
*
* @since v1-alpha4
*/
public Builder() {}
/**
* Builds a new {@link DependencyVector} instance.
*
* @return new {@link DependencyVector} instance
* @throws IllegalStateException if {@link #identifier}, {@link #versioningSystem} or {@link #version} is unset or the version string is invalid
* @since v1-alpha4
*/
public @NotNull DependencyVector build() throws IllegalStateException {
// Check for required fields
checkRequiredFields();
// Set defaults
setDefaults();
//noinspection DataFlowIssue // IDE is dumb
return new DependencyVector(identifier, versioningSystem, version, dependencies, provides);
}
/**
* Checks for required fields.
*
* @since v1-alpha4
*/
protected void checkRequiredFields() throws IllegalStateException {
if (identifier == null || identifier.isBlank())
throw new IllegalStateException("The identifier is unset");
if (versioningSystem == null)
throw new IllegalStateException("The versioning system is unset");
if (version == null || version.isBlank())
throw new IllegalStateException("The version is unset");
// Check if version string is valid
try {
versioningSystem.getDeclaredConstructor(String.class).newInstance(version);
} catch (InvocationTargetException exception) {
if (exception.getTargetException().getClass() == InvalidVersionStringException.class)
throw new IllegalStateException("The version string is invalid: " + exception.getTargetException().getMessage());
else
throw new IllegalStateException("Version string validation failed: Constructor threw " + exception.getTargetException().getClass().getName() + ": " + exception.getTargetException().getMessage());
} catch (Exception exception) {
throw new IllegalStateException("Version string validation failed: Threw " + exception.getClass().getName() + ": " + exception.getMessage());
}
}
/**
* Allows extenders to set defaults.
*
* @since v1-alpha4
*/
protected void setDefaults() {
if (dependencies == null)
dependencies = new HashSet<>();
if (provides == null)
provides = new HashSet<>();
}
/**
* Returns the identifier of the new vector.
*
* @return identifier
* @see DependencyVector#identifier
* @since v1-alpha4
*/
public final @Nullable String getIdentifier() {
return identifier;
}
/**
* Returns the versioning system the new vector should use.
*
* @return versioning system to use
* @see DependencyVector#versioningSystem
* @since v1-alpha4
*/
public final @Nullable Class<? extends VersioningSystem> getVersioningSystem() {
return versioningSystem;
}
/**
* Returns the version of the new vector.
*
* @return vector version
* @see DependencyVector#version
* @since v1-alpha4
*/
public final @Nullable String getVersion() {
return version;
}
/**
* Contains a set of all identifiers and their versions the new vector should depend on.
*
* @return dependencies
* @see DependencyVector#dependencies
* @since v1-alpha4
*/
public final @Nullable Set<@NotNull String> getDependencies() {
return dependencies;
}
/**
* Contains a set of all identifiers and their versions the new vector should provide.
*
* @return provided vectors
* @see DependencyVector#provides
* @since v1-alpha4
*/
public final @Nullable Set<@NotNull String> getProvides() {
return provides;
}
/**
* Sets the identifier of the new vector.
*
* @param identifier new identifier
* @return builder instance
* @see DependencyVector#identifier
* @since v1-alpha4
*/
public final @NotNull DependencyVector.Builder setIdentifier(@Nullable String identifier) {
this.identifier = identifier;
return this;
}
/**
* Sets the versioning system the new vector should use.
*
* @param versioningSystem versioning system to use
* @return builder instance
* @see DependencyVector#versioningSystem
* @since v1-alpha4
*/
public final @NotNull DependencyVector.Builder setVersioningSystem(@Nullable Class<? extends VersioningSystem> versioningSystem) {
this.versioningSystem = versioningSystem;
return this;
}
/**
* Sets the version of the new vector.
*
* @param version vector version
* @return builder instance
* @see DependencyVector#version
* @since v1-alpha4
*/
public final @NotNull DependencyVector.Builder setVersion(@Nullable String version) {
this.version = version;
return this;
}
/**
* Sets a set of all identifiers and their versions the new vector should depend on.
*
* @param dependencies dependencies
* @return builder instance
* @see DependencyVector#dependencies
* @since v1-alpha4
*/
public final @NotNull DependencyVector.Builder setDependencies(@Nullable Set<@NotNull String> dependencies) {
this.dependencies = dependencies;
return this;
}
/**
* Sets a set of all identifiers and their versions the new vector should provide.
*
* @param provides provided vectors
* @return builder instance
* @see DependencyVector#provides
* @since v1-alpha4
*/
public final @NotNull DependencyVector.Builder setProvides(@Nullable Set<@NotNull String> provides) {
this.provides = provides;
return this;
}
}
}

View file

@ -1,77 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type;
/**
* Determines in which state the engine is currently in.
*
* @since v1-alpha2
*/
public enum EngineState {
/**
* Indicates that the state of the engine is
* currently unknown. The engine is most likely
* not initialized yet.
*
* @since v1-alpha2
*/
UNKNOWN,
/**
* Indicates that the engine is largely
* uninitialized and unsafe to use.
*
* @since v1-alpha8
*/
EARLY_STARTUP,
/**
* Indicates that the core engine has fully
* initialized, except for all subsystems.
*
* @since v1-alpha8
*/
STARTUP,
/**
* Indicates that the engine is running
* and operating normally.
*
* @since v1-alpha2
*/
RUNNING,
/**
* Indicates that the engine or the
* application has crashed.
*
* @since v1-alpha2
*/
CRASHED,
/**
* Indicates that the engine is shutting
* down. The engine is unusable in this
* state and should not be used.
*
* @since v1-alpha8
*/
SHUTDOWN,
}

View file

@ -1,145 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type;
import de.staropensource.engine.base.EngineInternals;
import de.staropensource.engine.base.implementable.Event;
import de.staropensource.engine.base.implementable.ShutdownHandler;
import org.jetbrains.annotations.NotNull;
/**
* Specifies multiple areas of internal engine access.
* Used for restricting access of internals.
*
* @see EngineInternals#restrictAccess(InternalAccessArea)
* @since v1-alpha4
*/
public enum InternalAccessArea {
/**
* Refers to all areas.
*
* @since v1-alpha4
*/
ALL,
/**
* Refers to all write-only areas.
*
* @since v1-alpha4
*/
ALL_WRITE,
/**
* Refers to all read-only areas.
*
* @since v1-alpha4
*/
ALL_READ,
/**
* Refers to all essential read-only areas.
* <p>
* Essential read-only areas are IIAs which are
* very important and should not be restricted.
*
* @since v1-alpha5
*/
ALL_READ_ESSENTIAL,
/**
* Refers to the toggling of the JVM shutdown hook, which
* prevents JVM shutdowns without the engine first shutting down.
*
* @since v1-alpha4
*/
SAFETY_SHUTDOWN_HOOK_UPDATE,
/**
* Refers to the getting of the engine's shutdown handler.
* The {@link ShutdownHandler} handles the shutdown sequence
* after the engine has been shut down.
*
* @since v1-alpha4
*/
SHUTDOWN_HANDLER_GET,
/**
* Refers to the updating of the engine's shutdown handler.
* The {@link ShutdownHandler} handles the shutdown sequence
* after the engine has been shut down.
*
* @since v1-alpha4
*/
SHUTDOWN_HANDLER_UPDATE,
/**
* Refers to the getting of the flag controlling whether
* automatic {@link Event} classpath searching should be performed.
*
* @since v1-alpha5
*/
REFLECTIVE_CLASSPATH_SCANNING_GET,
/**
* Refers to the overriding of the flag controlling whether
* automatic {@link Event} classpath searching should be performed.
*
* @since v1-alpha5
*/
REFLECTIVE_CLASSPATH_SCANNING_OVERRIDE;
/**
* Returns all read-only areas.
*
* @return array containing all read-only areas
* @since v1-alpha4
*/
public static @NotNull InternalAccessArea @NotNull [] valuesReadOnly() {
return new InternalAccessArea[]{
SHUTDOWN_HANDLER_GET,
};
}
/**
* Returns all essential read-only areas.
*
* @return array containing all essential read-only areas
* @since v1-alpha5
*/
public static @NotNull InternalAccessArea @NotNull [] valuesEssentialReadOnly() {
return new InternalAccessArea[]{
REFLECTIVE_CLASSPATH_SCANNING_GET,
};
}
/**
* Returns all write-only areas.
*
* @return array containing all write-only areas
* @since v1-alpha4
*/
public static @NotNull InternalAccessArea @NotNull [] valuesWriteOnly() {
return new InternalAccessArea[]{
SAFETY_SHUTDOWN_HOOK_UPDATE,
SHUTDOWN_HANDLER_UPDATE,
REFLECTIVE_CLASSPATH_SCANNING_OVERRIDE,
};
}
}

View file

@ -1,79 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type;
import de.staropensource.engine.base.exception.TristateConversionException;
import org.jetbrains.annotations.NotNull;
/**
* Just a {@link Boolean}, but it can be {@link #UNSET}.
*
* @since v1-alpha1
*/
public enum Tristate {
/**
* An unset tristate.
*
* @since v1-alpha1
*/
UNSET,
/**
* A true tristate.
*
* @since v1-alpha1
*/
TRUE,
/**
* A false tristate.
*
* @since v1-alpha1
*/
FALSE;
/**
* Converts the {@link Boolean} into a {@link Tristate}.
*
* @param bool boolean to convert
* @return tristated boolean
* @since v1-alpha5
*/
public static @NotNull Tristate toTristate(boolean bool) {
if (bool) return Tristate.TRUE;
else return Tristate.FALSE;
}
/**
* Converts the {@link Tristate} into a {@link Boolean}.
* Make sure to check for {@link #UNSET} first.
*
* @return booleanized {@link Tristate}
* @throws TristateConversionException when encountering {@link #UNSET}
* @since v1-alpha2
*/
public boolean toBoolean() {
return switch (this) {
case UNSET -> throw new TristateConversionException();
case TRUE -> true;
case FALSE -> false;
};
}
}

View file

@ -1,134 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.immutable;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
/**
* An unmodifiable {@link HashSet}.
*
* @param <E> contained type
* @since v1-alpha2
*/
@SuppressWarnings({ "unused" })
public class ImmutableHashSet<E> extends HashSet<E> {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha2
*/
public ImmutableHashSet() {}
/**
* Creates and initializes an instance of this class.
* Converts a {@link Set} into an {@link ImmutableHashSet}.
*
* @param set {@link Set} to convert
* @since v1-alpha2
*/
public ImmutableHashSet(@NotNull Set<E> set) {
super.addAll(set);
}
/**
* Converts the {@link ImmutableHashSet} into a regular {@link HashSet}.
*
* @return mutable {@link HashSet}
* @since v1-alpha2
*/
public @NotNull HashSet<E> toMutable() {
return new HashSet<>(this);
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean add(Object o) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean addAll(@NotNull Collection collection) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean retainAll(@NotNull Collection collection) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean removeIf(Predicate filter) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public void clear() {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException always, array list is immutable
*/
@Override
public boolean removeAll(@NotNull Collection collection) {
throw new UnsupportedOperationException("This method cannot be executed on an ImmutableHashSet");
}
}

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Data types related to logging.
*
* @see de.staropensource.engine.base.logging
* @since v1-alpha1
*/
package de.staropensource.engine.base.type.logging;

View file

@ -1,73 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.reflection;
import de.staropensource.engine.base.exception.UnexpectedCheckEndException;
import java.lang.reflect.Modifier;
/**
* Contains which visibility a class, method or field has.
*
* @since v1-alpha2
*/
public enum VisibilityModifier {
/**
* Marks the class, method or field as public.
*
* @since v1-alpha2
*/
PUBLIC,
/**
* Marks the class, method or field as protected.
*
* @since v1-alpha2
*/
PROTECTED,
/**
* Marks the class, method or field as private.
*
* @since v1-alpha2
*/
PRIVATE;
/**
* Converts the visibility into a usable modifier bit.
*
* @return int
* @since v1-alpha2
*/
public int getModifier() {
switch (this) {
case PUBLIC -> {
return Modifier.PUBLIC;
}
case PROTECTED -> {
return Modifier.PROTECTED;
}
case PRIVATE -> {
return Modifier.PRIVATE;
}
case null, default -> throw new UnexpectedCheckEndException("converting the visibility into a modifier");
}
}
}

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Data types related to reflection.
*
* @see de.staropensource.engine.base.reflection
* @since v1-alpha2
*/
package de.staropensource.engine.base.type.reflection;

View file

@ -1,107 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.vector;
import de.staropensource.engine.base.EngineConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
/**
* Represents a 2D double Vector.
*
* @since v1-alpha0
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Vec2d {
/**
* The X axis value.
*
* @since v1-alpha0
* -- GETTER --
* Returns the X axis value.
*
* @return X axis value
* @since v1-alpha0
* -- SETTER --
* Sets the X axis value.
*
* @param x X axis value
* @since v1-alpha0
*/
private double x;
/**
* The Y axis value.
*
* @since v1-alpha0
* -- GETTER --
* Returns the Y axis value.
*
* @return Y axis value
* @since v1-alpha0
* -- SETTER --
* Sets the Y axis value.
*
* @param y Y axis value
* @since v1-alpha0
*/
private double y;
/**
* Creates and initializes a new 2D double vector.
*
* @param x X axis value
* @param y Y axis value
* @since v1-alpha0
*/
public Vec2d(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Creates an identical copy of this vector.
*
* @return identical copy
* @since v1-alpha2
*/
@SneakyThrows
public @NotNull Vec2d clone() {
return (Vec2d) super.clone();
}
/**
* Returns a string representation of this vector.
*
* @return string representation
* @since v1-alpha2
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(x=" + x + " y=" + y + ")";
}
}

View file

@ -1,126 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.vector;
import de.staropensource.engine.base.EngineConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
/**
* Represents a 3D double Vector.
*
* @since v1-alpha0
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Vec3d {
/**
* The X axis value.
*
* @since v1-alpha0
* -- GETTER --
* Returns the X axis value.
*
* @return X axis value
* @since v1-alpha0
* -- SETTER --
* Sets the X axis value.
*
* @param x X axis value
* @since v1-alpha0
*/
private double x;
/**
* The Y axis value.
*
* @since v1-alpha0
* -- GETTER --
* Returns the Y axis value.
*
* @return Y axis value
* @since v1-alpha0
* -- SETTER --
* Sets the Y axis value.
*
* @param y Y axis value
* @since v1-alpha0
*/
private double y;
/**
* The Z axis value.
*
* @since v1-alpha0
* -- GETTER --
* Returns the Z axis value.
*
* @return Z axis value
* @since v1-alpha0
* -- SETTER --
* Sets the Z axis value.
*
* @param z Z axis value
* @since v1-alpha0
*/
private double z;
/**
* Creates and initializes a new 3D double vector.
*
* @param x X axis value
* @param y Y axis value
* @param z Z axis value
* @since v1-alpha0
*/
public Vec3d(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Creates an identical copy of this vector.
*
* @return identical copy
* @since v1-alpha2
*/
@SneakyThrows
public @NotNull Vec3d clone() {
return (Vec3d) super.clone();
}
/**
* Returns a string representation of this vector.
*
* @return string representation
* @since v1-alpha2
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(x=" + x + " y=" + y + " z=" + z + ")";
}
}

View file

@ -1,145 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.vector;
import de.staropensource.engine.base.EngineConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
/**
* Represents a 4D double Vector.
*
* @since v1-alpha6
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Vec4d {
/**
* The X axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the X axis value.
*
* @return X axis value
* @since v1-alpha6
* -- SETTER --
* Sets the X axis value.
*
* @param x X axis value
* @since v1-alpha6
*/
private double x;
/**
* The Y axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Y axis value.
*
* @return Y axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Y axis value.
*
* @param y Y axis value
* @since v1-alpha6
*/
private double y;
/**
* The Z axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Z axis value.
*
* @return Z axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Z axis value.
*
* @param z Z axis value
* @since v1-alpha6
*/
private double z;
/**
* The W axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the W axis value.
*
* @return W axis value
* @since v1-alpha6
* -- SETTER --
* Sets the W axis value.
*
* @param w W axis value
* @since v1-alpha6
*/
private double w;
/**
* Creates and initializes a new 4D double vector.
*
* @param x X axis value
* @param y Y axis value
* @param z Z axis value
* @param w W axis value
* @since v1-alpha6
*/
public Vec4d(double x, double y, double z, double w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Creates an identical copy of this vector.
*
* @return identical copy
* @since v1-alpha6
*/
@SneakyThrows
public @NotNull Vec4d clone() {
return (Vec4d) super.clone();
}
/**
* Returns a string representation of this vector.
*
* @return string representation
* @since v1-alpha6
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(x=" + x + " y=" + y + " z=" + z + " w=" + w + ")";
}
}

View file

@ -1,145 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.vector;
import de.staropensource.engine.base.EngineConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
/**
* Represents a 4D float Vector.
*
* @since v1-alpha6
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Vec4f {
/**
* The X axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the X axis value.
*
* @return X axis value
* @since v1-alpha6
* -- SETTER --
* Sets the X axis value.
*
* @param x X axis value
* @since v1-alpha6
*/
private float x;
/**
* The Y axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Y axis value.
*
* @return Y axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Y axis value.
*
* @param y Y axis value
* @since v1-alpha6
*/
private float y;
/**
* The Z axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Z axis value.
*
* @return Z axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Z axis value.
*
* @param z Z axis value
* @since v1-alpha6
*/
private float z;
/**
* The W axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the W axis value.
*
* @return W axis value
* @since v1-alpha6
* -- SETTER --
* Sets the W axis value.
*
* @param w W axis value
* @since v1-alpha6
*/
private float w;
/**
* Creates and initializes a new 4D float vector.
*
* @param x X axis value
* @param y Y axis value
* @param z Z axis value
* @param w W axis value
* @since v1-alpha6
*/
public Vec4f(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Creates an identical copy of this vector.
*
* @return identical copy
* @since v1-alpha6
*/
@SneakyThrows
public @NotNull Vec4f clone() {
return (Vec4f) super.clone();
}
/**
* Returns a string representation of this vector.
*
* @return string representation
* @since v1-alpha6
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(x=" + x + " y=" + y + " z=" + z + " w=" + w + ")";
}
}

View file

@ -1,145 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.type.vector;
import de.staropensource.engine.base.EngineConfiguration;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
/**
* Represents a 4D integer Vector.
*
* @since v1-alpha6
*/
@Getter
@Setter
@SuppressWarnings({ "JavadocDeclaration" })
public final class Vec4i {
/**
* The X axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the X axis value.
*
* @return X axis value
* @since v1-alpha6
* -- SETTER --
* Sets the X axis value.
*
* @param x X axis value
* @since v1-alpha6
*/
private int x;
/**
* The Y axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Y axis value.
*
* @return Y axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Y axis value.
*
* @param y Y axis value
* @since v1-alpha6
*/
private int y;
/**
* The Z axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the Z axis value.
*
* @return Z axis value
* @since v1-alpha6
* -- SETTER --
* Sets the Z axis value.
*
* @param z Z axis value
* @since v1-alpha6
*/
private int z;
/**
* The W axis value.
*
* @since v1-alpha6
* -- GETTER --
* Returns the W axis value.
*
* @return W axis value
* @since v1-alpha6
* -- SETTER --
* Sets the W axis value.
*
* @param w W axis value
* @since v1-alpha6
*/
private int w;
/**
* Creates and initializes a new 4D integer vector.
*
* @param x X axis value
* @param y Y axis value
* @param z Z axis value
* @param w W axis value
* @since v1-alpha6
*/
public Vec4i(int x, int y, int z, int w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Creates an identical copy of this vector.
*
* @return identical copy
* @since v1-alpha6
*/
@SneakyThrows
public @NotNull Vec4i clone() {
return (Vec4i) super.clone();
}
/**
* Returns a string representation of this vector.
*
* @return string representation
* @since v1-alpha6
*/
@Override
public @NotNull String toString() {
return (EngineConfiguration.getInstance().isHideFullTypePath()
? getClass().getName().replace(getClass().getPackage() + ".", "")
: getClass().getName())
+ "(x=" + x + " y=" + y + " z=" + z + " w=" + w + ")";
}
}

View file

@ -1,25 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Data types operating with sets of numbers.
*
* @since v1-alpha1
*/
package de.staropensource.engine.base.type.vector;

View file

@ -1,365 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.utility;
import de.staropensource.engine.base.exception.dependency.DependencyCycleException;
import de.staropensource.engine.base.exception.dependency.UnmetDependenciesException;
import de.staropensource.engine.base.implementable.VersioningSystem;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.DependencyVector;
import lombok.Getter;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Resolves dependency vectors.
*
* @since v1-alpha1
*/
@SuppressWarnings({ "unused", "UnusedReturnValue", "JavadocDeclaration" })
public final class DependencyResolver {
/**
* List of {@link DependencyVector}s to resolve.
*
* @since v1-alpha1
*/
@NotNull Set<DependencyVector> vectors = new HashSet<>();
/**
* Contains whether the current {@link DependencyVector} list has been resolved successfully.
*
* @since v1-alpha1
* -- GETTER --
* Returns whether the current {@link DependencyVector} list has been resolved successfully.
*
* @return resolved status
* @since v1-alpha1
*/
@Getter
private boolean resolved = false;
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha1
*/
public DependencyResolver() {}
/**
* Adds a {@link DependencyVector}.
*
* @param vector {@link DependencyVector} to add
* @return itself
* @throws IllegalArgumentException if the specified vector has been added already
* @since v1-alpha1
*/
public synchronized @NotNull DependencyResolver addVector(@NotNull DependencyVector vector) throws IllegalArgumentException {
if (vectors.contains(vector))
throw new IllegalArgumentException("The specified vector has been added already");
try {
vectors.add(vector);
} catch (IllegalArgumentException ignored) {}
resolved = false;
return this;
}
/**
* Adds multiple dependency vectors.
*
* @param vectors {@link DependencyVector}s to add
* @return itself
* @since v1-alpha1
*/
public @NotNull DependencyResolver addVectors(@NotNull DependencyVector @NotNull [] vectors) {
return addVectors(Arrays.stream(vectors).toList());
}
/**
* Adds multiple dependency vectors.
*
* @param vectors {@link DependencyVector}s to add
* @return itself
* @since v1-alpha1
*/
public @NotNull DependencyResolver addVectors(@NotNull Collection<? extends @NotNull DependencyVector> vectors) {
for (DependencyVector vector : vectors) // thread-safety
addVector(vector);
return this;
}
/**
* Resolves all dependency vectors.
* Throws an exception when detecting an unmet dependency or a dependency cycle.
*
* @return itself
* @throws IllegalStateException when encountering an invalid vector
* @throws UnmetDependenciesException when dependencies are unmet
* @throws DependencyCycleException when a circular dependency is found
* @since v1-alpha4
*/
public synchronized @NotNull DependencyResolver resolve() throws IllegalStateException, UnmetDependenciesException {
List<@NotNull String> unmetDependencies = new ArrayList<>();
List<@NotNull String> output;
for (DependencyVector vector : vectors)
unmetDependencies.addAll(resolveVector(vector, new LinkedHashSet<>()));
if (!unmetDependencies.isEmpty())
throw new UnmetDependenciesException(unmetDependencies);
resolved = true;
return this;
}
/**
* Resolves a vector.
* Throws an exception when detecting an unmet dependency or a dependency cycle.
*
* @return list of unmet dependencies
* @throws IllegalStateException when encountering an invalid dependency or provider
* @throws DependencyCycleException when a circular dependency is found
* @throws Exception when some unknown error occurs
* @since v1-alpha4
*/
private @NotNull List<@NotNull String> resolveVector(@NotNull DependencyVector vector, @NotNull LinkedHashSet<@NotNull String> vectorsDependencyStack) throws IllegalStateException, DependencyCycleException {
List<@NotNull String> unmetDependencies = new ArrayList<>();
vectorsDependencyStack.add(vector.getIdentifier());
// 0 = identifier
// 1 = version equal
// 2 = version smaller
// 3 = version bigger
int mode;
boolean[] duplicateCheck;
StringBuilder identifier;
StringBuilder versionEqual;
StringBuilder versionSmaller;
StringBuilder versionBigger;
for (String dependency : vector.getDependencies()) {
mode = 0;
duplicateCheck = new boolean[3];
identifier = new StringBuilder();
versionEqual = new StringBuilder();
versionSmaller = new StringBuilder();
versionBigger = new StringBuilder();
// Get variables
for (char character : dependency.toCharArray()) {
switch (character) {
case '=' -> {
// Check for duplicate
if (duplicateCheck[0])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot include multiple '=' characters");
// Update mode
mode = 1;
continue;
}
case '<' -> {
// Check for duplicate
if (duplicateCheck[1])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot include multiple '<' characters");
// Update mode
mode = 2;
continue;
}
case '>' -> {
// Check for duplicate
if (duplicateCheck[2])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot include multiple '>' characters");
// Update mode
mode = 3;
continue;
}
}
switch (mode) {
// Identifier
case 0 -> identifier.append(character);
// Version equal
case 1 -> {
duplicateCheck[0] = true;
// Check for smaller and bigger than
if (duplicateCheck[1] || duplicateCheck[2])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot require a specific version and have minimum and maximum version specifiers");
versionEqual.append(character);
}
// Version smaller
case 2 -> {
duplicateCheck[1] = true;
// Check for equal
if (duplicateCheck[0])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot require a specific version and have minimum and maximum version specifiers");
versionSmaller.append(character);
}
// Version bigger
case 3 -> {
duplicateCheck[2] = true;
// Check for equal
if (duplicateCheck[0])
throw new IllegalStateException("The dependency listing \"" + dependency + "\" cannot require a specific version and have minimum and maximum version specifiers");
versionBigger.append(character);
}
}
}
// Get vector with same identifier
DependencyVector vectorDependency = getMatchingVector(identifier.toString());
if (vectorDependency == null) {
unmetDependencies.add("Dependency \"" + dependency + "\" is not met: Not found");
continue;
}
// Resolve vector
if (vectorsDependencyStack.contains(vectorDependency.getIdentifier())) {
StringBuilder cycle = new StringBuilder();
for (String component : vectorsDependencyStack) {
if (!cycle.isEmpty())
cycle.append(" -> ");
cycle.append(component);
}
cycle
.append(" -> ")
.append(identifier);
throw new DependencyCycleException("Dependency cycle detected: " + cycle);
} else
resolveVector(vectorDependency, vectorsDependencyStack);
VersioningSystem versioningSystemResolved;
// Get resolved versioning system
try {
versioningSystemResolved = vectorDependency.getVersioningSystem().getDeclaredConstructor(String.class).newInstance(vectorDependency.getVersion());
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
Logger.crash("Unable to check version of dependency \"" + dependency + "\": Unable to initialize versioning system " + vectorDependency.getVersioningSystem().getName(), exception);
break;
}
// Compare
if (!versionEqual.isEmpty()) { // Version equals
VersioningSystem versioningSystemEquals;
// Get expected VersioningSystem
try {
versioningSystemEquals = vectorDependency.getVersioningSystem().getDeclaredConstructor(String.class).newInstance(versionEqual.toString());
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
Logger.crash("Unable to check version of dependency \"" + dependency + "\": Unable to initialize versioning system " + vectorDependency.getVersioningSystem().getName(), exception);
break;
}
// Compare versions
if (versioningSystemResolved.compare(versioningSystemEquals) != 1)
unmetDependencies.add("Dependency \"" + dependency + "\" is not met: Expected version " + versionEqual + " does not match found version " + vector.getVersion());
} else if (!versionBigger.isEmpty() || !versionSmaller.isEmpty()) {
VersioningSystem versioningSystemSmaller = null;
VersioningSystem versioningSystemBigger = null;
if (!versionSmaller.isEmpty())
// Get expected VersioningSystem
try {
versioningSystemSmaller = vectorDependency.getVersioningSystem().getDeclaredConstructor(String.class).newInstance(versionSmaller.toString());
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
Logger.crash("Unable to check version of dependency \"" + dependency + "\": Unable to initialize versioning system " + vectorDependency.getVersioningSystem().getName(), exception);
break;
}
if (!versionBigger.isEmpty())
// Get expected VersioningSystem
try {
versioningSystemBigger = vectorDependency.getVersioningSystem().getDeclaredConstructor(String.class).newInstance(versionBigger.toString());
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException exception) {
Logger.crash("Unable to check version of dependency \"" + dependency + "\": Unable to initialize versioning system " + vectorDependency.getVersioningSystem().getName(), exception);
break;
}
// Compare versions
if (versioningSystemSmaller != null && versioningSystemBigger != null) {
if (versioningSystemResolved.compare(versioningSystemSmaller) != 2 || versioningSystemResolved.compare(versioningSystemBigger) != 0)
unmetDependencies.add("Dependency \"" + dependency + "\" is not met: Version " + vector.getVersion() + " is not in range " + versionSmaller + " to " + versionBigger);
} else {
if (versioningSystemSmaller != null)
if (versioningSystemResolved.compare(versioningSystemSmaller) != 2)
unmetDependencies.add("Dependency \"" + dependency + "\" is not met: Version " + vector.getVersion() + " is bigger than " + versionSmaller);
if (versioningSystemBigger != null)
if (versioningSystemResolved.compare(versioningSystemBigger) != 0)
unmetDependencies.add("Dependency \"" + dependency + "\" is not met: Version " + vector.getVersion() + " is smaller than " + versionBigger);
}
}
}
vectorsDependencyStack.remove(vector.getIdentifier());
return unmetDependencies;
}
/**
* Searches all registered {@link DependencyVector}s for the specified identifier
* and returns the first matching one.
*
* @return matching vector or {@code null} if not found
* @since v1-alpha4
*/
private @Nullable DependencyVector getMatchingVector(@NotNull String identifier) {
for (DependencyVector vector : vectors) {
if (vector.getIdentifier().equals(identifier)) {
return vector;
} else {
// Search 'provides' for matches
for (String provider : vector.getProvides())
if (provider.substring(0, provider.indexOf("=")).equals(identifier))
return vector;
}
}
return null;
}
/**
* Returns the correct order which stuff needs to be loaded/done in.
*
* @return {@link LinkedList} with dependencies first and dependents last
* @throws IllegalStateException when the current dependency vector list has not been resolved yet. in this case, just invoke {@code resolve()}
* @since v1-alpha1
*/
@ApiStatus.Experimental() // TODO
public LinkedList<DependencyVector> getOrder() throws IllegalStateException {
if (!resolved)
throw new IllegalStateException("The current dependency vector list has not been resolved yet");
return new LinkedList<>();
}
}

View file

@ -1,851 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.utility;
import de.staropensource.engine.base.Engine;
import de.staropensource.engine.base.logging.Logger;
import de.staropensource.engine.base.type.EngineState;
import de.staropensource.engine.base.type.FileType;
import lombok.Getter;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
import java.util.stream.Stream;
/**
* Provides a simplified way of
* accessing files and directories.
*
* @since v1-alpha8
*/
@Getter
@SuppressWarnings({ "JavadocDeclaration", "unused" })
public final class FileAccess {
// -----> Static variables
/**
* Contains a list of all files and directories
* which should be deleted at shutdown.
* <p>
* While this feature is built into Java, in
* our testing it did not seem to work correctly.
* That's why we're implementing it here.
*
* @since v1-alpha8
*/
private static @NotNull Path[] scheduledDeletion = new Path[0];
/**
* Contains a {@link FileAccess} instance to
* a cache directory provided by the engine.
*
* @since v1-alpha8
* -- GETTER --
* Returns a {@link FileAccess} instance to
* a cache directory provided by the engine.
*
* @return cache directory
* @since v1-alpha8
*/
@Getter
private static FileAccess cacheDirectory;
// -----> Instance variables
/**
* Contains the {@link Path} to this file or directory.
*
* @since v1-alpha8
* -- GETTER --
* Returns the {@link Path} to this file or directory.
* <p>
* Please only use this method when you have to.
* Use the methods in this class instead, if you can.
*
* @return associated {@link Path} instance
* @since v1-alpha8
*/
private final @NotNull Path path;
/**
* Contains the {@link File} to this file or directory.
*
* @since v1-alpha8
* -- GETTER --
* Returns the {@link File} to this file or directory.
* <p>
* Please only use this method when you have to.
* Use the methods in this class instead, if you can.
*
* @return associated {@link File} instance
* @since v1-alpha8
*/
private final @NotNull File file;
// -----> Constructors
/**
* Creates and initializes an instance of this class.
*
* @param path path you wish to access
* @throws InvalidPathException if a {@link Path} cannot be created (see {@link FileSystem#getPath(String, String...)})
* @since v1-alpha8
*/
public FileAccess(@NotNull String path) throws InvalidPathException {
this.path = formatPath(path).toAbsolutePath();
this.file = new File(path);
}
/**
* Creates and initializes an instance of this class.
*
* @param path path you wish to access
* @since v1-alpha8
*/
public FileAccess(@NotNull Path path) {
this.path = path.toAbsolutePath();
this.file = this.path.toFile();
}
/**
* Creates and initializes an instance of this class.
*
* @param file {@link File} to the path you wish to access
* @throws InvalidPathException if a {@link Path} cannot be created (see {@link FileSystem#getPath(String, String...)})
* @since v1-alpha8
*/
public FileAccess(@NotNull File file) throws InvalidPathException {
this.path = file.toPath().toAbsolutePath();
this.file = file;
}
/**
* Creates and initializes an instance of this class.
*
* @param uri {@link URI} to the path you wish to access
* @throws FileSystemNotFoundException if the filesystem is not supported by Java
* @throws IllegalArgumentException if the URI is improperly formatted
* @since v1-alpha8
*/
public FileAccess(@NotNull URI uri) throws FileSystemNotFoundException, IllegalArgumentException {
this.path = Path.of(uri);
this.file = new File(uri);
}
// -----> Static instance initialization
/**
* Initializes all uninitialized static
* {@link FileAccess} instances.
* <p>
* Only works during early engine startup.
*
* @throws IOException on an IO error
* @since v1-alpha8
*/
public static void initializeInstances() throws IOException {
if (Engine.getInstance().getState() == EngineState.EARLY_STARTUP)
cacheDirectory = new FileAccess(System.getProperties().getProperty("java.io.tmpdir").replace("\\", "/") + "/sosengine-cache-" + ProcessHandle.current().pid()).createDirectory().deleteOnShutdown();
}
/**
* Deletes all files scheduled for deletion.
* <p>
* Only works during engine shutdown.
*
* @since v1-alpha8
*/
public static void deleteScheduled() {
if (Engine.getInstance().getState() == EngineState.SHUTDOWN || Engine.getInstance().getState() == EngineState.CRASHED) {
Logger.verb("Deleting files scheduled for deletion on shutdown");
for (Path path : scheduledDeletion)
try (Stream<Path> stream = Files.walk(path)) {
Logger.diag("Deleting file or directory \"" + path + "\"");
//noinspection ResultOfMethodCallIgnored
stream.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
if (Files.exists(path))
Logger.error("Deleting file or directory \"" + path + "\" failed");
} catch (Exception exception) {
Logger.error("File or directory \"" + path + "\" could not be deleted\n" + Miscellaneous.getStackTraceHeader(exception) + "\n" + Miscellaneous.getStackTraceAsString(exception, true));
}
}
}
// -----> Path formatting
/**
* Formats the path into a {@link Path} instance.
*
* @param path path to format
* @return formatted {@link Path}
* @since v1-alpha8
*/
public static @NotNull Path formatPath(@NotNull String path) {
return Path.of(
path
.replace("/./", "/")
.replace("/", File.separator)
);
}
/**
* Unformats the a {@link Path} instance into a string.
*
* @param path {@link Path} to unformat
* @return unformatted path
* @since v1-alpha8
*/
public static @NotNull String unformatPath(@NotNull Path path) {
return path
.toString()
.replace(File.separator, "/");
}
// -----> File getters & setters
/**
* Returns the absolute path of this file.
*
* @return absolute path
* @since v1-alpha8
*/
public @NotNull String getPath() {
return unformatPath(path);
}
/**
* Returns the file name.
*
* @param excludeExtension if to remove the extension (e.g. {@code .txt}, {@code .java})
* @return file name
* @since v1-alpha8
*/
public @NotNull String getFileName(boolean excludeExtension) {
if (excludeExtension)
return file.getName().replaceFirst("[.][^.]+$", "");
else
return file.getName();
}
/**
* Returns whether or not this file exists.
*
* @return exists?
* @since v1-alpha8
*/
public boolean exists() {
return Files.exists(path);
}
/**
* Returns the type of this file.
*
* @return file type
* @since v1-alpha8
*/
public @NotNull FileType getType() {
if (!exists())
return FileType.VOID;
else if (Files.isRegularFile(path))
return FileType.FILE;
else if (Files.isDirectory(path))
return FileType.DIRECTORY;
else
return FileType.UNKNOWN;
}
/**
* Returns whether or not this file is a symbolic link.
*
* @return symbolic link?
* @since v1-alpha8
*/
public boolean isSymbolicLink() {
return Files.isSymbolicLink(path);
}
/**
* Returns whether or not the file is hidden.
*
* @return is hidden?
* @throws IOException on an IO error
* @since v1-alpha8
*/
public boolean isHidden() throws IOException {
return Files.isHidden(path);
}
/**
* Returns the names of all files and
* directories in this directory.
*
* @return array of file and directory names
* @throws UnsupportedOperationException if the file is not a directory
* @throws IOException on an IO error
* @since v1-alpha8
*/
public @NotNull String @NotNull [] listContents() throws UnsupportedOperationException, IOException {
if (getType() != FileType.DIRECTORY)
throw new UnsupportedOperationException("The file \"" + path + "\" is not a directory");
String[] list = file.list();
if (list == null)
throw new IOException("list is null");
else
return list;
}
/**
* Returns the destination of the symbolic link.
*
* @return file type
* @throws UnsupportedOperationException if the file is not a symbolic link
* @throws IOException on an IO error
* @since v1-alpha8
*/
public @NotNull String getLinkDestination() throws IOException {
if (!isSymbolicLink())
throw new UnsupportedOperationException("The file \"" + path + "\" is not a symbolic link");
return unformatPath(Files.readSymbolicLink(path));
}
// -----> Permissions
/**
* Returns whether or not the file can be read from.
*
* @return can be read?
* @since v1-alpha8
*/
public boolean isReadable() {
return Files.isReadable(path);
}
/**
* Returns whether or not the file can be written to.
*
* @return can be written?
* @since v1-alpha8
*/
public boolean isWritable() {
return Files.isWritable(path);
}
/**
* Returns whether or not the file can be executed.
*
* @return can be executed?
* @since v1-alpha8
*/
public boolean isExecutable() {
return Files.isExecutable(path);
}
/**
* Returns the file's permissions the
* POSIX {@code rwxrwxrwx} format.
*
* @return POSIX permissions format
* @throws IOException on an IO error
* @since v1-alpha8
*/
public @NotNull String getPosixPermissions() throws IOException {
try {
return PosixFilePermissions.toString(Files.getPosixFilePermissions(path));
} catch (UnsupportedOperationException exception) {
// POSIX permissions are not supported
// For the Macrohard Windoze users under us
StringBuilder output = new StringBuilder();
if (isReadable())
output.append("r");
if (isWritable())
output.append("w");
if (isExecutable())
output.append("x");
// Repeat the same thing two times
output.repeat(output, 2);
return output.toString();
}
}
/**
* Returns the file's permissions the
* POSIX {@code rwxrwxrwx} format.
*
* @param permissions POSIX {@code rwxrwxrwx} permission format
* @return this instance
* @throws IllegalArgumentException if the format of the {@code permissions} argument is invalid
* @throws IOException on an IO error
* @since v1-alpha8
*/
@SuppressWarnings({ "RegExpSingleCharAlternation", "ResultOfMethodCallIgnored" })
public @NotNull FileAccess setPosixPermissions(@NotNull String permissions) throws IllegalArgumentException, IOException {
if (
permissions.length() != 9
|| !permissions.matches("^(r|-)(w|-)(x|-)(r|-)(w|-)(x|-)(r|-)(w|-)(x|-)$")
)
throw new IllegalArgumentException("Invalid permission format: " + permissions);
try {
Logger.diag("Setting POSIX file permissions for \"" + path + "\" to '" + permissions + "'");
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(permissions));
} catch (UnsupportedOperationException exception) {
Logger.diag("Setting POSIX file permissions for \"" + path + "\" to '" + permissions.substring(0, 2) + "'");
char @NotNull [] chars = permissions.toCharArray();
for (int permission = 0; permission < 3; permission++) {
boolean enabled = chars[permission] != '-';
switch (permission) {
case 0 -> file.setReadable(enabled);
case 1 -> file.setWritable(enabled);
case 2 -> file.setExecutable(enabled);
}
}
}
return this;
}
// -----> Filesystem information
/**
* Returns the filesystem of this file.
*
* @return filesystem
* @since v1-alpha8
*/
public @NotNull FileSystem getFilesystem() {
return path.getFileSystem();
}
/**
* Returns whether or not the filesystem is POSIX-compliant.
*
* @return POSIX compliant?
* @since v1-alpha8
*/
public boolean isFilesystemPosixCompliant() {
return path.getFileSystem().supportedFileAttributeViews().contains("posix");
}
/**
* Returns all forbidden file names.
* <p>
* The required functionality is not yet
* implemented. As such, this method
* will just return an empty array.
*
* @return forbidden file names
* @since v1-alpha8
*/
@ApiStatus.Experimental
public @NotNull String @NotNull [] getRestrictedFileNames() {
return new String[0];
}
/**
* Returns all forbidden characters in file names.
* <p>
* The required functionality is not yet
* implemented. As such, this method
* will just return an empty array.
*
* @return forbidden characters
* @since v1-alpha8
*/
@ApiStatus.Experimental
public char @NotNull [] getRestrictedCharacters() {
return new char[0];
}
// -----> Directory traversal
/**
* Returns the parent directory.
*
* @return new {@link FileAccess} instance to the parent directory
* @since v1-alpha8
*/
public @NotNull FileAccess parent() {
return new FileAccess(path.getParent());
}
/**
* Traverses through directories and files.
*
* @param path path to traverse
* @return new {@link FileAccess} instance
* @since v1-alpha8
*/
public @NotNull FileAccess traverse(@NotNull String path) {
return new FileAccess(this.path.resolve(formatPath(path)));
}
/**
* Traverses through directories and files.
*
* @param path path to traverse
* @return new {@link FileAccess} instance
* @throws FileNotFoundException if the specified path does not exist
* @since v1-alpha8
*/
public @NotNull FileAccess traverseIfExists(@NotNull String path) throws FileNotFoundException {
Path pathResolved = this.path.resolve(formatPath(path));
if (!Files.exists(pathResolved))
throw new FileNotFoundException("Traversal failed as relative path \"" + path + "\" does not exist from absolute path \"" + path + "\"");
return new FileAccess(pathResolved);
}
// -----> File/Directory creation and deletion
/**
* Deletes the file.
* If it doesn't exist, nothing will be done.
*
* @return this instance
* @since v1-alpha8
*/
public @NotNull FileAccess delete() {
if (exists()) {
Logger.diag("Deleting \"" + path + "\"");
//noinspection ResultOfMethodCallIgnored
file.delete();
}
return this;
}
/**
* Marks this file for deletion at engine shutdown.
*
* @return this instance
* @see Engine#shutdown()
* @see Engine#shutdown(int)
* @since v1-alpha8
*/
public @NotNull FileAccess deleteOnShutdown() {
Logger.diag("Marking \"" + path + "\" for deletion at engine shutdown");
// Append path to scheduledDeletion array
List<@NotNull Path> scheduledDeletionList = new ArrayList<>(Arrays.stream(scheduledDeletion).toList());
scheduledDeletionList.add(path);
scheduledDeletion = scheduledDeletionList.toArray(new Path[0]);
return this;
}
/**
* Creates the file.
* If it already exists, nothing will be done.
*
* @return this instance
* @throws IOException on an IO error
* @since v1-alpha8
*/
@SuppressWarnings({"UnusedReturnValue", "ResultOfMethodCallIgnored"})
public @NotNull FileAccess createFile() throws IOException {
if (!exists()) {
Logger.diag("Creating a file at \"" + path + "\"");
file.getParentFile().mkdirs();
file.createNewFile();
}
return this;
}
/**
* Creates the directory recursively.
* If it already exists, nothing will be done.
*
* @return this instance
* @throws IOException on an IO error
* @since v1-alpha8
*/
public @NotNull FileAccess createDirectory() throws IOException {
if (!exists()) {
Logger.diag("Creating a directory at \"" + path + "\"");
if (!file.mkdirs())
throw new IOException("Creating directory \"" + path + "\" recursively failed");
}
return this;
}
/**
* Creates a symbolic link at this location.
* If it already exists, nothing will be done.
*
* @param hard creates a hard link if {@code true} or a symbolic link if {@code false}
* @param destination destination of the new link
* @return this instance
* @throws IOException on an IO error
* @since v1-alpha8
*/
@SuppressWarnings("UnusedReturnValue")
public @NotNull FileAccess createLink(boolean hard, @NotNull String destination) throws IOException {
if (!exists()) {
Logger.diag("Creating a " + (hard ? "hard" : "symbolic") + " link at \"" + path + "\"");
if (hard)
Files.createLink(path, formatPath(destination));
else
Files.createSymbolicLink(path, formatPath(destination));
}
return this;
}
// -----> File locking
/**
* Returns whether or not this file is locked.
*
* @return is locked?
* @since v1-alpha8
*/
public boolean isLocked() {
return false;
}
/**
* Locks this file.
*
* @return this instance
* @since v1-alpha8
*/
public @NotNull FileAccess lock() {
return this;
}
/**
* Unlocks this file.
*
* @return this instance
* @since v1-alpha8
*/
public @NotNull FileAccess unlock() {
return this;
}
// -----> Content reading
/**
* Returns the contents of this file.
* <p>
* Returns an empty array if this file
* is not of type {@link FileType#FILE}.
*
* @return file contents in bytes
* @throws IOException on an IO error
* @throws OutOfMemoryError if the file is larger than the allocated amount of memory
* @since v1-alpha8
*/
public byte @NotNull [] readBytes() throws IOException, OutOfMemoryError {
if (getType() != FileType.FILE)
return new byte[0];
Logger.diag("Reading file \"" + path + "\" (bytes)");
return Files.readAllBytes(path);
}
/**
* Returns the contents of this file.
* <p>
* Returns an empty list if this file
* is not of type {@link FileType#FILE}.
*
* @return file contents in bytes
* @throws IOException on an IO error
* @throws OutOfMemoryError if the file is larger than the allocated amount of memory
* @since v1-alpha8
*/
public @NotNull List<@NotNull String> readLines() throws IOException, OutOfMemoryError {
if (getType() != FileType.FILE)
return new ArrayList<>();
Logger.diag("Reading file \"" + path + "\" (lines)");
return Files.readAllLines(path);
}
/**
* Returns the contents of this file.
* This method will decode the bytes using the
* {@link StandardCharsets#UTF_8} character set.
* <p>
* Returns an empty string if this file
* is not of type {@link FileType#FILE}.
*
* @return file contents as a string
* @throws IOException on an IO error
* @throws OutOfMemoryError if the file is larger than the allocated amount of memory
* @since v1-alpha8
*/
public @NotNull String readContent() throws IOException, OutOfMemoryError {
return readContent(StandardCharsets.UTF_8);
}
/**
* Returns the contents of this file.
* <p>
* Returns an empty string if this file
* is not of type {@link FileType#FILE}.
*
* @param charset charset to decode the bytes with
* @return file contents as a string
* @throws IOException on an IO error
* @throws OutOfMemoryError if the file is larger than the allocated amount of memory
* @since v1-alpha8
*/
public @NotNull String readContent(@NotNull Charset charset) throws IOException, OutOfMemoryError {
if (getType() != FileType.FILE)
return "";
Logger.diag("Reading file \"" + path + "\" (string)");
return Files.readString(path, charset);
}
// -----> Content writing
/**
* Writes the specified bytes into this file.
*
* @param bytes bytes to write
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess writeBytes(byte @NotNull [] bytes, boolean async) throws UnsupportedOperationException, IOException {
if (getType() == FileType.VOID)
createFile();
else if (getType() != FileType.FILE)
throw new UnsupportedOperationException("File \"" + path + "\" is not of type FileType.VOID or FileType.FILE");
createFile();
Logger.diag("Writing file \"" + path + "\" (bytes, " + (async ? "async" : "dsync") + ")");
Files.write(path, bytes, StandardOpenOption.WRITE, async ? StandardOpenOption.DSYNC : StandardOpenOption.SYNC);
return this;
}
/**
* Writes the specified bytes into this file.
* This method will encode the string using the
* {@link StandardCharsets#UTF_8} character set.
*
* @param string string to write
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess writeString(@NotNull String string, boolean async) throws UnsupportedOperationException, IOException {
return writeString(string, StandardCharsets.UTF_8, async);
}
/**
* Writes the specified bytes into this file.
*
* @param string string to write
* @param charset charset to encode the string in
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess writeString(@NotNull String string, @NotNull Charset charset, boolean async) throws UnsupportedOperationException, IOException {
if (getType() == FileType.VOID)
createFile();
else if (getType() != FileType.FILE)
throw new UnsupportedOperationException("File \"" + path + "\" is not of type FileType.VOID or FileType.FILE");
Logger.diag("Writing file \"" + path + "\" (string, " + (async ? "async" : "dsync") + ")");
Files.writeString(path, string, charset, StandardOpenOption.WRITE, async ? StandardOpenOption.DSYNC : StandardOpenOption.SYNC);
return this;
}
// -----> Content appending
/**
* Appends the specified bytes to this file.
*
* @param bytes bytes to append
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess appendBytes(byte @NotNull [] bytes, boolean async) throws UnsupportedOperationException, IOException {
if (getType() == FileType.VOID)
createFile();
else if (getType() != FileType.FILE)
throw new UnsupportedOperationException("File \"" + path + "\" is not of type FileType.VOID or FileType.FILE");
Logger.diag("Appending file \"" + path + "\" (bytes, " + (async ? "async" : "dsync") + ")");
Files.write(path, bytes, StandardOpenOption.APPEND, async ? StandardOpenOption.DSYNC : StandardOpenOption.SYNC);
return this;
}
/**
* Appends the specified string to this file.
* This method will encode the string using the
* {@link StandardCharsets#UTF_8} character set.
*
* @param string string to append
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess appendString(@NotNull String string, boolean async) throws UnsupportedOperationException, IOException {
return appendString(string, StandardCharsets.UTF_8, async);
}
/**
* Appends the specified string to this file.
*
* @param string string to append
* @param charset charset to encode the string in
* @param async allows the operating system to decide when to flush the file to disk if {@code true}, flushes the data to disk immediately if {@code false}
* @throws UnsupportedOperationException if the type of this file is neither {@link FileType#VOID} or {@link FileType#FILE}
* @throws IOException on an IO error
* @return this instance
*/
public @NotNull FileAccess appendString(@NotNull String string, @NotNull Charset charset, boolean async) throws UnsupportedOperationException, IOException {
if (getType() == FileType.VOID)
createFile();
else if (getType() != FileType.FILE)
throw new UnsupportedOperationException("File \"" + path + "\" is not of type FileType.VOID or FileType.FILE");
Logger.diag("Appending file \"" + path + "\" (string, " + (async ? "async" : "dsync") + ")");
Files.writeString(path, string, charset, StandardOpenOption.APPEND, async ? StandardOpenOption.DSYNC : StandardOpenOption.SYNC);
return this;
}
}

View file

@ -1,250 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.utility;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.LinkedList;
/**
* Utility class for math operations.
*
* @since v1-alpha2
*/
// All mean and double methods have been sourced
// from https://stackoverflow.com/a/4191729, tysm!
@SuppressWarnings({ "unused" })
public final class Math {
/**
* Creates and initializes an instance of this class
*
* @since v1-alpha6
*/
private Math() {}
/**
* Adds padding zeros to a number.
*
* @param number number
* @param length length
* @return the padded number
* @since v1-alpha2
*/
public static @NotNull String padNumbers(long number, int length) {
return String.format("%0" + length + "d", number);
}
/**
* Ensures the integer is inside the
* specified bounds. If not, the
* integer will be corrected.
*
* @param min minimum value
* @param max maximum value
* @param value value
* @return number in threshold
* @throws IndexOutOfBoundsException when the minimum value is bigger than the maximum value
* @since v1-alpha6
*/
public static int boundNumber(int min, int max, int value) throws IndexOutOfBoundsException {
if (min > max)
throw new IndexOutOfBoundsException();
if (value < min)
value = min;
else if (value > max)
value = max;
return value;
}
/**
* Ensures the float is inside the
* specified bounds. If not, the
* float will be corrected.
*
* @param min minimum value
* @param max maximum value
* @param value value
* @return number in threshold
* @throws IndexOutOfBoundsException when the minimum value is bigger than the maximum value
* @since v1-alpha6
*/
public static float boundNumber(float min, float max, float value) throws IndexOutOfBoundsException {
if (min > max)
throw new IndexOutOfBoundsException();
if (value < min)
value = min;
else if (value > max)
value = max;
return value;
}
/**
* Ensures the double is inside the
* specified bounds. If not, the
* double will be corrected.
*
* @param min minimum value
* @param max maximum value
* @param value value
* @return number in threshold
* @throws IndexOutOfBoundsException when the minimum value is bigger than the maximum value
* @since v1-alpha6
*/
public static double boundNumber(double min, double max, double value) throws IndexOutOfBoundsException {
if (min > max)
throw new IndexOutOfBoundsException();
if (value < min)
value = min;
else if (value > max)
value = max;
return value;
}
/**
* Returns the mean of a collection of numbers.
*
* @param collection collection of {@code double}s
* @return mean
* @since v1-alpha2
*/
public static double getMeanDouble(@NotNull Collection<@NotNull Double> collection) {
double sum = 0;
for (double number : collection)
sum += number;
return sum / collection.size();
}
/**
* Returns the mean of a collection of numbers.
*
* @param collection collection of {@code float}s
* @return mean
* @since v1-alpha2
*/
public static double getMeanFloat(@NotNull Collection<@NotNull Float> collection) {
double sum = 0;
for (float number : collection)
sum += number;
return sum / collection.size();
}
/**
* Returns the mean of a collection of numbers.
*
* @param collection collection of {@code long}s
* @return mean
* @since v1-alpha2
*/
public static double getMeanLong(@NotNull Collection<@NotNull Long> collection) {
double sum = 0;
for (long number : collection)
sum += number;
return sum / collection.size();
}
/**
* Returns the mean of a collection of numbers.
*
* @param collection collection of {@code int}s
* @return mean
* @since v1-alpha2
*/
public static double getMeanInt(@NotNull Collection<@NotNull Integer> collection) {
double sum = 0;
for (int number : collection)
sum += number;
return sum / collection.size();
}
/**
* Returns the median of a linked list of numbers.
*
* @param list linked list of {@code double}s
* @return median
* @since v1-alpha2
*/
public static double getMedianDouble(@NotNull LinkedList<@NotNull Double> list) {
int middle = list.size() / 2;
if (list.size() % 2 == 1)
return list.get(middle);
else
return list.get(middle - 1) / 2.0 + list.get(middle) / 2.0;
}
/**
* Returns the median of a linked list of numbers.
*
* @param list linked list of {@code float}s
* @return median
* @since v1-alpha2
*/
public static double getMedianFloat(@NotNull LinkedList<@NotNull Float> list) {
int middle = list.size() / 2;
if (list.size() % 2 == 1)
return list.get(middle);
else
return list.get(middle - 1) / 2.0 + list.get(middle) / 2.0;
}
/**
* Returns the median of a linked list of numbers.
*
* @param list linked list of {@code long}s
* @return median
* @since v1-alpha2
*/
public static double getMedianLong(@NotNull LinkedList<@NotNull Long> list) {
int middle = list.size() / 2;
if (list.size() % 2 == 1)
return list.get(middle);
else
return list.get(middle - 1) / 2.0 + list.get(middle) / 2.0;
}
/**
* Returns the median of a linked list of numbers.
*
* @param list linked list of {@code int}s
* @return median
* @since v1-alpha2
*/
public static double getMedianInt(@NotNull LinkedList<@NotNull Integer> list) {
int middle = list.size() / 2;
if (list.size() % 2 == 1)
return list.get(middle);
else
return list.get(middle - 1) / 2.0 + list.get(middle) / 2.0;
}
}

View file

@ -1,254 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.engine.base.utility;
import de.staropensource.engine.base.event.ThrowableCatchEvent;
import de.staropensource.engine.base.exception.TristateConversionException;
import de.staropensource.engine.base.type.Tristate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.stream.Collectors;
/**
* Contains smaller functions that don't fit into other utility classes.
*
* @since v1-alpha0
*/
@SuppressWarnings({ "unused" })
public final class Miscellaneous {
/**
* Creates and initializes an instance of this class.
*
* @since v1-alpha6
*/
private Miscellaneous() {}
/**
* Converts a boolean into an integer.
*
* @param bool boolean to convert
* @return converted integer
* @since v1-alpha2
*/
@Range(from = 0, to = 1)
public static int getIntegerizedBoolean(boolean bool) {
return bool ? 1 : 0;
}
/**
* Converts an integer into a {@link Tristate}.
*
* @param integer integer to convert
* @return expected boolean result, except if neither {@code 0} or {@code 1}, in which case {@link Tristate#UNSET} is returned
* @since v1-alpha2
*/
public static Tristate getTristatedInteger(@Range(from = 0, to = 1) int integer) {
return switch (integer) {
case 0 -> Tristate.TRUE;
case 1 -> Tristate.FALSE;
default -> Tristate.UNSET;
};
}
/**
* Converts an integer into a {@link Tristate} and then into a boolean.
*
* @param integer integer to convert
* @return booleanized integer
* @throws TristateConversionException when encountering {@link Tristate#UNSET}.
* @since v1-alpha2
*/
public static boolean getBooleanizedInteger(@Range(from = 0, to = 1) int integer) throws TristateConversionException {
return getTristatedInteger(integer).toBoolean();
}
/**
* Searches for a value in a {@link Map}.
*
* @param map map to use
* @param value value to search for
* @return all keys matching the specified value
* @since v1-alpha0
*/
public static Set<?> getMapValues(@NotNull Map<?, ?> map, @Nullable Object value) {
return map
.entrySet().stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
/**
* Counts the occurrences of a substring inside of a string.
*
* @param string string to search
* @param substring substring to search for
* @return occurrences
*/
public static long countOccurrences(@NotNull String string, @NotNull String substring) {
return (string.length() - string.replace(substring, "").length()) / substring.length();
}
/**
* Returns the correct separator to use when splitting a string.
*
* @param string string to split
* @param separators separators to check
* @param requiredOccurrences exact amount of occurrences for a separator to be deemed valid
* @return separator to use or {@code null}
* @since v1-alpha1
*/
public static @Nullable String getSeparator(@NotNull String string, @NotNull String @NotNull [] separators, int requiredOccurrences) {
if (string.isBlank() || separators.length == 0 || requiredOccurrences == 0)
return null;
for (String separator : separators)
if (countOccurrences(string, separator) == requiredOccurrences)
return separator;
return null;
}
/**
* Returns the correct separator to use when splitting a string.
*
* @param string string to split
* @param separators separators to check
* @param minimumOccurrences minimum amount of occurrences for a separator to be deemed valid
* @return separator to use or {@code null}
* @since v1-alpha1
*/
public static @Nullable String getSeparator(@NotNull String string, List<String> separators, Integer minimumOccurrences) {
for (String separator : separators)
if (countOccurrences(string, separator) >= minimumOccurrences)
return separator;
return null;
}
/**
* Measures the execution time of a {@link Runnable}.
*
* @param runnable {@link Runnable} to execute
* @return execution time in milliseconds
* @see Runnable
* @since v1-alpha0
*/
public static long measureExecutionTime(@NotNull Runnable runnable) {
long initTime = System.currentTimeMillis();
runnable.run();
return System.currentTimeMillis() - initTime;
}
/**
* Executes a {@link Runnable} and emits {@link ThrowableCatchEvent} if a throwable is caught.
*
* @param runnable {@link Runnable} to execute
* @param identifier some identifier to distinguish {@link Runnable}s
* @since v1-alpha1
*/
public static void executeSafely(@NotNull Runnable runnable, @NotNull String identifier) {
try {
runnable.run();
} catch (Throwable throwable) {
new ThrowableCatchEvent().callEvent(throwable, identifier);
}
}
/**
* Forcefully invokes the garbage collector
* and blocks execution until finished.
* If you want to run it in parallel to your
* program, consider running it in a {@code VirtualThread}.
* <p>
* This method does not guarantee full garbage collection,
* as the JVM only hints the garbage collector to do it's job.
* This is because all garbage collectors are non-deterministic.
*
* @since v1-alpha0
*/
@SuppressWarnings("UnusedAssignment")
public static void invokeGarbageCollector() {
Object object = new Object();
WeakReference<Object> weakReference = new WeakReference<>(object);
object = null;
while(weakReference.get() != null) System.gc();
}
/**
* Ensures that the code is running on the main thread.
*
* @return {@code true} if running on the main thread, {@code false} otherwise
* @since v1-alpha2
*/
public static boolean onMainThread() {
return Thread.currentThread().threadId() == 1;
}
/**
* Returns the {@code Caused by} message usually found when the JVM prints a throwable.
*
* @param throwable {@link Throwable} to use
* @return stack trace header
* @since v1-alpha4
*/
public static @NotNull String getStackTraceHeader(@NotNull Throwable throwable) {
return "Caused by: " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage());
}
/**
* Converts an array of {@link StackTraceElement}s into a regular string.
*
* @param stacktrace array of {@link StackTraceElement}s to convert
* @param indent if all lines should be indented with a single {@code \t} character, like in regular stack traces
* @return converted stacktrace string
* @since v1-alpha4
*/
public static @NotNull String getStackTraceAsString(@NotNull StackTraceElement @NotNull [] stacktrace, boolean indent) {
StringBuilder output = new StringBuilder();
for (StackTraceElement element : stacktrace) {
if (!output.isEmpty())
output.append("\n");
if (indent)
output.append("\t");
output.append("at ").append(element);
}
return output.toString();
}
/**
* Converts the stacktrace of a throwable into a regular string.
*
* @param throwable throwable to derive the stacktrace from
* @param indent if all lines should be indented with a single {@code \t} character, like in regular stack traces
* @return converted stacktrace string
* @since v1-alpha4
*/
public static @NotNull String getStackTraceAsString(@NotNull Throwable throwable, boolean indent) {
return getStackTraceAsString(throwable.getStackTrace(), indent);
}
}

View file

@ -1,29 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//package de.staropensource.engine.base.utility.information;
/**
* Provides information about the environment
* ie. the operating system, paths, etc..
*
* @since v1-alpha8
*/
//public final class EnvironmentInformation {
//}

View file

@ -1,25 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Classes which can be used to retrieve information about the execution environment.
*
* @since v1-alpha0
*/
package de.staropensource.engine.base.utility.information;

View file

@ -1,26 +0,0 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* A namespace for various things,
* not really specified what though.
*
* @since v1-alpha5
*/
package de.staropensource.engine.dynamic;

View file

@ -0,0 +1,385 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.sosengine.base;
import de.staropensource.sosengine.base.annotations.EngineSubsystem;
import de.staropensource.sosengine.base.classes.SubsystemMainClass;
import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.sosengine.base.data.info.EngineInformation;
import de.staropensource.sosengine.base.data.versioning.StarOpenSourceVersioningSystem;
import de.staropensource.sosengine.base.events.EngineCrashEvent;
import de.staropensource.sosengine.base.events.EngineShutdownEvent;
import de.staropensource.sosengine.base.events.LogEvent;
import de.staropensource.sosengine.base.exceptions.UnmetDependenciesException;
import de.staropensource.sosengine.base.internal.events.InternalEngineShutdownEvent;
import de.staropensource.sosengine.base.internal.types.DependencySubsystemVector;
import de.staropensource.sosengine.base.logging.CrashHandler;
import de.staropensource.sosengine.base.logging.Logger;
import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.sosengine.base.types.CodePart;
import de.staropensource.sosengine.base.types.DependencyVector;
import de.staropensource.sosengine.base.types.immutable.ImmutableLinkedList;
import de.staropensource.sosengine.base.types.logging.LogIssuer;
import de.staropensource.sosengine.base.utility.DependencyResolver;
import de.staropensource.sosengine.base.utility.Miscellaneous;
import de.staropensource.sosengine.base.utility.PlaceholderEngine;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import java.util.*;
/**
* sos!engine management object.<br/>
* It is responsible for the base engine initialization.
*
* @see EngineConfiguration
* @since 1-alpha0
*/
@SuppressWarnings({ "unused", "JavadocDeclaration", "JavadocBlankLines" })
@EngineSubsystem
public final class Engine implements SubsystemMainClass {
/**
* Contains the class instance.
*
* @since 1-alpha0
*
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless the engine is uninitialized
* @since 1-alpha0
*/
@Getter
private static Engine instance = null;
/**
* Logger instance.
*
* @see LoggerInstance
* @since 1-alpha0
*/
@SuppressWarnings("NotNullFieldNotInitialized")
@NotNull
private LoggerInstance logger;
/**
* Contains a list of all registered subsystems.
* The list is sorted after initialization order.
*
* @since 1-alpha1
*
* -- GETTER --
* Returns a list of all registered subsystems.
* The list is sorted after initialization order.
*
* @return subsystem list
* @since 1-alpha1
*/
@NotNull
@Getter
private ImmutableLinkedList<@NotNull DependencySubsystemVector> subsystems = new ImmutableLinkedList<>();
/**
* Indicates if the engine is shutting down.
*
* @since 1-alpha1
*
* -- GETTER --
* Returns if the engine is shutting down.
*
* @return if the engine is shutting down
* @since 1-alpha1
*/
@Getter
private boolean shuttingDown = false;
/**
* Initializes the StarOpenSource Engine.
*
* @since 1-alpha0
*/
public Engine() {
// Only allow one instance
if (instance == null)
instance = this;
else
return;
long initTime = Miscellaneous.measureExecutionTime(() -> {
// Initialize variables
logger = new LoggerInstance(new LogIssuer(getClass(), CodePart.ENGINE));
// Initialize EngineConfiguration and load it
new EngineConfiguration();
EngineConfiguration.getInstance().loadConfiguration();
// Initialize classes
initializeClasses();
// Populate crash content
populateCrashContent();
// Precompute event listeners
precomputeEventListeners();
// Start threads
startThreads();
// Collect subsystems
collectSubsystems();
// Initialize subsystems
try {
initializeSubsystems();
} catch (Exception exception) {
logger.crash("Subsystem dependency resolution failed", exception);
}
});
logger.info("Initialized sos!engine v%engine_version% (commit %engine_git_commit_id_long%-%engine_git_branch%, dirty %engine_git_dirty%) in " + initTime + "ms");
}
/**
* Initializes all classes.
*
* @since 1-alpha0
*/
private void initializeClasses() {
// Sorted in rough order of dependence
new PlaceholderEngine();
EngineInformation.updateVariables();
}
/**
* This method populates the Crash Handler's content with the default set of content.
*
* @see CrashHandler#getCrashContent()
* @since 1-alpha0
*/
@SuppressWarnings("ExtractMethodRecommender")
private void populateCrashContent() {
// Issuer
Map<@NotNull String, @NotNull String> crashContentIssuer = new LinkedHashMap<>();
crashContentIssuer.put("Code part", "%issuer_code_part%");
crashContentIssuer.put("Classpath", "%issuer_path%");
crashContentIssuer.put("Additional information", "%issuer_info%");
crashContentIssuer.put("Message", "%issuer_message%");
// Engine -> Dependencies
Map<@NotNull String, @NotNull String> crashContentEngineDependencies = new LinkedHashMap<>();
crashContentEngineDependencies.put("Lombok", "%engine_dependency_lombok%");
crashContentEngineDependencies.put("Jetbrains Annotations", "%engine_dependency_jetbrains_annotations%");
crashContentEngineDependencies.put("Jansi", "%engine_dependency_jansi%");
crashContentEngineDependencies.put("Reflections", "%engine_dependencies_reflections%");
crashContentEngineDependencies.put("SLF4J", "%engine_dependencies_slf4j%");
crashContentEngineDependencies.put("LWJGL", "%engine_dependencies_lwjgl%");
// Engine -> Plugins
Map<@NotNull String, @NotNull String> crashContentEnginePlugins = new LinkedHashMap<>();
crashContentEnginePlugins.put("Shadow", "%engine_plugin_shadow%");
crashContentEnginePlugins.put("Lombok", "%engine_plugin_lombok%");
// Engine -> *
Map<@NotNull String, @NotNull Object> crashContentEngine = new LinkedHashMap<>();
crashContentEngine.put("Version", "%engine_version%");
crashContentEngine.put("Dependencies", crashContentEngineDependencies);
crashContentEngine.put("Plugins", crashContentEnginePlugins);
// JVM -> Implementation
Map<@NotNull String, @NotNull String> crashContentJvmImplementation = new LinkedHashMap<>();
crashContentJvmImplementation.put("Name", "%jvm_implementation_name%");
crashContentJvmImplementation.put("Version", "%jvm_implementation_version%");
crashContentJvmImplementation.put("Vendor", "%jvm_implementation_vendor%");
// JVM -> *
Map<@NotNull String, @NotNull Object> crashContentJvm = new LinkedHashMap<>();
crashContentJvm.put("Java Version", "%jvm_java%");
crashContentJvm.put("Implementation", crashContentJvmImplementation);
crashContentJvm.put("Arguments", "%jvm_arguments%");
// Operating system
Map<@NotNull String, @NotNull String> crashContentOS = new LinkedHashMap<>();
crashContentOS.put("Time", "%time_hour%:%time_minute%:%time_second% (%time_zone%, UNIX Epoch: %time_epoch%)");
crashContentOS.put("Date", "%date_day%.%date_month%.%date_year%");
// Add to crash handler
CrashHandler.getCrashContent().put("Issuer", crashContentIssuer);
CrashHandler.getCrashContent().put("Engine", crashContentEngine);
CrashHandler.getCrashContent().put("Java Virtual Machine", crashContentJvm);
CrashHandler.getCrashContent().put("Operating system", crashContentOS);
CrashHandler.getCrashContent().put("Stacktrace", "%stacktrace%");
}
/**
* Precomputes all base engine events.
*
* @since 1-alpha0
*/
private void precomputeEventListeners() {
// Internal events
EventHelper.precomputeEventListeners(InternalEngineShutdownEvent.class);
// General events
EventHelper.precomputeEventListeners(EngineCrashEvent.class);
EventHelper.precomputeEventListeners(EngineShutdownEvent.class);
EventHelper.precomputeEventListeners(LogEvent.class);
}
/**
* Collects all subsystems by their {@link EngineSubsystem} annotation.
*
* @since 1-alpha1
*/
private void collectSubsystems() {
ArrayList<@NotNull DependencySubsystemVector> subsystemsMutable = new ArrayList<>();
// Scan entire classpath using the Reflections library
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
.setScanners(Scanners.TypesAnnotated)
);
// Get annotated methods
Set<@NotNull Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(EngineSubsystem.class);
// Initialize classes, get dependency vector and add to 'subsystemsMutable'
for (Class<?> clazz : annotatedClasses) {
try {
// Create new instance
Object initializedClassRaw = clazz.getDeclaredConstructor().newInstance();
SubsystemMainClass initializedClass = null;
// Check if class implements SubsystemMainClass
if (initializedClassRaw instanceof SubsystemMainClass subsystemInstance)
initializedClass = subsystemInstance;
else
logger.crash("Failed to initialize subsystem " + clazz.getName() + ": Does not implement " + SubsystemMainClass.class.getName());
//noinspection DataFlowIssue // the crash call will prevent a NullPointerException
subsystemsMutable.add(new DependencySubsystemVector(initializedClass.getDependencyVector(), initializedClass));
} catch (Exception exception) {
logger.crash("Failed to initialize subsystem " + clazz.getName() + ": Method invocation error", exception);
}
}
// Update 'subsystems'
subsystems = new ImmutableLinkedList<>(subsystemsMutable);
}
/**
* Initializes all subsystems.
*
* @throws Exception exceptions thrown by the {@link DependencyResolver}
* @since 1-alpha1
*/
private void initializeSubsystems() throws Exception {
DependencyResolver resolver = new DependencyResolver();
LinkedList<DependencySubsystemVector> order = new LinkedList<>();
// Add vectors
resolver.addVectors(subsystems);
// Resolve dependencies and get order
logger.verb("Resolving subsystem dependencies");
try {
for (DependencyVector vector : resolver.resolve().getOrder()) // smol workaround
order.add((DependencySubsystemVector) vector);
} catch (Throwable throwable) {
if (throwable instanceof UnmetDependenciesException)
((UnmetDependenciesException) throwable).getUnmetDependencies();
logger.crash("An error occurred trying to resolve subsystem dependencies: " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage()));
throw throwable;
}
// Initialize subsystems
logger.info("Initializing engine subsystems");
for (DependencySubsystemVector vector : subsystems) {
logger.verb("Initializing subsystem " + vector.getMainClass().getClass().getName());
try {
vector.getMainClass().initializeSubsystem();
} catch (Throwable throwable) {
logger.crash("An error occurred trying to initialize subsystem " + vector.getMainClass().getClass().getName() + ": " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage()));
throw throwable;
}
}
// Update 'subsystems'
subsystems = new ImmutableLinkedList<>(order);
}
/**
* Starts engine threads.
*
* @since 1-alpha1
*/
public void startThreads() {
Logger.startLoggingThread();
}
/**
* Shuts the engine and JVM down.
*
* @param exitCode code to exit with, from 0-255
* @since 1-alpha0
*/
public synchronized void shutdown(@Range(from = 0, to = 255) int exitCode) {
logger.info("Shutting engine down");
shuttingDown = true;
logger.verb("Notifiying classes about shutdown");
new EngineShutdownEvent().callEvent();
logger.verb("Notifying subsystems about shutdown");
new InternalEngineShutdownEvent().callEvent();
logger.verb("Shutting down JVM with code " + exitCode);
Logger.flushLogMessages(); // Flush all log messages before exiting
Runtime.getRuntime().exit(exitCode);
}
/** {@inheritDoc} */
@Override
public void initializeSubsystem() {}
/**
* Returns the {@link DependencyVector} for this subsystem.
*
* @see DependencyVector
* @since 1-alpha1
*/
@NotNull
@Override
public DependencyVector getDependencyVector() {
return new DependencyVector("engine", StarOpenSourceVersioningSystem.class, EngineInformation.getVersioningString());
}
/**
* Shuts the engine and JVM down.
*
* @since 1-alpha0
*/
public synchronized void shutdown() {
shutdown(0);
}
}

View file

@ -0,0 +1,397 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.sosengine.base;
import de.staropensource.sosengine.base.classes.SubsystemConfiguration;
import de.staropensource.sosengine.base.logging.CrashHandler;
import de.staropensource.sosengine.base.logging.Logger;
import de.staropensource.sosengine.base.types.CodePart;
import de.staropensource.sosengine.base.types.logging.LogIssuer;
import de.staropensource.sosengine.base.types.logging.LogLevel;
import de.staropensource.sosengine.base.utility.converter.AnsiShortcodeConverter;
import de.staropensource.sosengine.base.utility.parser.PropertyParser;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Properties;
/**
* Provides the base engine configuration.
* <p>
* This class does not only provide engine settings but is also
* responsible for loading them into memory from {@link Properties} objects.
* <p>
* Now you might ask why we didn't go with the string-based approach.
* The answer is simple: It's a maintenance and documentation burden.
* Having various settings strings scattered across many classes will cause
* trouble at some point, which will cause some strings to be undocumented
* or have an inconsistent naming scheme. Containing settings as variables in
* one centralized place mitigates this.
*
* @since 1-alpha0
*/
@SuppressWarnings({ "unused", "JavadocDeclaration", "JavadocBlankLines" })
@Getter
public final class EngineConfiguration implements SubsystemConfiguration {
/**
* Contains the class instance.
*
* @since 1-alpha0
*
* -- GETTER --
* Returns the class instance.
*
* @return class instance unless {@link Engine} is uninitialized
* @since 1-alpha0
*/
@Getter
private static EngineConfiguration instance;
/**
* Defines the group every property must start with to be recognized as a subsystem configuration setting.
*
* @since 1-alpha0
*
* -- GETTER --
* Returns the group that every property must start with to be recognized as a subsystem configuration setting.
*
* @return property group
* @since 1-alpha0
*/
@NotNull
@Getter
private static final String group = "sosengine.base.";
/**
* If enabled, allows for unintentional behaviour and excess logging.<br/>
* Unless you want to debug or work on a sensitive part of the engine, don't enable this!
*
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code debug}.
*
* @return variable value
* @see EngineConfiguration#debug
* @since 1-alpha0
*/
private boolean debug;
/**
* If enabled, all called events will be logged.
*
* @see de.staropensource.sosengine.base.classes.helpers.EventHelper#logCall(Class, Object...)
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code debugEvents}.
*
* @return variable value
* @see EngineConfiguration#debugEvents
* @since 1-alpha0
*/
private boolean debugEvents;
/**
* If enabled, very verbose messages about the {@link AnsiShortcodeConverter}'s internals will be printed.<br/>
* Don't enable unless you want to work on it.
*
* @see AnsiShortcodeConverter
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code debugShortcodeConverter}.
*
* @return variable value
* @see EngineConfiguration#debugShortcodeConverter
* @since 1-alpha0
*/
private boolean debugShortcodeConverter;
/**
* If enabled, invalid shortcodes will be logged by the {@link AnsiShortcodeConverter}.
* The message will be printed as a silent warning.
*
* @see AnsiShortcodeConverter
* @see EngineConfiguration#loggerLevel
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code errorShortcodeConverter}.
*
* @return variable value
* @see EngineConfiguration#errorShortcodeConverter
* @since 1-alpha0
*/
private boolean errorShortcodeConverter;
/**
* Determines which logger levels are allowed by setting the minimum logger level.
*
* @see Logger
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code loggerLevel}.
*
* @return variable value
* @see EngineConfiguration#loggerLevel
* @since 1-alpha0
*/
private LogLevel loggerLevel;
/**
* Contains the logging template used for creating log messages.
*
* @see Logger
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code loggerTemplate}
*
* @return variable value
* @see EngineConfiguration#loggerTemplate
* @since 1-alpha0
*/
private String loggerTemplate;
/**
* If enabled, the JVM will immediately shutdown on an engine crash. This will prevent shutdown hooks from executing.<br/>
* Note: This will also prevent Jansi and potentially other libraries from removing temporary native libraries at shutdown.
*
* @see CrashHandler
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code loggerImmediateShutdown}.
*
* @return variable value
* @see EngineConfiguration#loggerImmediateShutdown
* @since 1-alpha0
*/
private boolean loggerImmediateShutdown;
/**
* If enabled, will force the {@link Logger} and {@link CrashHandler} to use <a href="https://www.man7.org/linux/man-pages/man3/stderr.3.html">the standard output</a>
* instead of <a href="https://www.man7.org/linux/man-pages/man3/stderr.3.html">the standard error</a> for logging {@code ERROR} and {@code CRASH}.
*
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code loggerForceStandardOutput}.
*
* @return variable value
* @see EngineConfiguration#loggerForceStandardOutput
* @since 1-alpha0
*/
private boolean loggerForceStandardOutput;
/**
* Determines how fast the logging thread will poll for queued messages.
* Only applies if {@code optimizeLogging} is turned on.
*
* @see EngineConfiguration#optimizeLogging
* @since 1-alpha1
*
* -- GETTER --
* Gets the value for {@code loggerForceStandardOutput}.
*
* @return variable value
* @see EngineConfiguration#loggerForceStandardOutput
* @since 1-alpha1
*/
private int loggerPollingSpeed;
/**
* If enabled, will makes the {@link Logger} work asynchronous, in a separate platform thread.
* Don't disable unless you want your application to run <b>extremely</b> slowly.
*
* @see EngineConfiguration#loggerPollingSpeed
* @see Thread
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code optimizeLogging}.
*
* @return variable value
* @see EngineConfiguration#optimizeLogging
* @since 1-alpha0
*/
private boolean optimizeLogging;
/**
* If enabled, will make all events asynchronous, in separate virtual threads.
* Don't disable unless you want your application to run slower.
*
* @see VirtualThread
* @since 1-alpha0
*
* -- GETTER --
* Gets the value for {@code optimizeEvents}.
*
* @return variable value
* @see EngineConfiguration#optimizeEvents
* @since 1-alpha0
*/
private boolean optimizeEvents;
/**
* Constructs this class.
*
* @see Engine
* @since 1-alpha0
*/
public EngineConfiguration() {
// Only allow one instance
if (instance == null)
instance = this;
else
Logger.crash(new LogIssuer(getClass(), CodePart.ENGINE), "Tried initializing " + getClass().getName() + " twice");
// Load default configuration
loadDefaultConfiguration();
}
/** {@inheritDoc} */
public synchronized void loadConfiguration(@NotNull Properties properties) {
// Define variables
PropertyParser parser = new PropertyParser(properties);
// Loop through all properties
for (String property : properties.stringPropertyNames()) {
// Check if property name starts with group
if (!property.startsWith(group)) continue;
// Skip to important stuff
property = property.substring(group.length());
// Overwrite matching settings
try {
switch (property) {
case "debug" -> debug = parser.getBoolean(group + property);
case "debugEvents" -> debugEvents = parser.getBoolean(group + property);
case "debugShortcodeConverter" -> debugShortcodeConverter = parser.getBoolean(group + property);
case "errorShortcodeConverter" -> errorShortcodeConverter = parser.getBoolean(group + property);
case "loggerLevel" -> {
try {
loggerLevel = LogLevel.valueOf(parser.getString(group + property).toUpperCase());
} catch (IllegalArgumentException ignored) {
System.out.println("Logger level " + parser.getString(group + property) + " is not valid");
}
}
case "loggerTemplate" -> loggerTemplate = parser.getString(group + property);
case "loggerImmediateShutdown" -> loggerImmediateShutdown = parser.getBoolean(group + property);
case "loggerForceStandardOutput" -> loggerForceStandardOutput = parser.getBoolean(group + property);
case "loggerPollingSpeed" -> loggerPollingSpeed = parser.getInteger(group + property, true);
case "optimizeLogging" -> optimizeLogging = parser.getBoolean(group + property);
case "optimizeEvents" -> optimizeEvents = parser.getBoolean(group + property);
}
} catch (NullPointerException ignored) {}
}
// Disable all debugging switches if 'debug' is disabled
if (!debug) {
debugEvents = false;
debugShortcodeConverter = false;
}
}
/** {@inheritDoc} */
public synchronized void loadConfiguration() {
loadConfiguration(System.getProperties());
}
/** {@inheritDoc} */
public synchronized void loadDefaultConfiguration() {
debug = false;
debugEvents = false;
debugShortcodeConverter = false;
errorShortcodeConverter = true;
loggerLevel = LogLevel.INFORMATIONAL;
loggerTemplate = "%log_color_primary%[%time_hour%:%time_minute%:%time_second%] [%log_level% %log_path%%log_info%] %log_color_secondary%%log_message%<reset>";
loggerImmediateShutdown = false;
loggerForceStandardOutput = false;
loggerPollingSpeed = 5;
optimizeLogging = true;
optimizeEvents = true;
}
/** {@inheritDoc} */
@Nullable
public Object getSetting(@NotNull String setting) {
switch (setting) {
case "debug" -> {
return debug;
}
case "debugEvents" -> {
return debugEvents;
}
case "debugShortcodeConverter" -> {
return debugShortcodeConverter;
}
case "errorShortcodeConverter" -> {
return errorShortcodeConverter;
}
case "loggerLevel" -> {
return loggerLevel;
}
case "loggerTemplate" -> {
return loggerTemplate;
}
case "loggerImmediateShutdown" -> {
return loggerImmediateShutdown;
}
case "loggerForceStandardOutput" -> {
return loggerForceStandardOutput;
}
case "loggerPollingSpeed" -> {
return loggerPollingSpeed;
}
case "optimizeLogging" -> {
return optimizeLogging;
}
case "optimizeEvents" -> {
return optimizeEvents;
}
default -> {
return null;
}
}
}
/**
* Clears {@code instance}. Used in unit tests.
*
* @since 1-alpha1
*/
private static void clearInstance() {
instance = null;
}
}

View file

@ -1,6 +1,6 @@
/* /*
* STAROPENSOURCE ENGINE SOURCE FILE * STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors * Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3 * Licensed under the GNU Affero General Public License v3
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -17,19 +17,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package de.staropensource.engine.base.annotation; package de.staropensource.sosengine.base.annotations;
import de.staropensource.engine.base.implementable.SubsystemClass;
import java.lang.annotation.*; import java.lang.annotation.*;
/** /**
* Marks a class as a subsystem main class. * This annotation marks a class as a subsystem main class.
* Make sure your subsystem implements {@link SubsystemClass}.
* *
* @see SubsystemClass * @since 1-alpha1
* @since v1-alpha1
*/ */
@SuppressWarnings("unused")
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Documented @Documented

View file

@ -1,6 +1,6 @@
/* /*
* STAROPENSOURCE ENGINE SOURCE FILE * STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors * Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3 * Licensed under the GNU Affero General Public License v3
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -17,39 +17,37 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package de.staropensource.engine.base.annotation; package de.staropensource.sosengine.base.annotations;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.type.EventPriority; import de.staropensource.sosengine.base.types.EventPriority;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.lang.annotation.*; import java.lang.annotation.*;
/** /**
* Marks a method as an event listener, allowing it * This annotation allows methods to listen on certain events.
* to respond to an events when it is emitted.
* *
* @since v1-alpha0 * @since 1-alpha0
*/ */
@SuppressWarnings("unused")
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Documented @Documented
public @interface EventListener { public @interface EventListener {
/** /**
* Specifies the event to listen for. * The event to listen for.
* *
* @return event to listen on * @return the event the method listens for
* @see Event
* @since v1-alpha0
*/ */
@NotNull Class<? extends Event> event(); @NotNull
Class<? extends Event> event();
/** /**
* Specifies the priority of the event. * The priority of the event.
* *
* @return event priority * @return the event priority
* @see EventPriority
* @since v1-alpha0
*/ */
@NotNull EventPriority priority() default EventPriority.DEFAULT; @NotNull
EventPriority priority() default EventPriority.DEFAULT;
} }

View file

@ -0,0 +1,26 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Contains annotations that are used by the engine
* to dynamically invoke methods or register classes.
*
* @since 1-alpha0
*/
package de.staropensource.sosengine.base.annotations;

View file

@ -1,6 +1,6 @@
/* /*
* STAROPENSOURCE ENGINE SOURCE FILE * STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors * Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3 * Licensed under the GNU Affero General Public License v3
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -17,21 +17,17 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package de.staropensource.engine.base.implementable; package de.staropensource.sosengine.base.classes;
import de.staropensource.engine.base.implementable.helper.EventHelper;
/** /**
* Represents an event. * Represents an event.
* *
* @see EventHelper * @since 1-alpha0
* @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public interface Event { public interface Event {
/** /**
* Emits the event and calls all event listeners. * Calls the event and notifies all annotated methods.
*
* @since v1-alpha0
*/ */
void callEvent(); void callEvent();
} }

View file

@ -0,0 +1,67 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.sosengine.base.classes;
import de.staropensource.sosengine.base.types.logging.LogIssuer;
import de.staropensource.sosengine.base.types.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
/**
* Interface for implementing custom logger implementations, called by {@link de.staropensource.sosengine.base.logging.Logger}.
*
* @see de.staropensource.sosengine.base.logging.Logger
* @since 1-alpha0
*/
@SuppressWarnings({ "unused" })
public interface LoggerImpl {
/**
* Run before placeholders are replaced.
*
* @param level log level
* @param logIssuer log issuer
* @param message log message
* @return new log message
* @since 1-alpha0
*/
@NotNull
String prePlaceholder(@NotNull LogLevel level, @NotNull LogIssuer logIssuer, @NotNull String message);
/**
* Run after placeholders are replaced.
*
* @param level log level
* @param logIssuer log issuer
* @param format log format
* @return new log format
* @since 1-alpha0
*/
@NotNull
String postPlaceholder(@NotNull LogLevel level, @NotNull LogIssuer logIssuer, @NotNull String format);
/**
* Responsible for printing the finalized log message.
*
* @param level log level
* @param logIssuer log issuer
* @param format finalized log format
* @since 1-alpha0
*/
void print(@NotNull LogLevel level, @NotNull LogIssuer logIssuer, @NotNull String format);
}

View file

@ -1,6 +1,6 @@
/* /*
* STAROPENSOURCE ENGINE SOURCE FILE * STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Authors * Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3 * Licensed under the GNU Affero General Public License v3
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@ -17,24 +17,35 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package de.staropensource.engine.base.implementable; package de.staropensource.sosengine.base.classes;
import de.staropensource.engine.base.utility.PlaceholderEngine; import de.staropensource.sosengine.base.utility.PlaceholderEngine;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Interface for implementing placeholders. * Interface for implementing placeholders.
* *
* @see PlaceholderEngine * @see PlaceholderEngine
* @since v1-alpha0 * @since 1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public interface Placeholder { public interface Placeholder {
/** /**
* Replaces the placeholder with content. * Returns the placeholder's name.
*
* @return the placeholder name
* @since 1-alpha0
*/
@NotNull
String getName();
/**
* Replaces the placeholder with it's appropriate content.
* *
* @param text text to process * @param text text to process
* @return processed text * @return the processed text
* @since v1-alpha2 * @since 1-alpha0
*/ */
@NotNull String replace(@NotNull String text); @NotNull
String replace(@NotNull String text);
} }

View file

@ -0,0 +1,254 @@
/*
* STAROPENSOURCE ENGINE SOURCE FILE
* Copyright (c) 2024 The StarOpenSource Engine Contributors
* Licensed under the GNU Affero General Public License v3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.staropensource.sosengine.base.classes;
import de.staropensource.sosengine.base.EngineConfiguration;
import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.sosengine.base.types.CodePart;
import de.staropensource.sosengine.base.types.logging.LogIssuer;
import lombok.Getter;
import org.fusesource.jansi.Ansi;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* The base skeleton for implementing a shortcode parser.
* <p>
* The following shortcodes are available and can be used:
* <ul>
* <li>reset</li>
* <li>fg:[black,red,green,yellow,blue,magenta,cyan,white]</li>
* <li>bg:[black,red,green,yellow,blue,magenta,cyan,white]</li>
* <li>bold</li>
* <li>italic</li>
* <li>strikethrough</li>
* <li>underline</li>
* <li>blink</li>
* <li>negative</li>
* </ul>
*
* @since 1-alpha1
*/
@SuppressWarnings({ "unused", "JavadocDeclaration", "JavadocBlankLines" })
public abstract class ShortcodeParserSkeleton {
/**
* Logger instance.
*
* @see LoggerInstance
* @since 1-alpha1
*/
protected final LoggerInstance logger = new LoggerInstance(new LogIssuer(getClass(), CodePart.ENGINE));
/**
* A list of components the parsed string is made out of.
*
* @since 1-alpha1
*
* -- GETTER --
* Returns a list of components the parsed string is made out of.
*
* @return component list of the parsed string
* @since 1-alpha1
*/
@NotNull
@Getter
protected final List<String> components;
/**
* Constructs this class.
*
* @param string string to parse
* @since 1-alpha1
*/
public ShortcodeParserSkeleton(@NotNull String string) {
components = parse(string);
}
/**
* Parses an input string and spits out all of it's components.
*
* @param string string to parse
* @return list of components
* @see EngineConfiguration#errorShortcodeConverter
* @since 1-alpha1
*/
@NotNull
private List<@NotNull String> parse(@NotNull String string) {
List<String> components = new ArrayList<>(); // List of components
boolean tagActive = false; // Indicates that a tag is being parsed
String part = ""; // Current part. May be a tag, may be regular text
// Iterate through every character
for (char character : string.toCharArray()) {
if (tagActive) {
// A tag is being parsed
if (character == '>') {
// Tag is ending, disable tag parsing
tagActive = false;
// fg:*
if (part.startsWith("fg:")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
try {
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=fg data=" + part.substring(3).toUpperCase() + " enum=" + Ansi.Color.valueOf(part.substring(3).toUpperCase()));
} catch (IllegalArgumentException ignored) {
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=fg data=" + part.substring(3).toUpperCase() + " enum=<invalid>");
}
components.add("COLOR:FOREGROUND:" + part.substring(3).toUpperCase());
}
// bg:*
else if (part.startsWith("bg:")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
try {
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=bg data=" + part.substring(3).toUpperCase() + " enum=" + Ansi.Color.valueOf(part.substring(3).toUpperCase()));
} catch (IllegalArgumentException ignored) {
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=bg data=" + part.substring(3).toUpperCase() + " enum=<invalid>");
}
components.add("COLOR:BACKGROUND:" + part.substring(3).toUpperCase());
}
// bold
else if (part.equals("bold")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=bold");
// Insert attribute
components.add("ATTRIBUTE:BOLD");
}
// italic
else if (part.equals("italic")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=italic");
// Insert attribute
components.add("ATTRIBUTE:ITALIC");
}
// strikethrough
else if (part.equals("strikethrough")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=strikethrough");
// Insert attribute
components.add("ATTRIBUTE:STRIKETHROUGH");
}
// underline
else if (part.equals("underline")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=underline");
// Insert attribute
components.add("ATTRIBUTE:UNDERLINE");
}
// underline
else if (part.equals("blink")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=blink");
// Insert attribute
components.add("ATTRIBUTE:BLINK");
}
// underline
else if (part.equals("negative")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=negative");
// Insert attribute
components.add("ATTRIBUTE:NEGATIVE");
}
// reset
else if (part.equals("reset")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=reset");
// Insert reset
components.add("RESET");
}
// error case
else {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " invalidtag=" + part);
// Complain about invalid shortcode
if (EngineConfiguration.getInstance().isErrorShortcodeConverter())
logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text
components.add("TEXT:" + "<" + part + ">");
}
// Empty 'part'
part = "";
} else
// Tag has not ended yet, add character to 'part'
//noinspection StringConcatenationInLoop // It bloats the code to do it with StringBuilder
part += character;
} else {
// Regular text is being parsed
if (character == '<') {
if (!part.isEmpty()) {
// Tag is starting, insert previous text
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " text=" + part);
components.add("TEXT:" + part);
part = "";
}
tagActive = true; // Enable tag processing
} else
// Regular text, add character to 'part'
//noinspection StringConcatenationInLoop // It bloats the code to do it with StringBuilder
part += character;
}
}
// Processing ended, insert leftover text
if (!part.isEmpty()) {
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " endtext=" + part);
components.add("TEXT:" + part);
}
return components;
}
}

Some files were not shown because too many files have changed in this diff Show more