Compare commits

..

19 commits

Author SHA1 Message Date
e1fd6a81af
Ensure consistent artifact naming scheme
Some checks failed
build-and-test / build (pull_request) Successful in 1m35s
build-and-test / generate-javadoc (pull_request) Has been cancelled
build-and-test / test (pull_request) Has been cancelled
2024-08-18 18:09:45 +02:00
ccb107ee80
[no ci] Rename step 2024-08-18 17:55:57 +02:00
c2e4a5c9e5
Fix javadoc-combined upload step 2024-08-18 17:52:07 +02:00
535a290e6f
Add generate-javadoc job 2024-08-18 17:47:55 +02:00
7bc23e43f5
Fix library and source jar upload 2024-08-18 17:30:15 +02:00
294137603f
Add test job, update build job 2024-08-18 17:01:49 +02:00
fbbf7094c7
Switch to java flavour 2024-08-18 17:01:28 +02:00
c8cf0d7437
[no ci] Use one-time daemon 2024-08-18 16:51:38 +02:00
a98cc53b41
Migrate to actions-docker 2024-08-18 16:50:25 +02:00
479c71f329
OH SORRY it's gradlew 2024-08-18 14:41:18 +02:00
77fd061334
Add git package 2024-08-18 14:39:30 +02:00
50862c38d7
dum 2024-08-18 14:37:37 +02:00
92df303779
Add node package for actions 2024-08-18 14:35:55 +02:00
54f582eb72
Revert "Change runs-on"
This reverts commit 2d9dccedca.
2024-08-18 14:17:13 +02:00
34c4e86e2b
Rename artifact jobs 2024-08-18 14:16:23 +02:00
f2aef64ab0
Add set -x 2024-08-18 14:11:30 +02:00
bc461b25e3
Fix wrong pacman.conf location 2024-08-18 14:11:01 +02:00
2d9dccedca
Change runs-on 2024-08-18 14:08:04 +02:00
039f18774a
Does this work? 2024-08-18 14:06:25 +02:00
375 changed files with 11459 additions and 13129 deletions

View file

@ -12,26 +12,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4 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 - name: Compile
run: ./gradlew --no-daemon jar javadocJar sourceJar 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 - name: Upload library JARs
uses: https://code.forgejo.org/forgejo/upload-artifact@v4 uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with: with:
@ -62,26 +44,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4 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 - name: Generate javadoc
run: ./gradlew --no-daemon javadoc javadocAll 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 - name: Upload separate javadoc
uses: https://code.forgejo.org/forgejo/upload-artifact@v4 uses: https://code.forgejo.org/forgejo/upload-artifact@v4
with: with:
@ -103,23 +67,5 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4 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 - name: Run tests
run: ./gradlew --no-daemon test 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 }}-

3
.gitignore vendored
View file

@ -42,6 +42,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

@ -16,12 +16,11 @@ The StarOpenSource Engine is under heavy development and is extremely unstable.
- [Code style](#code-style) - [Code style](#code-style)
- [Pull request guidelines](#pull-request-guidelines) - [Pull request guidelines](#pull-request-guidelines)
- [Making your first contribution](#making-your-first-contribution) - [Making your first contribution](#making-your-first-contribution)
- [Gradle properties](#gradle-properties)
## About ## About
### ... the engine ### ... 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 StarOpenSource 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 a few closely-related things.
\ \
Not only that. The engine also features various useful classes, interfaces and methods making development fun and simpler, while being lightweight. Not only that. The engine also features various useful classes, interfaces and methods making development fun and simpler, while being lightweight.
### ... the repository ### ... the repository
@ -51,10 +50,10 @@ We recommend and are using [IntelliJ IDEA Community Edition](https://github.com/
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 and code for a good understanding on how we'd like code to be written.
Here's a quick rundown on the most important things: Here's a quick rundown on the most important things:
- Document EVERYTHING. Every single class, field and method, even if private. - Document EVERYTHING. Every single class, field and method, even if private.
- Make comments about your code, unless it's extremely simple and easy to understand. - Make comments about your code, unless it's extremly simple and easy to understand.
- Make sure to add and update `@since` in javadoc comments (update if the javadoc changes a good amount). - 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. - 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. - Make sure every field and method has a newline to seperate it.
- Files must end with a newline or cats might get angry. - Files must end with a newline or cats might get angry.
- Use your brain. - Use your brain.
### Pull request guidelines ### Pull request guidelines
@ -66,24 +65,3 @@ Before creating a pull request, make sure you've:
- 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,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
@ -16,7 +16,6 @@
* You should have received a copy of the GNU Affero General Public License * 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/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
// Plugins // Plugins
plugins { plugins {
id("java") id("java")
@ -24,8 +23,9 @@ plugins {
id("maven-publish") id("maven-publish")
} }
// Dependencies // Project dependencies
dependencies { dependencies {
// -> Runtime <-
// Lombok // Lombok
compileOnly("org.projectlombok:lombok:${dependencyLombok}") compileOnly("org.projectlombok:lombok:${dependencyLombok}")
annotationProcessor("org.projectlombok:lombok:${dependencyLombok}") annotationProcessor("org.projectlombok:lombok:${dependencyLombok}")
@ -33,11 +33,36 @@ dependencies {
// JetBrains Annotations // JetBrains Annotations
compileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}") compileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}")
// Jansi // ANSI support
implementation("org.fusesource.jansi:jansi:${dependencyJansi}") implementation("org.fusesource.jansi:jansi:${dependencyJansi}")
// Project // Project
implementation(project(":base")) implementation(project(":base"))
// -> Testing <-
// Jetbrains Annotations
testCompileOnly("org.jetbrains:annotations:${dependencyJetbrainsAnnotations}")
// JUnit
testImplementation(platform("org.junit:junit-bom:${dependencyJunit}"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
// Fix delombok task
delombok.doFirst {
File target = file("${project.projectDir}/src/main/module-info.java")
File source = file("${project.projectDir}/src/main/java/module-info.java")
target.delete()
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")
target.delete()
source.renameTo(target)
} }
// Javadoc configuration // Javadoc configuration
@ -54,7 +79,6 @@ javadoc {
setMemberLevel(JavadocMemberLevel.PUBLIC) // Only display public stuff setMemberLevel(JavadocMemberLevel.PUBLIC) // Only display public stuff
setOverview("src/main/javadoc/overview.html") // We want a custom overview page to greet the visitor setOverview("src/main/javadoc/overview.html") // We want a custom overview page to greet the visitor
setLocale("en_US") // setLocale("en_US") //
addStringOption("Xwerror", "-quiet") // Fail build on warning
setJFlags([ setJFlags([
"-Duser.language=en_US" // See above "-Duser.language=en_US" // See above
@ -63,6 +87,19 @@ javadoc {
} }
} }
// Unit testing configuration
test {
useJUnitPlatform()
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 // Include javadoc and source jar during publishing
java { java {
withJavadocJar() withJavadocJar()
@ -75,7 +112,7 @@ publishing {
repositories { repositories {
maven { maven {
name = "staropensource" name = "staropensource"
url = uri("https://mvn.staropensource.de/engine") url = uri("https://mvn.staropensource.de/sosengine")
credentials(org.gradle.api.credentials.PasswordCredentials) credentials(org.gradle.api.credentials.PasswordCredentials)
authentication { authentication {
//noinspection GroovyAssignabilityCheck //noinspection GroovyAssignabilityCheck
@ -94,19 +131,3 @@ publishing {
} }
} }
} }
// Fix delombok task
delombok.doFirst {
File target = file("${project.projectDir}/src/main/module-info.java")
File source = file("${project.projectDir}/src/main/java/module-info.java")
target.delete()
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")
target.delete()
source.renameTo(target)
}

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

@ -0,0 +1,75 @@
/*
* 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.ansi;
import de.staropensource.sosengine.base.EngineConfiguration;
import de.staropensource.sosengine.base.classes.LoggerImplementation;
import de.staropensource.sosengine.base.logging.Logger;
import de.staropensource.sosengine.base.types.logging.LogLevel;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Prints colored log output using the Jansi library.
*
* @see Logger
* @see LoggerImplementation
* @since v1-alpha2
*/
@SuppressWarnings({ "unused" })
public class AnsiLoggerImplementation implements LoggerImplementation {
/**
* Constructs this class.
*
* @since v1-alpha2
*/
public AnsiLoggerImplementation() {}
/** {@inheritDoc} */
@Override
public @NotNull String prePlaceholder(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @NotNull String format) {
return format; // No modifications necessary
}
/** {@inheritDoc} */
@Override
public @NotNull String postPlaceholder(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @NotNull String format) {
return format; // No modifications necessary
}
/** {@inheritDoc} */
@Override
@SuppressWarnings({ "resource" }) // Using try-with-resources will cause issues here
public void print(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @NotNull String format) {
// Convert to Ansi
Ansi output = new AnsiShortcodeConverter(format, true).getAnsi();
// Print message
if (level == LogLevel.ERROR || level == LogLevel.CRASH)
if (EngineConfiguration.getInstance().isLoggerForceStandardOutput())
AnsiConsole.out().println(output);
else
AnsiConsole.err().println(output);
else
AnsiConsole.out().println(output);
}
}

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,33 +17,30 @@
* 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.ansi; package de.staropensource.sosengine.ansi;
import de.staropensource.engine.base.implementable.ShortcodeParser; import de.staropensource.sosengine.base.classes.ShortcodeParserSkeleton;
import de.staropensource.engine.base.exception.ParserException; import de.staropensource.sosengine.base.exceptions.ParserException;
import org.fusesource.jansi.Ansi; import org.fusesource.jansi.Ansi;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
/** /**
* Implementation of the {@link ShortcodeParser} class * Converts shortcodes such as {@code <bold>} or {@code <blink>} into a usable {@link Ansi} escape sequence.
* with ANSI support using the Jansi library.
* *
* @see ShortcodeParser * @see ShortcodeParserSkeleton
* @since v1-alpha8 * @since v1-alpha2
*/ */
public final class AnsiShortcodeParser extends ShortcodeParser { @SuppressWarnings({ "unused" })
public final class AnsiShortcodeConverter extends ShortcodeParserSkeleton {
/** /**
* Creates and initializes an instance of this class. * Constructs this class.
* *
* @param string string to convert * @param string string to convert
* @param ignoreInvalidEscapes will ignore invalid escapes and print treat them like regular text * @param ignoreInvalidEscapes will ignore invalid escapes and print treat them like regular text
* @throws ParserException when parsing failed * @throws ParserException when parsing failed
* @since v1-alpha2 * @since v1-alpha2
*/ */
public AnsiShortcodeParser(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException { public AnsiShortcodeConverter(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
super(string, ignoreInvalidEscapes); super(string, ignoreInvalidEscapes);
} }
@ -55,13 +52,11 @@ public final class AnsiShortcodeParser extends ShortcodeParser {
*/ */
public @NotNull Ansi getAnsi() { public @NotNull Ansi getAnsi() {
Ansi ansi = Ansi.ansi(); Ansi ansi = Ansi.ansi();
Set<@NotNull String> status = new HashSet<>();
for (String component : components) for (String component : components)
if (component.equals("RESET")) { if (component.equals("RESET"))
ansi.a(Ansi.Attribute.RESET); ansi.a(Ansi.Attribute.RESET);
status.clear(); else if (component.startsWith("TEXT:"))
} else if (component.startsWith("TEXT:"))
ansi.a(component.substring(5)); ansi.a(component.substring(5));
else if (component.startsWith("COLOR:")) else if (component.startsWith("COLOR:"))
if (component.startsWith("COLOR:FOREGROUND:")) if (component.startsWith("COLOR:FOREGROUND:"))
@ -69,38 +64,18 @@ public final class AnsiShortcodeParser extends ShortcodeParser {
else if (component.startsWith("COLOR:BACKGROUND:")) else if (component.startsWith("COLOR:BACKGROUND:"))
ansi.bg(Ansi.Color.valueOf(component.substring(17))); ansi.bg(Ansi.Color.valueOf(component.substring(17)));
else if (component.startsWith("ATTRIBUTE:")) else if (component.startsWith("ATTRIBUTE:"))
if (component.startsWith("ATTRIBUTE:BLINK")) { if (component.startsWith("ATTRIBUTE:BLINK"))
if (status.contains("ATTRIBUTE:BLINK"))
continue;
ansi.a(Ansi.Attribute.BLINK_SLOW); ansi.a(Ansi.Attribute.BLINK_SLOW);
status.add("ATTRIBUTE:BLINK"); else if (component.startsWith("ATTRIBUTE:BOLD"))
} else if (component.startsWith("ATTRIBUTE:BOLD")) {
if (status.contains("ATTRIBUTE:BOLD"))
continue;
ansi.a(Ansi.Attribute.INTENSITY_BOLD); ansi.a(Ansi.Attribute.INTENSITY_BOLD);
status.add("ATTRIBUTE:BOLD"); else if (component.startsWith("ATTRIBUTE:ITALIC"))
} else if (component.startsWith("ATTRIBUTE:ITALIC")) {
if (status.contains("ATTRIBUTE:ITALIC"))
continue;
ansi.a(Ansi.Attribute.ITALIC); ansi.a(Ansi.Attribute.ITALIC);
status.add("ATTRIBUTE:ITALIC"); else if (component.startsWith("ATTRIBUTE:STRIKETHROUGH"))
} else if (component.startsWith("ATTRIBUTE:STRIKETHROUGH")) {
if (status.contains("ATTRIBUTE:STRIKETHROUGH"))
continue;
ansi.a(Ansi.Attribute.STRIKETHROUGH_ON); ansi.a(Ansi.Attribute.STRIKETHROUGH_ON);
status.add("ATTRIBUTE:STRIKETHROUGH"); else if (component.startsWith("ATTRIBUTE:UNDERLINE"))
} else if (component.startsWith("ATTRIBUTE:UNDERLINE")) {
if (status.contains("ATTRIBUTE:UNDERLINE"))
continue;
ansi.a(Ansi.Attribute.UNDERLINE); ansi.a(Ansi.Attribute.UNDERLINE);
status.add("ATTRIBUTE:UNDERLINE"); else if (component.startsWith("ATTRIBUTE:NEGATIVE"))
} ansi.a(Ansi.Attribute.NEGATIVE_ON);
return ansi; return ansi;
} }

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,24 @@
* 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.ansi; package de.staropensource.sosengine.ansi;
import de.staropensource.engine.base.annotation.EngineSubsystem; import de.staropensource.sosengine.base.annotations.EngineSubsystem;
import de.staropensource.engine.base.implementable.SubsystemClass; import de.staropensource.sosengine.base.classes.SubsystemClass;
import de.staropensource.engine.base.utility.information.EngineInformation; import de.staropensource.sosengine.base.data.information.EngineInformation;
import de.staropensource.engine.base.implementation.versioning.StarOpenSourceVersioningSystem; import de.staropensource.sosengine.base.data.versioning.StarOpenSourceVersioningSystem;
import de.staropensource.engine.base.logging.Logger; import de.staropensource.sosengine.base.logging.Logger;
import de.staropensource.engine.base.type.DependencyVector; import de.staropensource.sosengine.base.types.DependencyVector;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Main class of the ANSI Compatibility subsystem. * Main object for the ANSI Compatibility subsystem.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@EngineSubsystem @EngineSubsystem
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class AnsiSubsystem extends SubsystemClass { public final class AnsiSubsystem extends SubsystemClass {
/** /**
* Contains the class instance. * Contains the class instance.
@ -50,7 +50,7 @@ public final class AnsiSubsystem extends SubsystemClass {
private static AnsiSubsystem instance = null; private static AnsiSubsystem instance = null;
/** /**
* Initializes this subsystem. * Constructs this subsystem.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@ -59,7 +59,7 @@ public final class AnsiSubsystem extends SubsystemClass {
if (instance == null) if (instance == null)
instance = this; instance = this;
else else
Logger.crash("Only one instance of this class is allowed, use getInstance() instead of creating a new instance"); logger.crash("Only one instance of this class is allowed, use getInstance() instead of creating a new instance");
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
@ -71,7 +71,7 @@ public final class AnsiSubsystem extends SubsystemClass {
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override @Override
public void initializeSubsystem() { public void initializeSubsystem() {
Logger.setLoggingAdapter(new AnsiLoggingAdapter()); Logger.setLoggerImplementation(new AnsiLoggerImplementation());
} }
/** {@inheritDoc} */ /** {@inheritDoc} */

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
@ -20,4 +20,4 @@
/** /**
* Contains the ANSI subsystem code. * Contains the ANSI subsystem code.
*/ */
package de.staropensource.engine.ansi; package de.staropensource.sosengine.ansi;

View file

@ -6,18 +6,22 @@
*/ */
module sosengine.ansi { module sosengine.ansi {
// Dependencies // Dependencies
// -> Java // -> Java <-
requires transitive java.management; requires transitive java.management;
// -> Engine
// -> Engine <-
requires transitive sosengine.base; requires transitive sosengine.base;
// -> Libraries
// -> Common stuff <-
requires transitive static lombok; requires transitive static lombok;
requires transitive org.jetbrains.annotations; requires transitive org.jetbrains.annotations;
// -> Subystem-specific dependencies <-
requires org.fusesource.jansi; requires org.fusesource.jansi;
// API access // API access
exports de.staropensource.engine.ansi; exports de.staropensource.sosengine.ansi;
// Reflection access // Reflection access
opens de.staropensource.engine.ansi; opens de.staropensource.sosengine.ansi;
} }

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

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
@ -26,9 +26,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}")
@ -39,7 +39,7 @@ dependencies {
// 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}")
@ -47,84 +47,22 @@ dependencies {
testImplementation(platform("org.junit:junit-bom:${dependencyJunit}")) testImplementation(platform("org.junit:junit-bom:${dependencyJunit}"))
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
testImplementation(project(":testing"))
} }
// 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)
options {
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") //
addStringOption("Xwerror", "-quiet") // Fail build on warning
setJFlags([
"-Duser.language=en_US" // See above
])
}
}
} }
delombok.doLast {
File target = file("${project.projectDir}/src/main/java/module-info.java")
File source = file("${project.projectDir}/src/main/module-info.java")
// Unit testing configuration target.delete()
test { source.renameTo(target)
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
@ -166,18 +104,69 @@ 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()
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/sosengine")
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
}
}
} }

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,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,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/>.
*/
/**
* Implementations for various interfaces and abstract classes.
*
* @since v1-alpha6
*/
package de.staropensource.engine.base.implementation;

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,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,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,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,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,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,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,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,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,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,501 @@
/*
* 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.ShutdownHandler;
import de.staropensource.sosengine.base.classes.SubsystemClass;
import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.sosengine.base.data.information.EngineInformation;
import de.staropensource.sosengine.base.data.information.JvmInformation;
import de.staropensource.sosengine.base.data.versioning.StarOpenSourceVersioningSystem;
import de.staropensource.sosengine.base.events.*;
import de.staropensource.sosengine.base.exceptions.NoAccessException;
import de.staropensource.sosengine.base.exceptions.dependency.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.DependencyVector;
import de.staropensource.sosengine.base.types.EngineState;
import de.staropensource.sosengine.base.types.immutable.ImmutableLinkedList;
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 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
*/
@EngineSubsystem
@SuppressWarnings({ "unused", "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 {@link LoggerInstance} for this instance.
*
* @see LoggerInstance
* @since v1-alpha0
*/
private static final LoggerInstance logger = new LoggerInstance.Builder().setClazz(Engine.class).setOrigin("ENGINE").setMetadata(EngineInformation.getVersioningCodename()).build();
/**
* Contains the engine state.
*
* @since v1-alpha2
* -- GETTER --
* Returns the engine state.
*
* @return shutdown state
* @since v1-alpha2
*/
@Getter
private @NotNull EngineState state = EngineState.UNKNOWN;
/**
* 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
@Setter
private @NotNull ShutdownHandler shutdownHandler = new Engine.JvmShutdownHandler();
/**
* 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<>();
/**
* Initializes the StarOpenSource Engine.
*
* @throws IllegalStateException when running in an incompatible environment
* @since v1-alpha0
*/
public Engine() throws IllegalStateException {
if (instance == null)
instance = this;
else
return;
long initTime = Miscellaneous.measureExecutionTime(() -> {
state = EngineState.EARLY_STARTUP;
new EngineConfiguration();
EngineConfiguration.getInstance().loadConfiguration();
logger.info("Initializing engine");
initializeClasses(); // Initialize classes
if (checkEnvironment())
throw new IllegalStateException("Running in an incompatible environment");
populateCrashContent(); // Populate crash content
cacheEvents(); // Cache event listeners
startThreads(); // Start threads
state = EngineState.STARTUP;
// Perform automatic subsystem initialization
if (EngineConfiguration.getInstance().isOptimizeSubsystemInitialization()) {
collectSubsystems(); // Collect subsystems
// Initialize subsystems
try {
initializeSubsystems();
} catch (Exception exception) {
logger.crash("Subsystem dependency resolution failed", exception);
}
}
});
state = EngineState.RUNNING;
logger.info("Initialized sos!engine %engine_version% (commit %engine_git_commit_id_long%-%engine_git_branch%, dirty %engine_git_dirty%) in " + initTime + "ms");
}
/**
* Checks if the environment is compatible with the engine build.
*
* @since v1-alpha4
*/
private boolean checkEnvironment() {
logger.diag("Checking environment");
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());
return false;
}
/**
* Initializes all classes.
*
* @since v1-alpha0
*/
private void initializeClasses() {
logger.verb("Initializing engine classes");
new PlaceholderEngine();
EngineInformation.update();
}
/**
* This method populates {@link CrashHandler#crashContent} with content.
*
* @see CrashHandler#getCrashContent()
* @since v1-alpha0
*/
@SuppressWarnings({ "ExtractMethodRecommender" })
private void populateCrashContent() {
logger.diag("Populating crash content");
// Issuer
Map<@NotNull String, @NotNull String> crashContentIssuer = new LinkedHashMap<>();
crashContentIssuer.put("Code part", "%issuer_origin%");
crashContentIssuer.put("Classpath", "%issuer_path%");
crashContentIssuer.put("Additional information", "%issuer_metadata%");
crashContentIssuer.put("Message", "%crash_message%");
// Engine -> Dependencies
LinkedList<@NotNull String> crashContentEngineDependencies = new LinkedList<>();
crashContentEngineDependencies.add("Subsystem 'base': Reflections: %engine_dependency_reflections%");
crashContentEngineDependencies.add("Subsystem 'ansi': Jansi: %engine_dependency_jansi%");
crashContentEngineDependencies.add("Subsystem 'slf4j-compat': SLF4J: %engine_dependency_slf4j%");
crashContentEngineDependencies.add("Subsystems 'glfw', 'opengl' & 'vulkan': LWJGL: %engine_dependency_lwjgl%");
// Engine -> *
Map<@NotNull String, @NotNull Object> crashContentEngine = new LinkedHashMap<>();
crashContentEngine.put("Version", "%engine_version%");
crashContentEngine.put("Dependencies", crashContentEngineDependencies);
// 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", JvmInformation.getArguments());
// 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", "\n%stacktrace%");
CrashHandler.getCrashContent().put("Stacktrace for all threads", "\n%stacktrace_all%");
}
/**
* Caches all base engine events.
*
* @since v1-alpha0
*/
private void cacheEvents() {
logger.diag("Caching events");
// Internal events
EventHelper.cacheEvent(InternalEngineShutdownEvent.class);
// General events
EventHelper.cacheEvent(EngineCrashEvent.class);
EventHelper.cacheEvent(EngineShutdownEvent.class);
EventHelper.cacheEvent(EngineSoftCrashEvent.class);
EventHelper.cacheEvent(LogEvent.class);
EventHelper.cacheEvent(ThrowableCatchEvent.class);
}
/**
* Starts engine threads.
*
* @since v1-alpha1
*/
public void startThreads() {
logger.diag("Starting threads");
Logger.startLoggingThread();
}
/**
* Collects all subsystems by their {@link EngineSubsystem} annotation.
*
* @since v1-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();
SubsystemClass initializedClass = null;
// Check if class implements SubsystemMainClass
if (initializedClassRaw instanceof SubsystemClass subsystemInstance)
initializedClass = subsystemInstance;
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);
}
/**
* 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.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 exception) {
Map<@NotNull DependencyVector, @NotNull String> unmetDependencies = exception.getUnmetDependencies();
StringBuilder list = new StringBuilder();
for (DependencyVector vector : unmetDependencies.keySet())
list.append("- ")
.append(vector.getIdentifier())
.append(": ")
.append(unmetDependencies.get(vector));
logger.crash("Found unresolved dependencies:" + list, throwable);
}
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");
long initTime;
for (DependencySubsystemVector vector : subsystems) {
logger.diag("Initializing subsystem " + vector.getMainClass().getName() + " (" + vector.getMainClass().getClass().getName() + ")");
try {
initTime = Miscellaneous.measureExecutionTime(() -> vector.getMainClass().initializeSubsystem());
} catch (Throwable throwable) {
logger.crash("An error occurred trying to initialize subsystem " + vector.getMainClass().getName() + " (" + vector.getMainClass().getClass().getName() + "): " + throwable.getClass().getName() + (throwable.getMessage() == null ? "" : ": " + throwable.getMessage()));
throw throwable;
}
logger.diag("Initialized subsystem " + vector.getMainClass().getName() + " (" + vector.getMainClass().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) {
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
Logger.flushLogMessages();
logger.verb("Notifiying classes about shutdown");
new EngineShutdownEvent().callEvent();
logger.verb("Notifying subsystems about shutdown");
new InternalEngineShutdownEvent().callEvent();
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";
}
/** {@inheritDoc} */
@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 NoAccessException if the caller class is unauthorized
* @since v1-alpha2
*/
public void setState(@NotNull EngineState state) throws NoAccessException {
if (!Thread.currentThread().getStackTrace()[2].getClassName().startsWith("de.staropensource.sosengine.base."))
throw new NoAccessException("Only classes inside the \"de.staropensource.sosengine.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) {
logger.warn("Terminating JVM");
System.exit(exitCode);
}
}
}

View file

@ -0,0 +1,393 @@
/*
* 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.ShortcodeParserSkeleton;
import de.staropensource.sosengine.base.classes.Configuration;
import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.sosengine.base.logging.CrashHandler;
import de.staropensource.sosengine.base.logging.Logger;
import de.staropensource.sosengine.base.types.EngineState;
import de.staropensource.sosengine.base.types.logging.LogLevel;
import de.staropensource.sosengine.base.types.vectors.Vec2f;
import de.staropensource.sosengine.base.utility.PropertiesReader;
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 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({ "unused", "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 group in which setting overrides must begin with..
*
* @since v1-alpha0
* -- GETTER --
* Returns the group in which setting overrides must begin with.
*
* @return property group
* @since v1-alpha0
*/
@Getter
private final @NotNull String group = "sosengine.base.";
/**
* If enabled, allows for unintentional behaviour and excess logging.
* Unless you want to debug or work on a sensitive part of the engine, don't enable this!
*
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #debug}.
*
* @return variable value
* @see #debug
* @since v1-alpha0
*/
private boolean debug;
/**
* If enabled, all called events will be logged.
*
* @see EventHelper#logCall(Class, Object...)
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #debugEvents}.
*
* @return variable value
* @see #debugEvents
* @since v1-alpha0
*/
private boolean debugEvents;
/**
* If enabled, very verbose messages about the {@link ShortcodeParserSkeleton}'s internals will be printed.
* Don't enable unless you want to work on it.
*
* @see ShortcodeParserSkeleton
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #debugShortcodeConverter}.
*
* @return variable value
* @see #debugShortcodeConverter
* @since v1-alpha0
*/
private boolean debugShortcodeConverter;
/**
* If enabled, invalid shortcodes will be logged by the {@link ShortcodeParserSkeleton}.
* The message will be printed as a {@link LogLevel#SILENT_WARNING}.
*
* @see ShortcodeParserSkeleton
* @see #loggerLevel
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #errorShortcodeConverter}.
*
* @return variable value
* @see #errorShortcodeConverter
* @since v1-alpha0
*/
private boolean errorShortcodeConverter;
/**
* 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 #loggerPollingSpeed
* @see Thread
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #optimizeLogging}.
*
* @return variable value
* @see #optimizeLogging
* @since v1-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 v1-alpha0
* -- GETTER --
* Gets the value for {@link #optimizeEvents}.
*
* @return variable value
* @see #optimizeEvents
* @since v1-alpha0
*/
private boolean optimizeEvents;
/**
* If enabled, will try to automatically initialize every subsystem found though reflection.
* <p>
* This however may fail in certain situation, where manual subsystem initialization may be required.
* For this reason, this can be turned off before the engine initializes.
* Please note though that dependency resolution between subsystems will not be done, be careful when
* initializing subsystems manually.
*
* @see Engine
* @since v1-alpha2
* -- GETTER --
* Gets the value for {@link #optimizeSubsystemInitialization}.
*
* @return variable value
* @see #optimizeSubsystemInitialization
* @since v1-alpha2
*/
private boolean optimizeSubsystemInitialization;
/**
* Contains which logger levels are allowed by setting the minimum logger level.
*
* @see Logger
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #loggerLevel}.
*
* @return variable value
* @see #loggerLevel
* @since v1-alpha0
*/
private LogLevel loggerLevel;
/**
* Contains the logging template used for creating log messages.
*
* @see Logger
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #loggerTemplate}
*
* @return variable value
* @see #loggerTemplate
* @since v1-alpha0
*/
private String loggerTemplate;
/**
* If enabled, the JVM will immediately shutdown on an engine crash. This will prevent shutdown hooks from executing.
* Note: This will also prevent Jansi and potentially other libraries from removing temporary native libraries at shutdown.
*
* @see CrashHandler
* @since v1-alpha0
* -- GETTER --
* Gets the value for {@link #loggerImmediateShutdown}.
*
* @return variable value
* @see #loggerImmediateShutdown
* @since v1-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 v1-alpha0
* -- GETTER --
* Gets the value for {@link #loggerForceStandardOutput}.
*
* @return variable value
* @see #loggerForceStandardOutput
* @since v1-alpha0
*/
private boolean loggerForceStandardOutput;
/**
* Contains how fast the logging thread will poll for queued messages.
* Only applies if {@code optimizeLogging} is turned on.
*
* @see #optimizeLogging
* @since v1-alpha1
* -- GETTER --
* Gets the value for {@link #loggerForceStandardOutput}.
*
* @return variable value
* @see #loggerForceStandardOutput
* @since v1-alpha1
*/
private int loggerPollingSpeed;
/**
* Will truncate the path of types when using their {@code toString} method.
* <p>
* Here's an example: Lets say that you have a {@link Vec2f} and to convert it
* to a String, which you can do with {@link Vec2f#toString()}. With this flag disabled
* it would return {@code de.staropensource.sosengine.base.types.vectors.Vec2(x=64 y=64)},
* with it however it would be {@code Vec2(x=64 y=64)}, which is much smaller.
*
* @since v1-alpha2
* -- GETTER --
* Gets the value for {@link #hideFullTypePath}.
*
* @return variable value
* @see #hideFullTypePath
* @since v1-alpha2
*/
private boolean hideFullTypePath;
/**
* Constructs this class.
*
* @see Engine
* @since v1-alpha0
*/
public EngineConfiguration() {
super("ENGINE"); // TODO Wait for flexible constructor bodies (JEP 482) to be implemented into the JVM as a stable feature. We don't want to use preview features in production code.
// Only allow one instance
if (instance == null)
instance = this;
else
logger.crash("Only one instance of this class is allowed, use getInstance() instead of creating a new instance");
// 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 "debugShortcodeConverter" -> debugShortcodeConverter = parser.getBoolean(group + property);
case "errorShortcodeConverter" -> errorShortcodeConverter = parser.getBoolean(group + property);
case "optimizeLogging" -> {
optimizeLogging = parser.getBoolean(group + property);
// Start logging thread automatically
if (optimizeLogging && Engine.getInstance().getState() == EngineState.RUNNING)
Logger.startLoggingThread();
}
case "optimizeEvents" -> optimizeEvents = parser.getBoolean(group + property);
case "optimizeSubsystemInitialization" -> optimizeSubsystemInitialization = 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 "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;
debugShortcodeConverter = false;
}
}
/** {@inheritDoc} */
@Override
public void loadDefaultConfiguration() {
debug = false;
debugEvents = false;
debugShortcodeConverter = false;
errorShortcodeConverter = true;
optimizeLogging = true;
optimizeEvents = true;
optimizeSubsystemInitialization = true;
loggerLevel = LogLevel.INFORMATIONAL;
loggerTemplate = "%log_color_primary%[%time_hour%:%time_minute%:%time_second%] [%log_level% %log_path%%log_metadata%] %log_color_secondary%%log_message%<reset>";
loggerImmediateShutdown = false;
loggerForceStandardOutput = false;
loggerPollingSpeed = 5;
hideFullTypePath = false;
}
/** {@inheritDoc} */
@Override
public @Nullable Object getSetting(@NotNull String setting) {
switch (setting) {
case "debug" -> { return debug; }
case "debugEvents" -> { return debugEvents; }
case "debugShortcodeConverter" -> { return debugShortcodeConverter; }
case "errorShortcodeConverter" -> { return errorShortcodeConverter; }
case "optimizeLogging" -> { return optimizeLogging; }
case "optimizeEvents" -> { return optimizeEvents; }
case "optimizeSubsystemInitialization" -> { return optimizeSubsystemInitialization; }
case "loggerLevel" -> { return loggerLevel; }
case "loggerTemplate" -> { return loggerTemplate; }
case "loggerImmediateShutdown" -> { return loggerImmediateShutdown; }
case "loggerForceStandardOutput" -> { return loggerForceStandardOutput; }
case "loggerPollingSpeed" -> { return loggerPollingSpeed; }
case "hideFullTypePath" -> { return hideFullTypePath; }
default -> { return 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,9 +17,9 @@
* 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 de.staropensource.sosengine.base.classes.SubsystemClass;
import java.lang.annotation.*; import java.lang.annotation.*;
@ -33,4 +33,5 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
@Documented @Documented
@SuppressWarnings("unused")
public @interface EngineSubsystem {} public @interface EngineSubsystem {}

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,10 +17,10 @@
* 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.*;
@ -34,6 +34,7 @@ import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Documented @Documented
@SuppressWarnings("unused")
public @interface EventListener { public @interface EventListener {
/** /**
* Specifies the event to listen for. * Specifies the event to listen for.

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
@ -23,4 +23,4 @@
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
package de.staropensource.engine.base.annotation; 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,9 +17,10 @@
* 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.PropertiesReader; import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.sosengine.base.utility.PropertiesReader;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -34,13 +35,26 @@ import java.util.Properties;
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@SuppressWarnings({ "unused" })
public abstract class Configuration { public abstract class Configuration {
/** /**
* Creates and initializes an instance of this abstract class. * Contains the {@link LoggerInstance} for this instance.
* *
* @see LoggerInstance
* @since v1-alpha1
*/
protected final @NotNull LoggerInstance logger;
/**
* Constructs this class.
*
* @param origin see {@link LoggerInstance.Builder#setOrigin(String)}
* @since v1-alpha2 * @since v1-alpha2
*/ */
protected Configuration() { public Configuration(@NotNull String origin) {
// Set logger instance
logger = new LoggerInstance.Builder().setClazz(getClass()).setOrigin(origin).build();
// Load default configuration // Load default configuration
loadDefaultConfiguration(); loadDefaultConfiguration();
} }
@ -87,7 +101,7 @@ public abstract class Configuration {
} }
/** /**
* Returns prefix properties must begin with. * Returns the group in which setting overrides must begin with.
* *
* @return property group * @return property group
* @since v1-alpha2 * @since v1-alpha2

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,9 +17,9 @@
* 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; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
/** /**
* Represents an event. * Represents an event.
@ -27,6 +27,7 @@ import de.staropensource.engine.base.implementable.helper.EventHelper;
* @see EventHelper * @see EventHelper
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public interface Event { public interface Event {
/** /**
* Emits the event and calls all event listeners. * Emits the event and calls all event listeners.

View file

@ -0,0 +1,75 @@
/*
* 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.logging.Logger;
import de.staropensource.sosengine.base.types.logging.LogLevel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Interface for implementing custom logger implementations.
*
* @see Logger#setLoggerImplementation(LoggerImplementation)
* @since v1-alpha0
*/
@SuppressWarnings({ "unused" })
public interface LoggerImplementation {
/**
* Invoked before anything is done with the log message.
*
* @param level level
* @param issuerClass issuer class
* @param issuerOrigin issuer origin
* @param issuerMetadata issuer metadata
* @param message raw message
* @param format unmodified log format
* @return new log message, return {@code null} for no change
* @since v1-alpha2
*/
@Nullable String prePlaceholder(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @NotNull String format);
/**
* Invoked after placeholders have been processed and replaced.
*
* @param level level
* @param issuerClass issuer class
* @param issuerOrigin issuer origin
* @param issuerMetadata issuer metadata
* @param message raw message
* @param format unmodified log format
* @return new log format
* @since v1-alpha2
*/
@NotNull String postPlaceholder(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @NotNull String format);
/**
* Prints the log message.
*
* @param level level
* @param issuerClass issuer class
* @param issuerOrigin issuer origin
* @param issuerMetadata issuer metadata
* @param message raw message
* @param format unmodified log format
* @since v1-alpha2
*/
void print(@NotNull LogLevel level, @NotNull Class<?> issuerClass, @NotNull String issuerOrigin, @Nullable String issuerMetadata, @NotNull String message, @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,9 +17,9 @@
* 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;
/** /**
@ -28,6 +28,7 @@ import org.jetbrains.annotations.NotNull;
* @see PlaceholderEngine * @see PlaceholderEngine
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public interface Placeholder { public interface Placeholder {
/** /**
* Replaces the placeholder with content. * Replaces the placeholder with content.

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,11 +17,11 @@
* 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.EngineConfiguration; import de.staropensource.sosengine.base.EngineConfiguration;
import de.staropensource.engine.base.exception.ParserException; import de.staropensource.sosengine.base.exceptions.ParserException;
import de.staropensource.engine.base.logging.Logger; import de.staropensource.sosengine.base.logging.LoggerInstance;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -29,7 +29,7 @@ import java.util.LinkedList;
import java.util.Locale; import java.util.Locale;
/** /**
* Base class for implementing a shortcode parser. * Base class for implementing a shortcode converter.
* <p> * <p>
* This class parses a string and converts it into a list of * This class parses a string and converts it into a list of
* components, which can then be in turn be converted to something * components, which can then be in turn be converted to something
@ -48,9 +48,16 @@ import java.util.Locale;
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @SuppressWarnings({ "unused", "JavadocDeclaration" })
@SuppressWarnings({ "JavadocDeclaration" }) public abstract class ShortcodeParserSkeleton {
public abstract class ShortcodeParser { /**
* Contains the {@link LoggerInstance} for this instance.
*
* @see LoggerInstance
* @since v1-alpha1
*/
protected final @NotNull LoggerInstance logger;
/** /**
* Contains a list of components the parsed text is made out of. * Contains a list of components the parsed text is made out of.
* *
@ -61,17 +68,19 @@ public abstract class ShortcodeParser {
* @return component list * @return component list
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter
protected final @NotNull LinkedList<String> components; protected final @NotNull LinkedList<String> components;
/** /**
* Creates and initializes an instance of this abstract class. * Constructs this class.
* *
* @param string string to parse * @param string string to parse
* @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text * @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text
* @throws ParserException on error * @throws ParserException on error
* @since v1-alpha2 * @since v1-alpha2
*/ */
protected ShortcodeParser(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException { public ShortcodeParserSkeleton(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
logger = new LoggerInstance.Builder().setClazz(getClass()).setOrigin("ENGINE").build();
components = parse(string, ignoreInvalidEscapes); components = parse(string, ignoreInvalidEscapes);
} }
@ -83,7 +92,7 @@ public abstract class ShortcodeParser {
* @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text * @param ignoreInvalidEscapes if {@code true}, will ignore and treat invalid escapes as text
* @return list of components * @return list of components
* @throws ParserException on error * @throws ParserException on error
* @see EngineConfiguration#errorShortcodeParser * @see EngineConfiguration#errorShortcodeConverter
* @since v1-alpha2 * @since v1-alpha2
*/ */
protected @NotNull LinkedList<@NotNull String> parse(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException { protected @NotNull LinkedList<@NotNull String> parse(@NotNull String string, boolean ignoreInvalidEscapes) throws ParserException {
@ -119,53 +128,110 @@ public abstract class ShortcodeParser {
tagActive = false; tagActive = false;
// fg:* // fg:*
if (part.toString().startsWith("fg:")) if (part.toString().startsWith("fg:")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=fg data=" + part.substring(3).toUpperCase());
if (isValidColor(part.substring(3).toUpperCase())) if (isValidColor(part.substring(3).toUpperCase()))
components.add("COLOR:FOREGROUND:" + part.substring(3).toUpperCase()); components.add("COLOR:FOREGROUND:" + part.substring(3).toUpperCase());
else { else {
// Complain about invalid shortcode // Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser()) if (EngineConfiguration.getInstance().isErrorShortcodeConverter())
Logger.sarn("Invalid shortcode: " + part); logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text // Convert tag regular text
components.add("TEXT:" + "<" + part + ">"); components.add("TEXT:" + "<" + part + ">");
} }
}
// bg:* // bg:*
else if (part.toString().startsWith("bg:")) else if (part.toString().startsWith("bg:")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=bg data=" + part.substring(3).toUpperCase());
if (isValidColor(part.substring(3).toUpperCase())) if (isValidColor(part.substring(3).toUpperCase()))
components.add("COLOR:BACKGROUND:" + part.substring(3).toUpperCase()); components.add("COLOR:BACKGROUND:" + part.substring(3).toUpperCase());
else { else {
// Complain about invalid shortcode // Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser()) if (EngineConfiguration.getInstance().isErrorShortcodeConverter())
Logger.sarn("Invalid shortcode: " + part); logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text // Convert tag regular text
components.add("TEXT:" + "<" + part + ">"); components.add("TEXT:" + "<" + part + ">");
} }
}
// bold // bold
else if (part.toString().equals("bold")) else if (part.toString().equals("bold")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=bold");
// Insert attribute
components.add("ATTRIBUTE:BOLD"); components.add("ATTRIBUTE:BOLD");
}
// italic // italic
else if (part.toString().equals("italic")) else if (part.toString().equals("italic")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=italic");
// Insert attribute
components.add("ATTRIBUTE:ITALIC"); components.add("ATTRIBUTE:ITALIC");
}
// strikethrough // strikethrough
else if (part.toString().equals("strikethrough")) else if (part.toString().equals("strikethrough")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=strikethrough");
// Insert attribute
components.add("ATTRIBUTE:STRIKETHROUGH"); components.add("ATTRIBUTE:STRIKETHROUGH");
}
// underline // underline
else if (part.toString().equals("underline")) else if (part.toString().equals("underline")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=underline");
// Insert attribute
components.add("ATTRIBUTE:UNDERLINE"); components.add("ATTRIBUTE:UNDERLINE");
// blink }
else if (part.toString().equals("blink"))
// underline
else if (part.toString().equals("blink")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=blink");
// Insert attribute
components.add("ATTRIBUTE:BLINK"); components.add("ATTRIBUTE:BLINK");
}
// reset // reset
else if (part.toString().equals("reset")) else if (part.toString().equals("reset")) {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " tag=reset");
// Insert reset
components.add("RESET"); components.add("RESET");
}
// error case // error case
else { else {
// Print debug message
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " invalidtag=" + part);
// Complain about invalid shortcode // Complain about invalid shortcode
if (EngineConfiguration.getInstance() != null && EngineConfiguration.getInstance().isErrorShortcodeParser()) if (EngineConfiguration.getInstance().isErrorShortcodeConverter())
Logger.sarn("Invalid shortcode: " + part); logger.sarn("Invalid shortcode: " + part);
// Convert tag regular text // Convert tag regular text
components.add("TEXT:" + "<" + part + ">"); components.add("TEXT:" + "<" + part + ">");
@ -182,6 +248,9 @@ public abstract class ShortcodeParser {
if (character == '<') { if (character == '<') {
if (!part.isEmpty()) { if (!part.isEmpty()) {
// Tag is starting, insert previous text // Tag is starting, insert previous text
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " text=" + part);
components.add("TEXT:" + part); components.add("TEXT:" + part);
part = new StringBuilder(); part = new StringBuilder();
} }
@ -195,8 +264,12 @@ public abstract class ShortcodeParser {
} }
// Processing ended, insert leftover text // Processing ended, insert leftover text
if (!part.isEmpty()) if (!part.isEmpty()) {
if (EngineConfiguration.getInstance().isDebugShortcodeConverter())
System.out.println(getClass().getName() + "#" + string.hashCode() + " endtext=" + part);
components.add("TEXT:" + part); components.add("TEXT:" + part);
}
return components; return components;
} }

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,9 +17,9 @@
* 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.Engine; import de.staropensource.sosengine.base.Engine;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
/** /**

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,28 +17,39 @@
* 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.Engine; import de.staropensource.sosengine.base.Engine;
import de.staropensource.engine.base.annotation.EngineSubsystem; import de.staropensource.sosengine.base.annotations.EngineSubsystem;
import de.staropensource.engine.base.annotation.EventListener; import de.staropensource.sosengine.base.annotations.EventListener;
import de.staropensource.engine.base.event.InternalEngineShutdownEvent; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.type.DependencyVector; import de.staropensource.sosengine.base.internal.events.InternalEngineShutdownEvent;
import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.sosengine.base.types.DependencyVector;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Abstract class for building subsystem main classes. * Interface for building subsystem main classes.
* *
* @see EngineSubsystem * @see EngineSubsystem
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public abstract class SubsystemClass { public abstract class SubsystemClass {
/** /**
* Creates and initializes an instance of this abstract class. * Constructs this class.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
protected SubsystemClass() {} public SubsystemClass() {}
/**
* Contains the {@link LoggerInstance} for this instance.
*
* @see LoggerInstance
* @since v1-alpha0
*/
public final LoggerInstance logger = new LoggerInstance.Builder().setClazz(getClass()).setOrigin("ENGINE").build();
/** /**
* Returns the name of the subsystem. * Returns the name of the subsystem.
@ -60,11 +71,10 @@ public abstract class SubsystemClass {
* Used for dependency resolution during startup. * Used for dependency resolution during startup.
* *
* @return matching {@link DependencyVector} for the subsystem * @return matching {@link DependencyVector} for the subsystem
* @throws IllegalStateException when building the DependencyVector fails, see {@link DependencyVector.Builder#build()}
* @see DependencyVector * @see DependencyVector
* @since v1-alpha4 * @since v1-alpha1
*/ */
public abstract @NotNull DependencyVector getDependencyVector() throws IllegalStateException; public abstract @NotNull DependencyVector getDependencyVector() throws InvalidVersionStringException;
/** /**
* Called on engine shutdown. * Called on engine shutdown.
@ -74,6 +84,5 @@ public abstract class SubsystemClass {
* @since v1-alpha0 * @since v1-alpha0
*/ */
@EventListener(event = InternalEngineShutdownEvent.class) @EventListener(event = InternalEngineShutdownEvent.class)
@SuppressWarnings({ "unused" })
protected static void shutdownSubsystem() {} protected static void shutdownSubsystem() {}
} }

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,9 +17,9 @@
* 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.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
@ -28,6 +28,7 @@ import org.jetbrains.annotations.Range;
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
@SuppressWarnings({ "unused" })
public interface VersioningSystem { public interface VersioningSystem {
/** /**
* Returns the name of the versioning system. * Returns the name of the versioning system.
@ -41,7 +42,7 @@ public interface VersioningSystem {
* Compares a {@link VersioningSystem} with another. * Compares a {@link VersioningSystem} with another.
* *
* @param version {@link VersioningSystem} to compare against * @param version {@link VersioningSystem} to compare against
* @return {@code 0} if the supplied version is bigger, {@code 1} if equal and {@code 2} if smaller * @return smaller = {@code 0}, equal = {@code 1}, bigger = {@code 2}
* @throws IncompatibleVersioningSystemException incompatible with the supplied versioning system * @throws IncompatibleVersioningSystemException incompatible with the supplied versioning system
* @since v1-alpha1 * @since v1-alpha1
*/ */

View file

@ -0,0 +1,218 @@
/*
* 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.helpers;
import de.staropensource.sosengine.base.EngineConfiguration;
import de.staropensource.sosengine.base.annotations.EventListener;
import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.sosengine.base.events.LogEvent;
import de.staropensource.sosengine.base.exceptions.UnexpectedThrowableException;
import de.staropensource.sosengine.base.exceptions.reflection.InstanceMethodFromStaticContextException;
import de.staropensource.sosengine.base.exceptions.reflection.InvalidMethodSignature;
import de.staropensource.sosengine.base.exceptions.reflection.NoAccessException;
import de.staropensource.sosengine.base.exceptions.reflection.StaticInitializerException;
import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.sosengine.base.reflection.Reflect;
import de.staropensource.sosengine.base.reflection.ReflectionMethod;
import de.staropensource.sosengine.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.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
/**
* Simplifies event logging and calling.
*
* @since v1-alpha0
*/
@Getter
@SuppressWarnings({ "unused" })
public final class EventHelper {
/**
* Holds all cached events.
* Should not be modified manually.
*
* @since v1-alpha0
*/
private static final @NotNull HashMap<@NotNull Class<? extends Event>, LinkedList<@NotNull ReflectionMethod>> cachedEventListeners = new HashMap<>();
/**
* Contains the {@link LoggerInstance} for this instance.
*
* @see LoggerInstance
* @since v1-alpha1
*/
private static final @NotNull LoggerInstance logger = new LoggerInstance.Builder().setClazz(EventHelper.class).setOrigin("ENGINE").build();
/**
* Constructs this class.
*
* @since v1-alpha0
*/
public EventHelper() {}
/**
* Logs an event call.
*
* @param event event class
* @param arguments arguments passed to event listeners
* @since v1-alpha0
*/
public static void logCall(@NotNull Class<? extends Event> event, @NotNull Object ... arguments) {
// Print event call if event debugging is enabled
if (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));
}
/**
* 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-alpha0
*/
public static @NotNull LinkedList<ReflectionMethod> getAnnotatedMethods(@NotNull Class<? extends Event> event, boolean forceScanning) {
LinkedList<ReflectionMethod> methods = new LinkedList<>();
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 this event out
for (Method method : annotatedMethods)
if (method.getAnnotation(EventListener.class).event() == event)
methods.add(Reflect.reflectOn(method));
// Sort 'methods' linked list after event priority
methods.sort(Comparator.comparing(method -> method.getAnnotation(EventListener.class).priority()));
} else
// Event listeners are cached and !forceScanning, return cached results
methods = cachedEventListeners.get(event);
return methods;
}
/**
* 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-alpha0
*/
public static @NotNull LinkedList<ReflectionMethod> getAnnotatedMethods(@NotNull Class<? extends Event> event) {
return getAnnotatedMethods(event, false);
}
/**
* Invokes all event listeners.
*
* @param event event class
* @param arguments arguments to pass to event listeners
* @since v1-alpha0
*/
public static void invokeAnnotatedMethods(@NotNull Class<? extends Event> event, Object... arguments) {
if (event != LogEvent.class)
logCall(event);
Runnable eventCode = () -> {
for (ReflectionMethod method : getAnnotatedMethods(event)) {
try {
method.invoke(arguments);
} catch (UnexpectedThrowableException exception) {
logger.crash("Event listener method " + method.getName() + " could not be called as an error occurred during reflection", exception, true);
} catch (NoAccessException exception) {
logger.warn("Event listener method " + method.getName() + " could not be called as the method could not be accessed");
} catch (InvalidMethodSignature exception) {
logger.warn("Event listener method " + method.getName() + " has an invalid method signature");
} catch (InvocationTargetException exception) {
logger.crash("Event listener method " + method.getName() + " threw a throwable", exception.getTargetException(), true);
} catch (InstanceMethodFromStaticContextException exception) {
logger.warn("Event listener method " + method.getName() + " is not static. Event listener methods must be static for them to be called.");
} catch (StaticInitializerException exception) {
logger.crash("Event listener method " + method.getName() + " could not be called as the static initializer failed", exception.getThrowable(), true);
}
}
};
if (EngineConfiguration.getInstance().isOptimizeEvents())
Thread
.ofVirtual()
.name("Event " + event.getName())
.start(eventCode);
else
eventCode.run();
}
/**
* (Re-)Caches all event listeners for some {@link Event}.
*
* @param event event to (re-)cache. Set to {@code null} to recompute all cached events
* @since v1-alpha0
*/
public static synchronized void cacheEvent(@Nullable Class<? extends Event> event) {
if (event == null)
for (Class<? extends Event> cachedEvent : cachedEventListeners.keySet())
cacheEvent(cachedEvent);
else {
LinkedList<@NotNull ReflectionMethod> annotatedMethods = getAnnotatedMethods(event);
if (cachedEventListeners.containsKey(event))
cachedEventListeners.replace(event, annotatedMethods);
else
cachedEventListeners.put(event, annotatedMethods);
}
}
/**
* Removes an event from the event listener cache.
*
* @param event event to uncache. Set to {@code null} to clear the entire cache
* @since v1-alpha0
*/
public static synchronized void uncacheEvent(@Nullable Class<? extends Event> event) {
if (event == null)
cachedEventListeners.clear();
else
cachedEventListeners.remove(event);
}
}

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
@ -23,4 +23,4 @@
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
package de.staropensource.engine.base.implementable.helper; package de.staropensource.sosengine.base.classes.helpers;

View file

@ -0,0 +1,27 @@
/*
* 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/>.
*/
/**
* Interfaces and abstract classes which can be used for implementing classes.
* <p>
* These are not to be confused with data types. See {@link de.staropensource.sosengine.base.types}.
*
* @since v1-alpha0
*/
package de.staropensource.sosengine.base.classes;

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,12 +17,15 @@
* 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.utility.information; package de.staropensource.sosengine.base.data.information;
import de.staropensource.engine.base.logging.Logger; import de.staropensource.sosengine.base.Engine;
import de.staropensource.engine.base.type.VersionType; import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.engine.base.utility.PropertiesReader; import de.staropensource.sosengine.base.types.VersionType;
import de.staropensource.sosengine.base.utility.PropertiesReader;
import de.staropensource.sosengine.base.utility.parser.StackTraceParser;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -39,8 +42,16 @@ import java.util.Properties;
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class EngineInformation { public final class EngineInformation {
/**
* Contains the {@link LoggerInstance} for this instance.
*
* @see LoggerInstance
* @since v1-alpha2
*/
private static final @NotNull LoggerInstance logger = new LoggerInstance.Builder().setClazz(EngineInformation.class).setOrigin("ENGINE").build();
/** /**
* Contains the engine's version codename. * Contains the engine's version codename.
* *
@ -322,11 +333,11 @@ public final class EngineInformation {
private static String dependencyLwjgl; private static String dependencyLwjgl;
/** /**
* Creates and initializes an instance of this class. * Constructs this class.
* *
* @since v1-alpha6 * @since v1-alpha0
*/ */
private EngineInformation() {} public EngineInformation() {}
/** /**
* Updates all variables. * Updates all variables.
@ -337,14 +348,14 @@ public final class EngineInformation {
* @since v1-alpha1 * @since v1-alpha1
*/ */
public static synchronized void update() { public static synchronized void update() {
Logger.diag("Updating engine information"); logger.diag("Updating engine information");
// Load properties from bundled gradle.properties // Load properties from bundled gradle.properties
Properties gradleProperties = new Properties(); Properties gradleProperties = new Properties();
InputStream gradleStream = EngineInformation.class.getClassLoader().getResourceAsStream("sosengine-gradle.properties"); InputStream gradleStream = EngineInformation.class.getClassLoader().getResourceAsStream("sosengine-gradle.properties");
if (gradleStream == null) { if (gradleStream == null) {
Logger.crash("Unable to load build information: The bundled gradle.properties file could not be found."); logger.crash("Unable to load build information: The bundled gradle.properties file could not be found.");
return; return;
} }
@ -352,7 +363,8 @@ public final class EngineInformation {
gradleProperties.load(gradleStream); gradleProperties.load(gradleStream);
gradleStream.close(); gradleStream.close();
} catch (IOException exception) { } catch (IOException exception) {
Logger.crash("Unable to load build information: InputStream 'gradleStream' failed", exception); StackTraceParser parser = new StackTraceParser(exception);
logger.crash("Unable to load build information: InputStream 'gradleStream' failed", exception);
return; return;
} }
@ -361,7 +373,7 @@ public final class EngineInformation {
Properties gitProperties = new Properties(); Properties gitProperties = new Properties();
InputStream gitStream = EngineInformation.class.getClassLoader().getResourceAsStream("sosengine-git.properties"); InputStream gitStream = EngineInformation.class.getClassLoader().getResourceAsStream("sosengine-git.properties");
if (gitStream == null) { if (gitStream == null) {
Logger.error("Unable to load build information: The bundled git.properties file could not be found. Did you download a tarball?"); logger.error("Unable to load build information: The bundled git.properties file could not be found. Did you download a tarball?");
// Fake information // Fake information
gitProperties.setProperty("git.total.commit.count", "0"); gitProperties.setProperty("git.total.commit.count", "0");
@ -379,7 +391,8 @@ public final class EngineInformation {
gitProperties.load(gitStream); gitProperties.load(gitStream);
gitStream.close(); gitStream.close();
} catch (IOException exception) { } catch (IOException exception) {
Logger.crash("Unable to load build information: InputStream 'gitStream' failed", exception); StackTraceParser parser = new StackTraceParser(exception);
logger.crash("Unable to load build information: InputStream 'gitStream' failed", exception);
return; return;
} }
} }
@ -416,7 +429,10 @@ public final class EngineInformation {
calendar.setTime(date); calendar.setTime(date);
gitCommitTime = calendar.toZonedDateTime(); gitCommitTime = calendar.toZonedDateTime();
} catch (ParseException exception) { } catch (ParseException exception) {
Logger.crash("Unable to load build information: Can't parse \"" + gitParser.getString("git.commit.time") + "\" using format \"yyyy-MM-dd'T'HH:mmZ\"", exception); StackTraceParser parser = new StackTraceParser(exception);
System.out.println("Unable to load build information: Can't parse \"" + gitParser.getString("git.commit.time") + "\" using format \"yyyy-MM-dd'T'HH:mmZ\"");
System.out.println(parser.getHeader() + "\n" + parser.getStackTrace());
Engine.getInstance().shutdown(69);
return; return;
} }
gitCommitterName = gitParser.getString("git.commit.user.name"); gitCommitterName = gitParser.getString("git.commit.user.name");

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,10 +17,9 @@
* 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.utility.information; package de.staropensource.sosengine.base.data.information;
import de.staropensource.engine.base.logging.Logger; import de.staropensource.sosengine.base.logging.LoggerInstance;
import de.staropensource.engine.base.type.immutable.ImmutableArrayList;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
@ -35,11 +34,19 @@ import java.util.List;
@SuppressWarnings({ "unused" }) @SuppressWarnings({ "unused" })
public final class JvmInformation { public final class JvmInformation {
/** /**
* Creates and initializes an instance of this class. * Contains the {@link LoggerInstance} for this instance.
* *
* @since v1-alpha6 * @see LoggerInstance
* @since v1-alpha2
*/ */
private JvmInformation() {} private static final @NotNull LoggerInstance logger = new LoggerInstance.Builder().setClazz(JvmInformation.class).setOrigin("ENGINE").build();
/**
* Constructs this class.
*
* @since v1-alpha0
*/
public JvmInformation() {}
/** /**
* Returns the Java version this JVM implements. * Returns the Java version this JVM implements.
@ -61,7 +68,7 @@ public final class JvmInformation {
try { try {
return Integer.parseInt(version); return Integer.parseInt(version);
} catch (NumberFormatException exception) { } catch (NumberFormatException exception) {
Logger.crash("Could not parse Java version: Integer conversion failed for string \"" + version + "\"", exception, true); logger.crash("Could not parse Java version: Integer conversion failed for string \"" + version + "\"", exception, true);
throw exception; throw exception;
} }
} }
@ -110,11 +117,11 @@ public final class JvmInformation {
* Returns all arguments passed to the JVM. * Returns all arguments passed to the JVM.
* This excludes all arguments passed to the application. * This excludes all arguments passed to the application.
* *
* @return immutable list with all JVM arguments * @return JVM arguments
* @since v1-alpha0 * @since v1-alpha0
*/ */
public static @NotNull List<@NotNull String> getArguments() { public static @NotNull List<@NotNull String> getArguments() {
return new ImmutableArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments()); return ManagementFactory.getRuntimeMXBean().getInputArguments();
} }
/** /**

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
@ -22,4 +22,4 @@
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
package de.staropensource.engine.base.utility.information; package de.staropensource.sosengine.base.data.information;

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,9 +18,8 @@
*/ */
/** /**
* Contains the core engine code. * Classes which provide or process information.
* *
* @see de.staropensource.engine.base.Engine
* @since v1-alpha0 * @since v1-alpha0
*/ */
package de.staropensource.engine.base; package de.staropensource.sosengine.base.data;

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,12 +17,12 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.utility.Miscellaneous; import de.staropensource.sosengine.base.utility.Miscellaneous;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
@ -33,7 +33,7 @@ import org.jetbrains.annotations.Range;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class FourNumberVersioningSystem implements VersioningSystem { public final class FourNumberVersioningSystem implements VersioningSystem {
/** /**
* Contains the first number vector. * Contains the first number vector.
@ -90,8 +90,7 @@ public final class FourNumberVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a four number-based version string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid

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,11 +17,11 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
@ -32,7 +32,7 @@ import org.jetbrains.annotations.Range;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class OneNumberVersioningSystem implements VersioningSystem { public final class OneNumberVersioningSystem implements VersioningSystem {
/** /**
* Contains the number vector. * Contains the number vector.
@ -53,8 +53,7 @@ public final class OneNumberVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a one number-based version string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid

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,12 +17,12 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.utility.Miscellaneous; import de.staropensource.sosengine.base.utility.Miscellaneous;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -40,7 +40,7 @@ import java.util.List;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class SemanticVersioningSystem implements VersioningSystem { public final class SemanticVersioningSystem implements VersioningSystem {
/** /**
* Contains the {@code MAJOR} vector. * Contains the {@code MAJOR} vector.
@ -109,8 +109,7 @@ public final class SemanticVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a semantic versioning string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid

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,12 +17,12 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.type.VersionType; import de.staropensource.sosengine.base.types.VersionType;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -41,7 +41,7 @@ import java.util.Locale;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class StarOpenSourceVersioningSystem implements VersioningSystem { public final class StarOpenSourceVersioningSystem implements VersioningSystem {
/** /**
* Contains the {@code VERSION} vector. * Contains the {@code VERSION} vector.
@ -110,8 +110,7 @@ public final class StarOpenSourceVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a StarOpenSource versioning string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid
@ -132,7 +131,7 @@ public final class StarOpenSourceVersioningSystem implements VersioningSystem {
String companion = null; String companion = null;
String fork = null; String fork = null;
// Iterate through all characters // Iterate through all chraracters
for (Character character : versionString.toCharArray()) { for (Character character : versionString.toCharArray()) {
switch (parsingId) { switch (parsingId) {
case 0 -> { // 'v' character case 0 -> { // 'v' character

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,12 +17,12 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.utility.Miscellaneous; import de.staropensource.sosengine.base.utility.Miscellaneous;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
@ -33,7 +33,7 @@ import org.jetbrains.annotations.Range;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class ThreeNumberVersioningSystem implements VersioningSystem { public final class ThreeNumberVersioningSystem implements VersioningSystem {
/** /**
* Contains the first number vector. * Contains the first number vector.
@ -78,8 +78,7 @@ public final class ThreeNumberVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a three number-based version string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid

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,12 +17,12 @@
* 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.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import de.staropensource.engine.base.exception.versioning.IncompatibleVersioningSystemException; import de.staropensource.sosengine.base.exceptions.versioning.IncompatibleVersioningSystemException;
import de.staropensource.engine.base.exception.versioning.InvalidVersionStringException; import de.staropensource.sosengine.base.exceptions.versioning.InvalidVersionStringException;
import de.staropensource.engine.base.utility.Miscellaneous; import de.staropensource.sosengine.base.utility.Miscellaneous;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Range; import org.jetbrains.annotations.Range;
@ -33,7 +33,7 @@ import org.jetbrains.annotations.Range;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public final class TwoNumberVersioningSystem implements VersioningSystem { public final class TwoNumberVersioningSystem implements VersioningSystem {
/** /**
* Contains the first number vector. * Contains the first number vector.
@ -66,8 +66,7 @@ public final class TwoNumberVersioningSystem implements VersioningSystem {
} }
/** /**
* Tries to parse the specified version string * Parses a two number-based version string.
* and if successful, return a new instance.
* *
* @param versionString version string to parse * @param versionString version string to parse
* @throws InvalidVersionStringException if the version string is invalid * @throws InvalidVersionStringException if the version string is invalid

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
@ -23,4 +23,4 @@
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
package de.staropensource.engine.base.implementation.versioning; package de.staropensource.sosengine.base.data.versioning;

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,20 @@
* 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.event; package de.staropensource.sosengine.base.events;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
/** /**
* Called in the event of an engine crash. * Called in the event of an engine crash.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public final class EngineCrashEvent implements Event { public final class EngineCrashEvent implements Event {
/** /**
* Creates and initializes an instance of this event. * Constructs this event.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */

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,10 +17,10 @@
* 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.event; package de.staropensource.sosengine.base.events;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
/** /**
* Called when the engine is about to shutdown. * Called when the engine is about to shutdown.
@ -29,7 +29,7 @@ import de.staropensource.engine.base.implementable.helper.EventHelper;
*/ */
public final class EngineShutdownEvent implements Event { public final class EngineShutdownEvent implements Event {
/** /**
* Creates and initializes an instance of this event. * Constructs this event.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */

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,11 +17,11 @@
* 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.event; package de.staropensource.sosengine.base.events;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.engine.base.logging.Logger; import de.staropensource.sosengine.base.logging.Logger;
/** /**
* Called in the event of a soft engine crash * Called in the event of a soft engine crash
@ -31,9 +31,10 @@ import de.staropensource.engine.base.logging.Logger;
* @see Logger#crash(Class, String, String, String, Throwable, boolean) * @see Logger#crash(Class, String, String, String, Throwable, boolean)
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public final class EngineSoftCrashEvent implements Event { public final class EngineSoftCrashEvent implements Event {
/** /**
* Creates and initializes an instance of this event. * Constructs this event.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */

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,11 +17,11 @@
* 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.event; package de.staropensource.sosengine.base.events;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.engine.base.type.logging.LogLevel; import de.staropensource.sosengine.base.types.logging.LogLevel;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -30,9 +30,10 @@ import org.jetbrains.annotations.Nullable;
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */
@SuppressWarnings({ "unused" })
public final class LogEvent implements Event { public final class LogEvent implements Event {
/** /**
* Creates and initializes an instance of this event. * Constructs this event.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */

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,11 +17,11 @@
* 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.event; package de.staropensource.sosengine.base.events;
import de.staropensource.engine.base.implementable.Event; import de.staropensource.sosengine.base.classes.Event;
import de.staropensource.engine.base.implementable.helper.EventHelper; import de.staropensource.sosengine.base.classes.helpers.EventHelper;
import de.staropensource.engine.base.utility.Miscellaneous; import de.staropensource.sosengine.base.utility.Miscellaneous;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@ -32,7 +32,7 @@ import org.jetbrains.annotations.NotNull;
*/ */
public final class ThrowableCatchEvent implements Event { public final class ThrowableCatchEvent implements Event {
/** /**
* Creates and initializes an instance of this event. * Constructs this event.
* *
* @since v1-alpha0 * @since v1-alpha0
*/ */

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
@ -22,4 +22,4 @@
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
package de.staropensource.engine.base.event; package de.staropensource.sosengine.base.events;

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,30 +17,34 @@
* 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.exception; package de.staropensource.sosengine.base.exceptions;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Thrown the throwing method is not allowed to be called. * Thrown when the caller class is not allowed to call the throwing method.
* * <p>
* @since v1-alpha4 * Not to be confused with {@link de.staropensource.sosengine.base.exceptions.reflection.NoAccessException},
*/ * which handles access violations of reflection objects.
public class IllegalAccessException extends RuntimeException {
/**
* Creates and initializes an instance of this exception.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
public IllegalAccessException() {} @SuppressWarnings({ "unused" })
public class NoAccessException extends RuntimeException {
/**
* Constructs this exception.
*
* @since v1-alpha2
*/
public NoAccessException() {}
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param message message * @param message message
* @since v1-alpha2 * @since v1-alpha2
*/ */
public IllegalAccessException(@NotNull String message) { public NoAccessException(@NotNull String message) {
super(message); super(message);
} }
} }

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,7 +17,7 @@
* 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.exception; package de.staropensource.sosengine.base.exceptions;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
*/ */
public class ParserException extends RuntimeException { public class ParserException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param message parsing error * @param message parsing error
* @since v1-alpha2 * @since v1-alpha2

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,9 +17,9 @@
* 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.exception; package de.staropensource.sosengine.base.exceptions;
import de.staropensource.engine.base.type.Tristate; import de.staropensource.sosengine.base.types.Tristate;
/** /**
* Thrown when converting a {@link Tristate} into a {@link Boolean} fails. * Thrown when converting a {@link Tristate} into a {@link Boolean} fails.
@ -32,7 +32,7 @@ import de.staropensource.engine.base.type.Tristate;
*/ */
public class TristateConversionException extends RuntimeException { public class TristateConversionException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */

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,7 +17,7 @@
* 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.exception; package de.staropensource.sosengine.base.exceptions;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
*/ */
public class UnexpectedCheckEndException extends RuntimeException { public class UnexpectedCheckEndException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param checkOccurrence the sequence of checks that failed * @param checkOccurrence the sequence of checks that failed
* @since v1-alpha2 * @since v1-alpha2
@ -38,7 +38,7 @@ public class UnexpectedCheckEndException extends RuntimeException {
} }
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */

View file

@ -0,0 +1,64 @@
/*
* 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.exceptions;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
/**
* Thrown when a method invokes another method and it throws an unhandled {@link Throwable}.
*
* @since v1-alpha1
*/
@Getter
@SuppressWarnings({ "unused", "JavadocDeclaration" })
public class UnexpectedThrowableException extends Exception {
/**
* Contains the throwable supplied to the constructor.
*
* @since v1-alpha1
* -- GETTER --
* Returns the throwable supplied by the constructor.
*
* @return throwable
* @since v1-alpha1
*/
private final @NotNull Throwable throwable;
/**
* Constructs this exception.
*
* @param throwable throwable
* @param message message
*/
public UnexpectedThrowableException(@NotNull Throwable throwable, @NotNull String message) {
super(message);
this.throwable = throwable;
}
/**
* Constructs this exception.
*
* @param throwable throwable
*/
public UnexpectedThrowableException(@NotNull Throwable throwable) {
this.throwable = throwable;
}
}

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,9 +17,9 @@
* 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.exception.dependency; package de.staropensource.sosengine.base.exceptions.dependency;
import de.staropensource.engine.base.utility.DependencyResolver; import de.staropensource.sosengine.base.utility.DependencyResolver;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@ -27,9 +27,10 @@ import org.jetbrains.annotations.NotNull;
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
@SuppressWarnings({ "unused" })
public class DependencyCycleException extends RuntimeException { public class DependencyCycleException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param path cycle path * @param path cycle path
* @since v1-alpha1 * @since v1-alpha1

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,14 +17,14 @@
* 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.exception.dependency; package de.staropensource.sosengine.base.exceptions.dependency;
import de.staropensource.engine.base.type.DependencyVector; import de.staropensource.sosengine.base.types.DependencyVector;
import de.staropensource.engine.base.utility.DependencyResolver; import de.staropensource.sosengine.base.utility.DependencyResolver;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.Map;
/** /**
* Thrown when the {@link DependencyResolver} cannot resolve one * Thrown when the {@link DependencyResolver} cannot resolve one
@ -33,28 +33,34 @@ import java.util.List;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public class UnmetDependenciesException extends Exception { public class UnmetDependenciesException extends Exception {
/** /**
* Contains the unmet dependencies list supplied to the constructor. * Contains the unmet dependencies list supplied to the constructor.
* <p>
* The key contains the {@link DependencyVector} that
* has unmet dependencies, while the value contains the error.
* *
* @since v1-alpha4 * @since v1-alpha1
* -- GETTER -- * -- GETTER --
* Returns the unmet dependencies list supplied to the constructor. * Returns the unmet dependencies list supplied to the constructor.
* <p>
* The key contains the {@link DependencyVector} that
* has unmet dependencies, while the value contains the error.
* *
* @return unmet dependencies list * @return unmet dependencies list
* @since v1-alpha4 * @since v1-alpha1
*/ */
private final @NotNull List<@NotNull String> unmetDependencies; private final @NotNull Map<@NotNull DependencyVector, @NotNull String> unmetDependencies;
/** /**
* Creates and initializes an instance of this event. * Constructs this exception.
* *
* @param unmetDependencies map of all unmet dependencies * @param unmetDependencies map of all unmet dependencies
* @see #unmetDependencies * @see #unmetDependencies
* @since v1-alpha4 * @since v1-alpha1
*/ */
public UnmetDependenciesException(@NotNull List<@NotNull String> unmetDependencies) { public UnmetDependenciesException(@NotNull Map<@NotNull DependencyVector, @NotNull String> unmetDependencies) {
this.unmetDependencies = unmetDependencies; this.unmetDependencies = unmetDependencies;
} }
} }

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
@ -20,7 +20,7 @@
/** /**
* Exceptions related to dependency resolving. * Exceptions related to dependency resolving.
* *
* @see de.staropensource.engine.base.utility.DependencyResolver * @see de.staropensource.sosengine.base.utility.DependencyResolver
* @since v1-alpha1 * @since v1-alpha1
*/ */
package de.staropensource.engine.base.exception.dependency; package de.staropensource.sosengine.base.exceptions.dependency;

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
@ -22,4 +22,4 @@
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
package de.staropensource.engine.base.exception; package de.staropensource.sosengine.base.exceptions;

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,10 +17,10 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import de.staropensource.engine.base.type.reflection.ClassType; import de.staropensource.sosengine.base.types.reflection.ClassType;
import de.staropensource.engine.base.utility.ListFormatter; import de.staropensource.sosengine.base.utility.ListFormatter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@ -28,20 +28,21 @@ import org.jetbrains.annotations.NotNull;
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@SuppressWarnings({ "unused" })
public class IncompatibleTypeException extends RuntimeException { public class IncompatibleTypeException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param methodName name of the method that failed * @param methodName name of the method that failed
* @param requiredClassType class type received by the method * @param requiredClassType class type received by the method
* @param compatibleTypes class types the method is compatible with * @param compatibleTypes class types the method is compatible with
*/ */
public IncompatibleTypeException(@NotNull String methodName, @NotNull ClassType requiredClassType, @NotNull ClassType @NotNull [] compatibleTypes) { public IncompatibleTypeException(@NotNull String methodName, @NotNull ClassType requiredClassType, @NotNull ClassType[] compatibleTypes) {
super("The method ReflectionClass#" + methodName + " only applies to type(s) " + ListFormatter.formatArray(compatibleTypes) + ", not " + requiredClassType.name()); super("The method ReflectionClass#" + methodName + " only applies to type(s) " + ListFormatter.formatArray(compatibleTypes) + ", not " + requiredClassType.name());
} }
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param methodName name of the method that failed * @param methodName name of the method that failed
* @param requiredClassType class type received by the method * @param requiredClassType class type received by the method

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,7 +17,7 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
*/ */
public class InstanceMethodFromStaticContextException extends Exception { public class InstanceMethodFromStaticContextException extends Exception {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param methodName name of the method * @param methodName name of the method
* @since v1-alpha2 * @since v1-alpha2

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,9 +17,9 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import de.staropensource.engine.base.reflection.ReflectionClass; import de.staropensource.sosengine.base.reflection.ReflectionClass;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@ -27,9 +27,10 @@ import org.jetbrains.annotations.NotNull;
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@SuppressWarnings({ "unused" })
public class InvalidFieldException extends Exception { public class InvalidFieldException extends Exception {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param clazz caller {@link ReflectionClass} * @param clazz caller {@link ReflectionClass}
* @param fieldName name of the invalid field * @param fieldName name of the invalid field

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,9 +17,9 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import de.staropensource.engine.base.reflection.ReflectionClass; import de.staropensource.sosengine.base.reflection.ReflectionClass;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
@ -27,9 +27,10 @@ import org.jetbrains.annotations.NotNull;
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@SuppressWarnings({ "unused" })
public class InvalidMethodException extends Exception { public class InvalidMethodException extends Exception {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param clazz caller {@link ReflectionClass} * @param clazz caller {@link ReflectionClass}
* @param fieldName name of the invalid method * @param fieldName name of the invalid method

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,23 +17,23 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
/** /**
* Thrown when a method could not be found due to an invalid method signature. * Thrown when a method could not be found due to an invalid method signature.
* *
* @since v1-alpha5 * @since v1-alpha2
*/ */
public class InvalidMethodSignatureException extends Exception { @SuppressWarnings({ "unused" })
public class InvalidMethodSignature extends Exception {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param methodName method name * @param methodName method name
* @since v1-alpha5
*/ */
public InvalidMethodSignatureException(@NotNull String methodName) { public InvalidMethodSignature(@NotNull String methodName) {
super("Method " + methodName + " has a different method signature"); super("Method " + methodName + " has a different method signature");
} }
} }

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,7 +17,7 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -26,9 +26,10 @@ import org.jetbrains.annotations.NotNull;
* *
* @since v1-alpha2 * @since v1-alpha2
*/ */
@SuppressWarnings({ "unused" })
public class NoAccessException extends Exception { public class NoAccessException extends Exception {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param type {@code class}, {@code method} or {@code field} * @param type {@code class}, {@code method} or {@code field}
* @param name class, method or field name * @param name class, method or field name

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,7 +17,7 @@
* 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.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull;
* @since v1-alpha2 * @since v1-alpha2
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public class StaticInitializerException extends Exception { public class StaticInitializerException extends Exception {
/** /**
* Contains the throwable thrown by the static initializer. * Contains the throwable thrown by the static initializer.
@ -43,7 +43,7 @@ public class StaticInitializerException extends Exception {
private final @NotNull Throwable throwable; private final @NotNull Throwable throwable;
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param throwable throwable thrown by the static initializer * @param throwable throwable thrown by the static initializer
* @since v1-alpha2 * @since v1-alpha2

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
@ -20,7 +20,7 @@
/** /**
* Exceptions related to reflection. * Exceptions related to reflection.
* *
* @see de.staropensource.engine.base.reflection * @see de.staropensource.sosengine.base.reflection
* @since v1-alpha2 * @since v1-alpha2
*/ */
package de.staropensource.engine.base.exception.reflection; package de.staropensource.sosengine.base.exceptions.reflection;

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,9 +17,9 @@
* 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.exception.versioning; package de.staropensource.sosengine.base.exceptions.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
/** /**
* Thrown when trying to compare a {@link VersioningSystem} against another * Thrown when trying to compare a {@link VersioningSystem} against another
@ -27,9 +27,10 @@ import de.staropensource.engine.base.implementable.VersioningSystem;
* *
* @since v1-alpha1 * @since v1-alpha1
*/ */
@SuppressWarnings({ "unused" })
public class IncompatibleVersioningSystemException extends RuntimeException { public class IncompatibleVersioningSystemException extends RuntimeException {
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param required required versioning system ie. the versioning system throwing this error * @param required required versioning system ie. the versioning system throwing this error
* @param found found versioning system ie. the incompatible one * @param found found versioning system ie. the incompatible one

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,9 +17,9 @@
* 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.exception.versioning; package de.staropensource.sosengine.base.exceptions.versioning;
import de.staropensource.engine.base.implementable.VersioningSystem; import de.staropensource.sosengine.base.classes.VersioningSystem;
import lombok.Getter; import lombok.Getter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -32,7 +32,7 @@ import org.jetbrains.annotations.Nullable;
* @since v1-alpha1 * @since v1-alpha1
*/ */
@Getter @Getter
@SuppressWarnings({ "JavadocDeclaration" }) @SuppressWarnings({ "unused", "JavadocDeclaration" })
public class InvalidVersionStringException extends Exception { public class InvalidVersionStringException extends Exception {
/** /**
* Contains the throwable supplied to the constructor. * Contains the throwable supplied to the constructor.
@ -51,7 +51,7 @@ public class InvalidVersionStringException extends Exception {
private final @Nullable Throwable throwable; private final @Nullable Throwable throwable;
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param versioningSystem versioning system that is unable to parse version strings * @param versioningSystem versioning system that is unable to parse version strings
* @param versionString version string {@code a} * @param versionString version string {@code a}
@ -65,7 +65,7 @@ public class InvalidVersionStringException extends Exception {
} }
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param versioningSystem versioning system that is unable to parse version strings * @param versioningSystem versioning system that is unable to parse version strings
* @param versionString version string {@code a} * @param versionString version string {@code a}
@ -78,7 +78,7 @@ public class InvalidVersionStringException extends Exception {
} }
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param versioningSystem versioning system that is unable to parse version strings * @param versioningSystem versioning system that is unable to parse version strings
* @param versionString version string {@code a} * @param versionString version string {@code a}
@ -91,7 +91,7 @@ public class InvalidVersionStringException extends Exception {
} }
/** /**
* Creates and initializes an instance of this exception. * Constructs this exception.
* *
* @param versioningSystem versioning system that is unable to parse version strings * @param versioningSystem versioning system that is unable to parse version strings
* @param versionString version string {@code a} * @param versionString version string {@code a}

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,9 +18,9 @@
*/ */
/** /**
* Exceptions thrown by implementations of {@link de.staropensource.engine.base.implementable.VersioningSystem}s. * Exceptions thrown by implementations of {@link de.staropensource.sosengine.base.classes.VersioningSystem}s.
* *
* @see de.staropensource.engine.base.implementable.VersioningSystem * @see de.staropensource.sosengine.base.classes.VersioningSystem
* @since v1-alpha1 * @since v1-alpha1
*/ */
package de.staropensource.engine.base.exception.versioning; package de.staropensource.sosengine.base.exceptions.versioning;

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