+++ /dev/null
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 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 General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is 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. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- 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.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- 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 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. Use with the GNU Affero General Public License.
-
- 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 Affero 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 special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU 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 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 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 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 General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <https://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- 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 GPL, see
-<https://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<https://www.gnu.org/licenses/why-not-lgpl.html>.
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
-
- This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
- 0. Additional Definitions.
-
- As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
- "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
- An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
- A "Combined Work" is a work produced by combining or linking an
-Application with the Library. The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
- The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
- The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
- 1. Exception to Section 3 of the GNU GPL.
-
- You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
- 2. Conveying Modified Versions.
-
- If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
- a) under this License, provided that you make a good faith effort to
- ensure that, in the event an Application does not supply the
- function or data, the facility still operates, and performs
- whatever part of its purpose remains meaningful, or
-
- b) under the GNU GPL, with none of the additional permissions of
- this License applicable to that copy.
-
- 3. Object Code Incorporating Material from Library Header Files.
-
- The object code form of an Application may incorporate material from
-a header file that is part of the Library. You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
- a) Give prominent notice with each copy of the object code that the
- Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the object code with a copy of the GNU GPL and this license
- document.
-
- 4. Combined Works.
-
- You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
- a) Give prominent notice with each copy of the Combined Work that
- the Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
- document.
-
- c) For a Combined Work that displays copyright notices during
- execution, include the copyright notice for the Library among
- these notices, as well as a reference directing the user to the
- copies of the GNU GPL and this license document.
-
- d) Do one of the following:
-
- 0) Convey the Minimal Corresponding Source under the terms of this
- License, and the Corresponding Application Code in a form
- suitable for, and under terms that permit, the user to
- recombine or relink the Application with a modified version of
- the Linked Version to produce a modified Combined Work, in the
- manner specified by section 6 of the GNU GPL for conveying
- Corresponding Source.
-
- 1) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (a) uses at run time
- a copy of the Library already present on the user's computer
- system, and (b) will operate properly with a modified version
- of the Library that is interface-compatible with the Linked
- Version.
-
- e) Provide Installation Information, but only if you would otherwise
- be required to provide such information under section 6 of the
- GNU GPL, and only to the extent that such information is
- necessary to install and execute a modified version of the
- Combined Work produced by recombining or relinking the
- Application with a modified version of the Linked Version. (If
- you use option 4d0, the Installation Information must accompany
- the Minimal Corresponding Source and Corresponding Application
- Code. If you use option 4d1, you must provide the Installation
- Information in the manner specified by section 6 of the GNU GPL
- for conveying Corresponding Source.)
-
- 5. Combined Libraries.
-
- You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
- a) Accompany the combined library with a copy of the same work based
- on the Library, uncombined with any other library facilities,
- conveyed under the terms of this License.
-
- b) Give prominent notice with the combined library that part of it
- is a work based on the Library, and explaining where to find the
- accompanying uncombined form of the same work.
-
- 6. Revised Versions of the GNU Lesser General Public License.
-
- The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser 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
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
- If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+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 this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+\f
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+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
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser 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 Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "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
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY 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
+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+\f
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey 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 library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
all: osgi
$(MAKE) -f Makefile-rcp.mk all
+
+install: osgi-install
+
+uninstall: osgi-uninstall
A2_CATEGORY = org.argeo.cms
org.argeo.cms.lib.jetty \
org.argeo.cms.lib.dbus \
org.argeo.cms.lib.sshd \
+org.argeo.cms.jshell \
org.argeo.cms.cli \
osgi/equinox/org.argeo.cms.lib.equinox \
swt/org.argeo.swt.minidesktop \
swt/org.argeo.cms.swt \
-swt/org.argeo.cms.e4 \
swt/rap/org.argeo.swt.specific.rap \
swt/rap/org.argeo.cms.swt.rap \
-swt/rap/org.argeo.cms.e4.rap \
DEP_CATEGORIES = \
+crypto/fips/org.argeo.tp.crypto \
org.argeo.tp \
-org.argeo.tp.crypto \
-org.argeo.tp.jetty \
+org.argeo.tp.httpd \
osgi/api/org.argeo.tp.osgi \
osgi/equinox/org.argeo.tp.eclipse \
swt/rap/org.argeo.tp.swt \
-swt/rap/org.argeo.tp.swt.workbench \
$(A2_CATEGORY) \
swt/$(A2_CATEGORY) \
swt/rap/$(A2_CATEGORY) \
BUNDLES = \
swt/rcp/org.argeo.swt.specific.rcp \
swt/rcp/org.argeo.cms.swt.rcp \
-swt/rcp/org.argeo.cms.e4.rcp \
DEP_CATEGORIES = \
org.argeo.cms \
swt/org.argeo.cms \
org.argeo.tp \
-org.argeo.tp.crypto \
org.argeo.tp.jetty \
osgi/equinox/org.argeo.tp.eclipse \
osgi/api/org.argeo.tp.osgi \
swt/rcp/org.argeo.tp.swt \
lib/linux/x86_64/swt/rcp/org.argeo.tp.swt \
-swt/rcp/org.argeo.tp.swt.workbench \
-
clean:
rm -rf $(BUILD_BASE)
--- /dev/null
+Argeo Commons - A lightweight integration framework
+
+Copyright 2007-2023 Mathieu Baudier
+Copyright 2012-2023 Argeo GmbH
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 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
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License
+along with this program; if not, see <https://www.gnu.org/licenses>.
+
+## Alternative licenses
+
+As an alternative, this Program is also provided to you under the terms and
+conditions of the Eclipse Public License version 2.0 or any later version.
+A copy of the Eclipse Public License version 2.0 is available at
+http://www.eclipse.org/legal/epl-2.0.
+
+This Source Code may also be made available under the following
+Secondary Licenses when the conditions for such availability set forth
+in the Eclipse Public License, v. 2.0 are satisfied:
+GNU General Public License, version 2.0, or any later versions of that license,
+with additional EPL and JCR permissions (these additional permissions being
+detailed hereafter).
+
+## Additional Permissions (when applicable)
+
+In case you decide to relicense this program to the GNU General Public License
+version 2.0, or any later version, the copyright holders of Argeo Commons give
+you the following additional permissions:
+
+# Eclipse Public License Permission
+
+Linking Argeo Commons statically or dynamically with other modules is making a
+combined work based on Argeo Commons. Thus, the terms and conditions of the GNU
+General Public License cover the whole combination when this license becomes
+applicable.
+
+In addition, as a special exception, the copyright holders of Argeo Commons give
+you permission to combine Argeo Commons with any program released under the
+terms and conditions of the Eclipse Public License v1.0, v2.0 (even without a
+Secondary License enabled) or any later version of this license. You may copy
+and distribute such a system following the terms of the GNU GPL for Argeo Commons
+and the licenses of the other code concerned, provided that you include the
+source code of that other code when and as the GNU GPL requires distribution of
+source code.
+
+Note that people who make modified versions of Argeo Commons are not obligated
+to grant this special exception for their modified versions; it is their choice
+whether to do so. The GNU General Public License gives permission to release a
+modified version without this exception; this exception also makes it possible
+to release a modified version which carries forward this exception.
+
+# Java Content Repository API version 2.0 Permission
+
+Linking Argeo Commons statically or dynamically with other modules is making a
+combined work based on Argeo Commons. Thus, the terms and conditions of the GNU
+General Public License cover the whole combination when this license becomes
+applicable.
+
+In addition, as a special exception, the copyright holders of Argeo Commons give
+you permission to combine Argeo Commons with code included in the standard
+release of the JCR API version 2.0 (and this version only), licensed under the
+Day Specification License and the Day JCR License. You may copy and distribute
+such a system following the terms of the GNU GPL for Argeo Commons and the
+licenses of the other code concerned.
+
+Copies of the Day Specification License and the Day JCR License
+are expected to be available here:
+https://jackrabbit.apache.org/jcr/jcr.html
+
+Note that people who make modified versions of Argeo Commons are not obligated
+to grant this special exception for their modified versions; it is their choice
+whether to do so. The GNU General Public License gives permission to release a
+modified version without this exception; this exception also makes it possible
+to release a modified version which carries forward this exception.
import java.util.Locale;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
import javax.security.auth.Subject;
import javax.xml.namespace.NamespaceContext;
+import org.argeo.api.acr.search.BasicSearch;
+
+/** An authenticated session to a repository. */
public interface ContentSession extends NamespaceContext {
Subject getSubject();
Locale getLocale();
Content get(String path);
-
+
boolean exists(String path);
CompletionStage<ContentSession> edit(Consumer<ContentSession> work);
+
+ Stream<Content> search(Consumer<BasicSearch> search);
}
--- /dev/null
+package org.argeo.api.acr.search;
+
+public class AndFilter extends ContentFilter<Intersection> {
+
+ public AndFilter() {
+ super(Intersection.class);
+ }
+
+}
--- /dev/null
+package org.argeo.api.acr.search;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Consumer;
+
+import javax.xml.namespace.QName;
+
+import org.argeo.api.acr.DName;
+import org.argeo.api.acr.QNamed;
+
+public class BasicSearch {
+
+ private List<QName> select = new ArrayList<>();
+ private List<Scope> from = new ArrayList<>();
+
+ private ContentFilter<? extends Composition> where;
+
+ public BasicSearch select(QNamed... attr) {
+ for (QNamed q : attr)
+ select.add(q.qName());
+ return this;
+ }
+
+ public BasicSearch select(QName... attr) {
+ select.addAll(Arrays.asList(attr));
+ return this;
+ }
+
+ public BasicSearch from(URI uri) {
+ return from(uri, Depth.INFINITTY);
+ }
+
+ public BasicSearch from(URI uri, Depth depth) {
+ Objects.requireNonNull(uri);
+ Objects.requireNonNull(depth);
+ Scope scope = new Scope(uri, depth);
+ from.add(scope);
+ return this;
+ }
+
+ public BasicSearch where(Consumer<AndFilter> and) {
+ if (where != null)
+ throw new IllegalStateException("A where clause is already set");
+ AndFilter subFilter = new AndFilter();
+ and.accept(subFilter);
+ where = subFilter;
+ return this;
+ }
+
+ public List<QName> getSelect() {
+ return select;
+ }
+
+ public List<Scope> getFrom() {
+ return from;
+ }
+
+ public ContentFilter<? extends Composition> getWhere() {
+ return where;
+ }
+
+ public static enum Depth {
+ ZERO, ONE, INFINITTY;
+ }
+
+ public static class Scope {
+
+ URI uri;
+ Depth depth;
+
+ public Scope(URI uri, Depth depth) {
+ this.uri = uri;
+ this.depth = depth;
+ }
+
+ public URI getUri() {
+ return uri;
+ }
+
+ public Depth getDepth() {
+ return depth;
+ }
+
+ }
+
+ static void main(String[] args) {
+ BasicSearch search = new BasicSearch();
+ search.select(DName.creationdate.qName()) //
+ .from(URI.create("/test")) //
+ .where((f) -> f.eq(DName.creationdate.qName(), ""));
+ }
+}
--- /dev/null
+package org.argeo.api.acr.search;
+interface Composition {
+}
+
--- /dev/null
+package org.argeo.api.acr.search;
+
+public interface Constraint {
+}
--- /dev/null
+package org.argeo.api.acr.search;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.function.Consumer;
+
+import javax.xml.namespace.QName;
+
+import org.argeo.api.acr.DName;
+import org.argeo.api.acr.QNamed;
+
+public abstract class ContentFilter<COMPOSITION extends Composition> implements Constraint {
+ private Set<Constraint> constraintss = new HashSet<>();
+
+ private COMPOSITION composition;
+
+ boolean negateNextOperator = false;
+
+ @SuppressWarnings("unchecked")
+ ContentFilter(Class<COMPOSITION> clss) {
+ if (clss == null)
+ this.composition = null;
+ else if (Intersection.class.isAssignableFrom(clss))
+ this.composition = (COMPOSITION) new Intersection(this);
+ else if (Union.class.isAssignableFrom(clss))
+ this.composition = (COMPOSITION) new Union(this);
+ else
+ throw new IllegalArgumentException("Unkown composition " + clss);
+ }
+
+ /*
+ * LOGICAL OPERATORS
+ */
+
+ public COMPOSITION all(Consumer<AndFilter> and) {
+ AndFilter subFilter = new AndFilter();
+ and.accept(subFilter);
+ addConstraint(subFilter);
+ return composition;
+ }
+
+ public COMPOSITION any(Consumer<OrFilter> or) {
+ OrFilter subFilter = new OrFilter();
+ or.accept(subFilter);
+ addConstraint(subFilter);
+ return composition;
+ }
+
+ public ContentFilter<COMPOSITION> not() {
+ negateNextOperator = !negateNextOperator;
+ return this;
+ }
+
+ /*
+ * NON WEBDAV
+ */
+ public COMPOSITION isContentClass(QName... contentClass) {
+ addConstraint(new IsContentClass(contentClass));
+ return composition;
+ }
+
+ public COMPOSITION isContentClass(QNamed... contentClass) {
+ addConstraint(new IsContentClass(contentClass));
+ return composition;
+ }
+
+ /*
+ * COMPARISON OPERATORS
+ */
+
+ public COMPOSITION eq(QName attr, Object value) {
+ addConstraint(new Eq(attr, value));
+ return composition;
+ }
+
+ public COMPOSITION eq(QNamed attr, Object value) {
+ addConstraint(new Eq(attr.qName(), value));
+ return composition;
+ }
+
+ /*
+ * UTILITIES
+ */
+ protected void addConstraint(Constraint operator) {
+ checkAddConstraint();
+ Constraint operatorToAdd;
+ if (negateNextOperator) {
+ operatorToAdd = new Not(operator);
+ negateNextOperator = false;
+ } else {
+ operatorToAdd = operator;
+ }
+ constraintss.add(operatorToAdd);
+ }
+
+ /** Checks that the root operator is not set. */
+ private void checkAddConstraint() {
+ if (composition == null && !constraintss.isEmpty())
+ throw new IllegalStateException("An operator is already registered (" + constraintss.iterator().next()
+ + ") and no composition is defined");
+ }
+
+ /*
+ * ACCESSORs
+ */
+ public Set<Constraint> getConstraints() {
+ return constraintss;
+ }
+
+ public boolean isUnion() {
+ return composition instanceof Union;
+ }
+
+ /*
+ * CLASSES
+ */
+
+ public static class Not implements Constraint {
+ final Constraint negated;
+
+ public Not(Constraint negated) {
+ this.negated = negated;
+ }
+
+ public Constraint getNegated() {
+ return negated;
+ }
+
+ }
+
+ public static class Eq implements Constraint {
+ final QName prop;
+ final Object value;
+
+ public Eq(QName prop, Object value) {
+ super();
+ this.prop = prop;
+ this.value = value;
+ }
+
+ public QName getProp() {
+ return prop;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ }
+
+ public static class IsContentClass implements Constraint {
+ final QName[] contentClasses;
+
+ public IsContentClass(QName[] contentClasses) {
+ this.contentClasses = contentClasses;
+ }
+
+ public IsContentClass(QNamed[] contentClasses) {
+ this.contentClasses = new QName[contentClasses.length];
+ for (int i = 0; i < contentClasses.length; i++)
+ this.contentClasses[i] = contentClasses[i].qName();
+ }
+
+ public QName[] getContentClasses() {
+ return contentClasses;
+ }
+
+ }
+
+ public static void main(String[] args) {
+ AndFilter filter = new AndFilter();
+ filter.eq(new QName("test"), "test").and().not().eq(new QName("type"), "integer");
+
+ OrFilter unionFilter = new OrFilter();
+ unionFilter.all((f) -> {
+ f.eq(DName.displayname, "").and().eq(DName.creationdate, "");
+ }).or().not().any((f) -> {
+ f.eq(DName.creationdate, "").or().eq(DName.displayname, "");
+ });
+
+ }
+
+}
--- /dev/null
+package org.argeo.api.acr.search;
+class Intersection implements Composition {
+ ContentFilter<Intersection> filter;
+
+ @SuppressWarnings("unchecked")
+ public Intersection(ContentFilter<?> filter) {
+ this.filter = (ContentFilter<Intersection>) filter;
+ }
+
+ public ContentFilter<Intersection> and() {
+ return filter;
+ }
+
+}
+
--- /dev/null
+package org.argeo.api.acr.search;
+
+public class OrFilter extends ContentFilter<Union> {
+
+ public OrFilter() {
+ super(Union.class);
+ }
+
+}
--- /dev/null
+package org.argeo.api.acr.search;
+
+class Union implements Composition {
+ ContentFilter<Union> filter;
+
+ @SuppressWarnings("unchecked")
+ public Union(ContentFilter<?> filter) {
+ this.filter = (ContentFilter<Union>) filter;
+ }
+
+ public ContentFilter<Union> or() {
+ return filter;
+ }
+
+}
package org.argeo.api.acr.spi;
import java.util.Iterator;
+import java.util.Spliterator;
import javax.xml.namespace.NamespaceContext;
+import org.argeo.api.acr.Content;
+import org.argeo.api.acr.search.BasicSearch;
+
public interface ContentProvider extends NamespaceContext {
ProvidedContent get(ProvidedSession session, String relativePath);
return prefixes.hasNext() ? prefixes.next() : null;
}
+ default Spliterator<Content> search(ProvidedSession session, BasicSearch search, String relPath) {
+ throw new UnsupportedOperationException();
+ }
+
// default ContentName parsePrefixedName(String nameWithPrefix) {
// return NamespaceUtils.parsePrefixedName(this, nameWithPrefix);
// }
/** A running node process. */
public interface CmsState {
+ /** Local host on which this state is running. */
String getHostname();
+ /** Since when this state has been available. */
Long getAvailableSince();
UUID getUuid();
+ /** A deploy property, or <code>null</code> if it is not set. */
String getDeployProperty(String property);
/**
*/
List<String> getDeployProperties(String property);
+ /** A local path in the data area. */
Path getDataPath(String relativePath);
+
+ /** A local path in the state area. */
+ Path getStatePath(String relativePath);
}
import java.util.UUID;
/**
- * An {@link UuidFactory} which does not implement any algorith and returns
+ * An {@link UuidFactory} which does not implement any algorithm and returns
* {@link UnsupportedOperationException} for methods requiring them. Only
* {@link UuidFactory#get()} and {@link UuidFactory#randomUUID()} are
* implemented, trivially based on {@link UUID#randomUUID()}. It can be useful
- * as a base class for partial implementations, or whren only random
+ * as a base class for partial implementations, or when only random
* {@link UUID}s are needed, but one wants to integrate with this UUID API via
* {@link UuidFactory}.
*/
Main-Class: org.argeo.cms.cli.ArgeoCli
+# ls -1; ls -1 ../log/syslogger/org.argeo.tp/*; ls -1 ../org.argeo.tp/*; ls -1 ../crypto/fips/org.argeo.tp.crypto/* ; ls -1 ../osgi/equinox/org.argeo.cms/*; ls -1 ../osgi/equinox/org.argeo.tp.osgi/*;
+
Class-Path: \
org.argeo.api.acr.2.1.jar \
org.argeo.api.cli.2.1.jar \
org.argeo.api.cms.2.1.jar \
+org.argeo.api.register.2.1.jar \
org.argeo.api.uuid.2.1.jar \
org.argeo.cms.2.1.jar \
+org.argeo.cms.cli.2.1.jar \
org.argeo.cms.ee.2.1.jar \
-../osgi/equinox/org.argeo.cms/org.argeo.cms.lib.equinox.2.1.jar \
+org.argeo.cms.lib.dbus.2.1.jar \
org.argeo.cms.lib.jetty.2.1.jar \
org.argeo.cms.lib.sshd.2.1.jar \
org.argeo.cms.ux.2.1.jar \
org.argeo.init.2.1.jar \
-org.argeo.util.2.1.jar \
-../org.argeo.tp/com.fasterxml.jackson.core.jackson-annotations.2.13.jar \
-../org.argeo.tp/com.fasterxml.jackson.core.jackson-core.2.13.jar \
-../org.argeo.tp/com.fasterxml.jackson.core.jackson-databind.2.13.jar \
-../org.argeo.tp/com.googlecode.javaewah.JavaEWAH.1.1.jar \
-../org.argeo.tp/de.thjom.java.systemd.2.1.jar \
+../log/syslogger/org.argeo.tp/org.argeo.tp.syslogger.2.1.jar \
+../org.argeo.tp/com.fasterxml.jackson.core.jackson.annotations.2.14.jar \
+../org.argeo.tp/com.fasterxml.jackson.core.jackson.core.2.14.jar \
+../org.argeo.tp/com.fasterxml.jackson.core.jackson.databind.2.14.jar \
../org.argeo.tp/javax.servlet.4.0.jar \
../org.argeo.tp/javax.websocket.1.1.jar \
../org.argeo.tp/org.apache.batik.1.16.jar \
../org.argeo.tp/org.apache.batik.i18n.1.16.jar \
../org.argeo.tp/org.apache.batik.util.1.16.jar \
../org.argeo.tp/org.apache.commons.cli.1.5.jar \
-../org.argeo.tp/org.apache.commons.fileupload.1.4.jar \
+../org.argeo.tp/org.apache.commons.codec.1.15.jar \
+../org.argeo.tp/org.apache.commons.compress.1.22.jar \
+../org.argeo.tp/org.apache.commons.fileupload.1.5.jar \
../org.argeo.tp/org.apache.commons.io.2.11.jar \
../org.argeo.tp/org.apache.httpcomponents.httpclient.4.5.jar \
../org.argeo.tp/org.apache.httpcomponents.httpcore.4.4.jar \
../org.argeo.tp/org.apache.httpcomponents.httpmime.4.5.jar \
+../org.argeo.tp/org.apache.sshd.2.9.jar \
+../org.argeo.tp/org.apache.sshd.cli.2.9.jar \
+../org.argeo.tp/org.apache.sshd.git.2.9.jar \
+../org.argeo.tp/org.apache.sshd.putty.2.9.jar \
+../org.argeo.tp/org.apache.sshd.scp.2.9.jar \
+../org.argeo.tp/org.apache.sshd.sftp.2.9.jar \
+../org.argeo.tp/org.apache.tomcat.jni.9.0.jar \
../org.argeo.tp/org.apache.xalan.2.7.jar \
../org.argeo.tp/org.apache.xerces.2.12.jar \
-../org.argeo.tp/org.apache.xmlgraphics.2.7.jar \
+../org.argeo.tp/org.apache.xmlgraphics.2.8.jar \
../org.argeo.tp/org.apache.xml.resolver.1.2.jar \
-../org.argeo.tp/org.argeo.ext.slf4j.2.3.jar \
-../org.argeo.tp/org.eclipse.jgit.6.3.jar \
../org.argeo.tp/org.freeedesktop.dbus.4.2.jar \
-../org.argeo.tp/org.slf4j.api.1.7.jar \
-../org.argeo.tp/org.slf4j.commons.logging.1.7.jar \
+../org.argeo.tp/org.h2.2.1.jar \
+../org.argeo.tp/org.postgresql.jdbc.42.5.jar \
+../org.argeo.tp/org.tukaani.xz.1.9.jar \
../org.argeo.tp/org.w3c.css.sac.1.3.jar \
../org.argeo.tp/org.w3c.dom.smil.1.0.jar \
../org.argeo.tp/org.w3c.dom.svg.1.1.jar \
-../org.argeo.tp.crypto/bcmail.1.72.jar \
-../org.argeo.tp.crypto/bcpg.1.72.jar \
-../org.argeo.tp.crypto/bcpkix.1.72.jar \
-../org.argeo.tp.crypto/bcprov.1.72.jar \
-../org.argeo.tp.crypto/bcutil.1.72.jar \
-../org.argeo.tp.crypto/net.i2p.crypto.eddsa.0.3.jar \
-../org.argeo.tp.crypto/org.apache.sshd.2.9.jar \
-../org.argeo.tp.crypto/org.apache.sshd.cli.2.9.jar \
-../org.argeo.tp.crypto/org.apache.sshd.git.2.9.jar \
-../org.argeo.tp.crypto/org.apache.sshd.putty.2.9.jar \
-../org.argeo.tp.crypto/org.apache.sshd.scp.2.9.jar \
-../org.argeo.tp.crypto/org.apache.sshd.sftp.2.9.jar \
-../org.argeo.tp.crypto/org.apache.tomcat.jni.9.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bcmail-fips.1.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bcmail-fips.1.0.src.jar \
+../crypto/fips/org.argeo.tp.crypto/bc-noncert.1.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bc-noncert.1.0.src.jar \
+../crypto/fips/org.argeo.tp.crypto/bcpg-fips.1.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bcpg-fips.1.0.src.jar \
+../crypto/fips/org.argeo.tp.crypto/bcpkix-fips.1.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bcpkix-fips.1.0.src.jar \
+../crypto/fips/org.argeo.tp.crypto/bctls-fips.1.0.jar \
+../crypto/fips/org.argeo.tp.crypto/bctls-fips.1.0.src.jar \
+../osgi/equinox/org.argeo.cms/org.argeo.cms.lib.equinox.2.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.apache.felix.gogo.command.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.apache.felix.gogo.runtime.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.apache.felix.gogo.shell.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.apache.felix.scr.2.2.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.eclipse.equinox.console.1.4.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.eclipse.osgi.3.18.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.eclipse.osgi.services.3.11.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.eclipse.osgi.util.3.7.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.cm.1.6.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.component.1.5.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.coordinator.1.0.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.device.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.event.1.4.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.log.stream.1.0.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.metatype.1.4.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.prefs.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.provisioning.1.2.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.upnp.1.2.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.useradmin.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.service.wireadmin.1.0.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.function.1.2.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.measurement.1.0.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.position.1.0.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.promise.1.3.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.pushstream.1.1.jar \
+../osgi/equinox/org.argeo.tp.osgi/org.osgi.util.xml.1.0.jar \
* '/'), taking into account reverse proxies.
*/
public static StringBuilder getRequestUrlBase(HttpServletRequest req) {
+ return getRequestUrlBase(req, false);
+ }
+
+ /**
+ * The base URL for this query (without any path component (not even an ending
+ * '/'), taking into account reverse proxies.
+ *
+ * @param forceReverseProxyHttps if a reverse proxy is detected and this is set
+ * to true, the https scheme will be used. This is
+ * to work around issued when the an https reverse
+ * proxy is talking to an http application.
+ */
+ public static StringBuilder getRequestUrlBase(HttpServletRequest req, boolean forceReverseProxyHttps) {
List<String> viaHosts = new ArrayList<>();
for (Enumeration<String> it = req.getHeaders(VIA.getHeaderName()); it.hasMoreElements();) {
String[] arr = it.nextElement().split(" ");
boolean isReverseProxy = outerHost != null && !outerHost.equals(requestUrl.getHost());
if (isReverseProxy) {
- String protocol = req.isSecure() ? "https" : "http";
+ String protocol;
+ if (forceReverseProxyHttps)
+ protocol = "https";
+ else
+ protocol = req.isSecure() ? "https" : "http";
return new StringBuilder(protocol + "://" + outerHost);
} else {
return new StringBuilder(requestUrl.getScheme() + "://" + requestUrl.getHost()
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.argeo.cms.jshell</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ds.core.builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" activate="start" deactivate="stop" name="org.argeo.cms.cmsJShell">
+ <implementation class="org.argeo.cms.jshell.CmsJShell"/>
+ <reference bind="setCmsState" cardinality="1..1" interface="org.argeo.api.cms.CmsState" name="CmsState" policy="static"/>
+</scr:component>
--- /dev/null
+Main-Class: org.argeo.cms.jshell.JShellClient
+
+Import-Package: \
+org.osgi.framework.namespace, \
+*
+
+Service-Component:\
+OSGI-INF/cmsJShell.xml
--- /dev/null
+bin.includes = META-INF/,\
+ .,\
+ OSGI-INF/cmsJShell.xml
+source.. = src/
+output.. = bin/
--- /dev/null
+org.argeo.internal.cms.jshell.osgi.OsgiExecutionControlProvider
\ No newline at end of file
--- /dev/null
+package org.argeo.cms.jshell;
+
+import jdk.jshell.execution.DirectExecutionControl;
+import jdk.jshell.execution.LoaderDelegate;
+import jdk.jshell.spi.ExecutionControl;
+import jdk.jshell.spi.ExecutionEnv;
+
+/** Custom {@link ExecutionControl}. */
+public class CmsExecutionControl extends DirectExecutionControl {
+ private final ExecutionEnv executionEnv;
+
+ public CmsExecutionControl(ExecutionEnv executionEnv, LoaderDelegate loaderDelegate) {
+ super(loaderDelegate);
+ this.executionEnv = executionEnv;
+
+ }
+
+ @Override
+ protected void clientCodeEnter() throws InternalException {
+ super.clientCodeEnter();
+ }
+
+ @Override
+ protected void clientCodeLeave() throws InternalException {
+ super.clientCodeLeave();
+ executionEnv.userOut().flush();
+ }
+
+}
--- /dev/null
+package org.argeo.cms.jshell;
+
+import java.io.IOException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardWatchEventKinds;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import org.argeo.api.cms.CmsLog;
+import org.argeo.api.cms.CmsState;
+import org.argeo.api.uuid.UuidFactory;
+import org.argeo.cms.util.OS;
+import org.argeo.internal.cms.jshell.osgi.OsgiExecutionControlProvider;
+import org.osgi.framework.Bundle;
+
+/** A factory for JShell sessions. */
+public class CmsJShell {
+ private final static CmsLog log = CmsLog.getLog(CmsJShell.class);
+ static ClassLoader loader = CmsJShell.class.getClassLoader();
+
+ public static UuidFactory uuidFactory = null;
+
+ private CmsState cmsState;
+
+ private Map<Path, LocalJShellSession> localSessions = new HashMap<>();
+ private Map<Path, Path> bundleDirs = new HashMap<>();
+
+ private Path stateRunDir;
+ private Path jshBase;
+ private Path jshLinkedDir;
+ private Path jtermBase;
+ private Path jtermLinkedDir;
+
+ public void start() throws Exception {
+ // TODO better define application id, make it configurable
+ String applicationID;
+ if (Files.exists(cmsState.getStatePath("dev.properties"))) { // in Eclipse
+ applicationID = cmsState.getStatePath("").getFileName().toString();
+ } else {
+ applicationID = cmsState.getStatePath("").getParent().getFileName().toString();
+ }
+
+ // TODO centralise state run dir
+ stateRunDir = OS.getRunDir().resolve(applicationID);
+
+ jshBase = stateRunDir.resolve(JShellClient.JSH);
+ Files.createDirectories(jshBase);
+ jshLinkedDir = Files.createSymbolicLink(cmsState.getStatePath(JShellClient.JSH), jshBase);
+
+ jtermBase = stateRunDir.resolve(JShellClient.JTERM);
+ Files.createDirectories(jtermBase);
+ jtermLinkedDir = Files.createSymbolicLink(cmsState.getStatePath(JShellClient.JTERM), jtermBase);
+
+ log.info("Local JShell on " + jshBase + ", linked to " + jshLinkedDir);
+ log.info("Local JTerm on " + jtermBase + ", linked to " + jtermLinkedDir);
+
+ new Thread(() -> {
+ try {
+ WatchService watchService = FileSystems.getDefault().newWatchService();
+
+ jshBase.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
+ StandardWatchEventKinds.ENTRY_DELETE);
+ try (DirectoryStream<Path> bundleSns = Files.newDirectoryStream(jshBase)) {
+ for (Path bundleSnDir : bundleSns) {
+ addBundleSnDir(bundleSnDir, watchService);
+ }
+ }
+ jtermBase.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
+ StandardWatchEventKinds.ENTRY_DELETE);
+ try (DirectoryStream<Path> bundleSns = Files.newDirectoryStream(jtermBase)) {
+ for (Path bundleSnDir : bundleSns) {
+ addBundleSnDir(bundleSnDir, watchService);
+ }
+ }
+
+ WatchKey key;
+ while ((key = watchService.take()) != null) {
+ events: for (WatchEvent<?> event : key.pollEvents()) {
+// System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
+ Path parent = (Path) key.watchable();
+ // sessions
+ if (Files.isSameFile(jshBase, parent)) {
+ Path bundleSnDir = jshBase.resolve((Path) event.context());
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ addBundleSnDir(bundleSnDir, watchService);
+ } else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
+ }
+ } else if (Files.isSameFile(jtermBase, parent)) {
+ Path bundleSnDir = jtermBase.resolve((Path) event.context());
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ addBundleSnDir(bundleSnDir, watchService);
+ } else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
+ }
+ } else {
+ Path path = parent.resolve((Path) event.context());
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ if (!Files.isDirectory(path)) {
+ log.warn("Ignoring " + path + " as it is not a directory");
+ continue events;
+ }
+ try {
+ UUID.fromString(path.getFileName().toString());
+ } catch (IllegalArgumentException e) {
+ log.warn("Ignoring " + path + " as it is not named as UUID");
+ continue events;
+ }
+
+ boolean interactive;
+ if (Files.isSameFile(jshBase, parent.getParent())) {
+ interactive = false;
+ } else if (Files.isSameFile(jtermBase, parent.getParent())) {
+ interactive = true;
+ } else {
+ log.warn("Ignoring " + path + " as we don't know whether it is interactive or not");
+ continue events;
+ }
+ Path bundleIdDir = bundleDirs.get(parent);
+ LocalJShellSession localSession = new LocalJShellSession(path, bundleIdDir,
+ interactive);
+ localSessions.put(path, localSession);
+ } else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
+ localSessions.remove(path);
+ }
+ }
+ }
+ key.reset();
+ }
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ }
+ }, "JShell local sessions watcher").start();
+ }
+
+ private void addBundleSnDir(Path bundleSnDir, WatchService watchService) throws IOException {
+ String symbolicName = bundleSnDir.getFileName().toString();
+ Bundle fromBundle = OsgiExecutionControlProvider.getBundleFromSn(symbolicName);
+ if (fromBundle == null) {
+ log.error("Ignoring bundle " + symbolicName + " because it was not found");
+ return;
+ }
+ Long bundleId = fromBundle.getBundleId();
+ Path bundleIdDir = stateRunDir.resolve(bundleId.toString());
+ Files.createDirectories(bundleIdDir);
+ bundleDirs.put(bundleSnDir, bundleIdDir);
+
+ bundleSnDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
+ }
+
+ public void stop() {
+ try {
+ Files.delete(jshLinkedDir);
+ } catch (IOException e) {
+ log.error("Cannot remove " + jshLinkedDir);
+ }
+ try {
+ Files.delete(jtermLinkedDir);
+ } catch (IOException e) {
+ log.error("Cannot remove " + jtermLinkedDir);
+ }
+ }
+
+ public void setCmsState(CmsState cmsState) {
+ this.cmsState = cmsState;
+ }
+}
--- /dev/null
+package org.argeo.cms.jshell;
+
+import static java.lang.System.Logger.Level.ERROR;
+import static java.lang.System.Logger.Level.TRACE;
+import static java.net.StandardProtocolFamily.UNIX;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.lang.System.Logger;
+import java.lang.management.ManagementFactory;
+import java.net.StandardSocketOptions;
+import java.net.UnixDomainSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.AsynchronousCloseException;
+import java.nio.channels.Channels;
+import java.nio.channels.ClosedByInterruptException;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/** A JShell client to a local CMS node. */
+public class JShellClient {
+ private final static Logger logger = System.getLogger(JShellClient.class.getName());
+
+ public final static String STD = "std";
+ public final static String CTL = "ctl";
+
+ public final static String JSH = "jsh";
+ public final static String JTERM = "jterm";
+
+ private static String sttyExec = "/usr/bin/stty";
+
+ /** Benchmark based on uptime. */
+ private static boolean benchmark = false;
+
+ /**
+ * The real path (following symbolic links) to the directory were to create
+ * sessions.
+ */
+ private Path localBase;
+
+ /** The symbolic name of the bundle from which to run. */
+ private String symbolicName;
+
+ /** The script to run. */
+ private Path script;
+ /** Additional arguments of the script */
+ private List<String> scriptArgs;
+
+ private String ttyConfig;
+ private boolean terminal;
+
+ /** Workaround to be able to test in Eclipse console */
+ private boolean inEclipse = false;
+
+ public JShellClient(Path targetStateDirectory, String symbolicName, Path script, List<String> scriptArgs) {
+ try {
+ this.terminal = System.console() != null && script == null;
+ if (inEclipse && script == null)
+ terminal = true;
+ if (terminal) {
+ localBase = targetStateDirectory.resolve(JTERM);
+ } else {
+ localBase = targetStateDirectory.resolve(JSH);
+ }
+ if (Files.isSymbolicLink(localBase)) {
+ localBase = localBase.toRealPath();
+ }
+ this.symbolicName = symbolicName;
+ this.script = script;
+ this.scriptArgs = scriptArgs == null ? new ArrayList<>() : scriptArgs;
+ } catch (IOException e) {
+ throw new IllegalStateException("Cannot initialise client", e);
+ }
+ }
+
+ public void run() {
+ try {
+ if (terminal)
+ toRawTerminal();
+ SocketPipeSource std = new SocketPipeSource(STD, script != null);
+ std.setInputStream(System.in);
+ std.setOutputStream(System.out);
+
+ SocketPipeSource ctl = new SocketPipeSource(CTL, false);
+ ctl.setOutputStream(System.err);
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+// System.out.println("\nShutting down...");
+ toOriginalTerminal();
+ std.shutdown();
+ ctl.shutdown();
+ }, "Shut down JShell client"));
+
+ Path bundleSnDir = localBase.resolve(symbolicName);
+ if (!Files.exists(bundleSnDir))
+ Files.createDirectory(bundleSnDir);
+ UUID uuid = UUID.randomUUID();
+ Path sessionDir = bundleSnDir.resolve(uuid.toString());
+
+ // creating the directory will trigger opening of the session on server side
+ Files.createDirectory(sessionDir);
+
+ Path stdPath = sessionDir.resolve(JShellClient.STD);
+ Path ctlPath = sessionDir.resolve(JShellClient.CTL);
+
+ while (!(Files.exists(stdPath) && Files.exists(ctlPath))) {
+ // TODO timeout
+ try {
+ Thread.sleep(1);
+ } catch (InterruptedException e) {
+ // silent
+ }
+ }
+
+ UnixDomainSocketAddress stdSocketAddress = UnixDomainSocketAddress.of(stdPath.toRealPath());
+ UnixDomainSocketAddress ctlSocketAddress = UnixDomainSocketAddress.of(ctlPath.toRealPath());
+
+ try (SocketChannel stdChannel = SocketChannel.open(UNIX);
+ SocketChannel ctlChannel = SocketChannel.open(UNIX);) {
+ ctlChannel.connect(ctlSocketAddress);
+ ctl.process(ctlChannel);
+ if (script != null) {
+ new ScriptThread(ctlChannel).start();
+ }
+ stdChannel.connect(stdSocketAddress);
+ std.process(stdChannel);
+
+ while (!std.isCompleted() && !ctl.isCompleted()) {
+ // isCompleted() will block
+ }
+ }
+ if (benchmark)
+ System.err.println(ManagementFactory.getRuntimeMXBean().getUptime());
+ std.shutdown();
+ ctl.shutdown();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ toOriginalTerminal();
+ }
+
+ }
+
+ public static void main(String[] args) throws IOException, InterruptedException {
+ if (benchmark)
+ System.err.println(ManagementFactory.getRuntimeMXBean().getUptime());
+ List<String> plainArgs = new ArrayList<>();
+ Map<String, List<String>> options = new HashMap<>();
+ String currentOption = null;
+ for (int i = 0; i < args.length; i++) {
+ if (args[i].startsWith("-")) {
+ currentOption = args[i];
+ if (!options.containsKey(currentOption))
+ options.put(currentOption, new ArrayList<>());
+ i++;
+ options.get(currentOption).add(args[i]);
+ } else {
+ plainArgs.add(args[i]);
+ }
+ }
+
+ Path targetStateDirectory = Paths.get(options.get("-d").get(0));
+ String symbolicName = options.get("-b").get(0);
+
+ Path script = plainArgs.isEmpty() ? null : Paths.get(plainArgs.get(0));
+ List<String> scriptArgs = new ArrayList<>();
+ for (int i = 1; i < plainArgs.size(); i++)
+ scriptArgs.add(plainArgs.get(i));
+
+ JShellClient client = new JShellClient(targetStateDirectory, symbolicName, script, scriptArgs);
+ client.run();
+ }
+
+ /*
+ * TERMINAL
+ */
+ /** Set the terminal to raw mode. */
+ protected synchronized void toRawTerminal() {
+ boolean isWindows = File.separatorChar == '\\';
+ if (isWindows)
+ return;
+ if (inEclipse)
+ return;
+ // save current configuration
+ ttyConfig = stty("-g");
+ if (ttyConfig == null)
+ return;
+ ttyConfig.trim();
+ // set the console to be character-buffered instead of line-buffered
+ stty("-icanon min 1");
+ // disable character echoing
+ stty("-echo");
+ }
+
+ /** Restore original terminal configuration. */
+ protected synchronized void toOriginalTerminal() {
+ if (ttyConfig == null)
+ return;
+ try {
+ stty(ttyConfig);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ ttyConfig = null;
+ }
+
+ /**
+ * Execute the stty command with the specified arguments against the current
+ * active terminal.
+ */
+ protected String stty(String args) {
+ List<String> cmd = new ArrayList<>();
+ cmd.add("/bin/sh");
+ cmd.add("-c");
+ cmd.add(sttyExec + " " + args + " < /dev/tty");
+
+ logger.log(TRACE, () -> cmd.toString());
+
+ try {
+ ProcessBuilder pb = new ProcessBuilder(cmd);
+ Process p = pb.start();
+ String firstLine = new BufferedReader(new InputStreamReader(p.getInputStream())).readLine();
+ p.waitFor();
+ logger.log(TRACE, () -> firstLine);
+ return firstLine;
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /*
+ * SCRIPT
+ */
+ private class ScriptThread extends Thread {
+ private SocketChannel channel;
+
+ public ScriptThread(SocketChannel channel) {
+ super("JShell script writer");
+ this.channel = channel;
+ }
+
+ @Override
+ public void run() {
+ try {
+ if (benchmark)
+ System.err.println(ManagementFactory.getRuntimeMXBean().getUptime());
+ StringBuilder sb = new StringBuilder();
+ if (!scriptArgs.isEmpty()) {
+ // additional arguments as $1, $2, etc.
+ for (String arg : scriptArgs)
+ sb.append('\"').append(arg).append('\"').append(";\n");
+ }
+ if (sb.length() > 0)
+ writeLine(sb);
+
+ try (BufferedReader reader = Files.newBufferedReader(script)) {
+ String line;
+ lines: while ((line = reader.readLine()) != null) {
+ if (line.startsWith("#"))
+ continue lines;
+ writeLine(line);
+ }
+ }
+
+ // exit
+ if (channel.isConnected())
+ writeLine("/exit");
+ } catch (IOException e) {
+ logger.log(ERROR, "Cannot execute " + script, e);
+ }
+ }
+
+ /** Not optimal, but performance is not critical here. */
+ private void writeLine(Object obj) throws IOException {
+ channel.write(ByteBuffer.wrap((obj + "\n").getBytes(UTF_8)));
+ }
+ }
+}
+
+/** Pipe streams to a channel. */
+class SocketPipeSource {
+ private ReadableByteChannel inChannel;
+ private WritableByteChannel outChannel;
+
+ private Thread readThread;
+ private Thread forwardThread;
+
+ private int inBufferSize = 1;
+ private int outBufferSize = 1024;
+
+ private final String id;
+ private final boolean batch;
+
+ private boolean completed = false;
+
+ public SocketPipeSource(String id, boolean batch) {
+ this.id = id;
+ this.batch = batch;
+ }
+
+ public void process(SocketChannel channel) throws IOException {
+ if (batch) {
+ Integer socketRcvBuf = channel.getOption(StandardSocketOptions.SO_RCVBUF);
+ inBufferSize = socketRcvBuf;
+ outBufferSize = socketRcvBuf;
+ }
+
+ readThread = new Thread(() -> {
+
+ try {
+ ByteBuffer buffer = ByteBuffer.allocate(outBufferSize);
+ while (true) {
+ if (channel.read(buffer) < 0)
+ break;
+ buffer.flip();
+ outChannel.write(buffer);
+ buffer.rewind();
+ }
+ } catch (ClosedByInterruptException e) {
+ // silent
+ } catch (AsynchronousCloseException e) {
+ // silent
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ markCompleted();
+ }, "JShell read " + id);
+ readThread.start();
+
+ // TODO make it smarter than a 1 byte buffer
+ // we should recognize control characters
+ // e.g ^C
+// int c = System.in.read();
+// if (c == 0x1B) {
+// break;
+// }
+
+ if (inChannel != null) {
+ forwardThread = new Thread(() -> {
+ try {
+ ByteBuffer buffer = ByteBuffer.allocate(inBufferSize);
+ while (channel.isConnected()) {
+ if (inChannel.read(buffer) < 0) {
+ System.err.println("in EOF");
+ channel.shutdownOutput();
+ break;
+ }
+// int b = (int) buffer.get(0);
+// if (b == 0x1B) {
+// System.out.println("Ctrl+C");
+// }
+
+ buffer.flip();
+ channel.write(buffer);
+ buffer.rewind();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }, "JShell write " + id);
+ forwardThread.setDaemon(true);
+ forwardThread.start();
+ // end
+ // TODO make it more robust
+ // we want to be asynchronous when read only
+// try {
+// // TODO add timeout
+// readThread.join();
+// } catch (InterruptedException e) {
+// e.printStackTrace();
+// }
+
+ }
+ }
+
+ public synchronized boolean isCompleted() {
+ if (!completed)
+ try {
+ wait();
+ } catch (InterruptedException e) {
+ // silent
+ }
+ return completed;
+ }
+
+ protected synchronized void markCompleted() {
+ completed = true;
+ notifyAll();
+ }
+
+ public void shutdown() {
+ if (inChannel != null)
+ try {
+ inChannel.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ try {
+ outChannel.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+// if (inChannel != null)
+// forwardThread.interrupt();
+// readThread.interrupt();
+ }
+
+ public void setInputStream(InputStream in) {
+ inChannel = Channels.newChannel(in);
+ }
+
+ public void setOutputStream(OutputStream out) {
+ outChannel = Channels.newChannel(out);
+ }
+}
--- /dev/null
+package org.argeo.cms.jshell;
+
+import static java.net.StandardProtocolFamily.UNIX;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.net.UnixDomainSocketAddress;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.argeo.api.cms.CmsAuth;
+import org.argeo.api.cms.CmsLog;
+import org.argeo.cms.util.CurrentSubject;
+import org.argeo.cms.util.FsUtils;
+import org.argeo.internal.cms.jshell.osgi.OsgiExecutionControlProvider;
+
+import jdk.jshell.tool.JavaShellToolBuilder;
+
+/** A JShell session based on local UNIX sockets. */
+class LocalJShellSession implements Runnable {
+ private final static CmsLog log = CmsLog.getLog(LocalJShellSession.class);
+
+ private UUID uuid;
+ private Path sessionDir;
+ private Path socketsDir;
+
+ private Path stdPath;
+ private Path ctlPath;
+
+ private Thread replThread;
+
+ private LoginContext loginContext;
+
+ private Long bundleId;
+
+ private final boolean interactive;
+
+ LocalJShellSession(Path sessionDir, Path bundleIdDir, boolean interactive) {
+ this.interactive = interactive;
+ try {
+ this.sessionDir = sessionDir;
+ this.uuid = UUID.fromString(sessionDir.getFileName().toString());
+ bundleId = Long.parseLong(bundleIdDir.getFileName().toString());
+ socketsDir = bundleIdDir.resolve(uuid.toString());
+ Files.createDirectories(socketsDir);
+
+ stdPath = socketsDir.resolve(JShellClient.STD);
+ Files.createSymbolicLink(sessionDir.resolve(JShellClient.STD), stdPath);
+
+ ctlPath = socketsDir.resolve(JShellClient.CTL);
+ Files.createSymbolicLink(sessionDir.resolve(JShellClient.CTL), ctlPath);
+
+ // TODO proper login
+ try {
+ loginContext = new LoginContext(CmsAuth.DATA_ADMIN.getLoginContextName());
+ loginContext.login();
+ } catch (LoginException e1) {
+ throw new RuntimeException("Could not login as data admin", e1);
+ } finally {
+ }
+
+ } catch (IOException e) {
+ log.error("Cannot initiate local session " + uuid, e);
+ cleanUp();
+ return;
+ }
+ replThread = new Thread(() -> CurrentSubject.callAs(loginContext.getSubject(), Executors.callable(this)),
+ "JShell " + sessionDir);
+ replThread.start();
+ }
+
+ public void run() {
+
+ log.debug(() -> "Started JShell session " + sessionDir);
+ try (SocketPipeMirror std = new SocketPipeMirror(JShellClient.STD + " " + uuid); //
+ SocketPipeMirror ctl = new SocketPipeMirror(JShellClient.CTL + " " + uuid);) {
+ // prepare jshell tool builder
+ String feedbackMode;
+ JavaShellToolBuilder builder = JavaShellToolBuilder.builder();
+ if (interactive) {
+ builder.in(std.getInputStream(), null);
+ builder.out(new PrintStream(std.getOutputStream()));
+ builder.err(new PrintStream(ctl.getOutputStream()));
+ builder.interactiveTerminal(true);
+ feedbackMode = "concise";
+ } else {
+ builder.in(ctl.getInputStream(), std.getInputStream());
+ PrintStream cmdOut = new PrintStream(ctl.getOutputStream());
+ PrintStream discard = new PrintStream(OutputStream.nullOutputStream());
+ builder.out(cmdOut, discard, new PrintStream(std.getOutputStream()));
+ builder.err(cmdOut);
+ builder.promptCapture(true);
+ feedbackMode = "silent";
+ }
+
+ UnixDomainSocketAddress stdSocketAddress = UnixDomainSocketAddress.of(stdPath);
+ UnixDomainSocketAddress ctlSocketAddress = UnixDomainSocketAddress.of(ctlPath);
+
+ try (ServerSocketChannel stdServerChannel = ServerSocketChannel.open(UNIX);
+ ServerSocketChannel ctlServerChannel = ServerSocketChannel.open(UNIX);) {
+ stdServerChannel.bind(stdSocketAddress);
+ ctlServerChannel.bind(ctlSocketAddress);
+ try (SocketChannel stdChannel = stdServerChannel.accept();
+ SocketChannel ctlChannel = ctlServerChannel.accept();) {
+ std.open(stdChannel);
+ ctl.open(ctlChannel);
+
+ ClassLoader cmsJShellBundleCL = OsgiExecutionControlProvider.class.getClassLoader();
+ ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
+ try {
+ String classpath = OsgiExecutionControlProvider.getBundleClasspath(bundleId);
+ Path bundleStartupScript = OsgiExecutionControlProvider.getBundleStartupScript(bundleId);
+ // we need our own class loader so that Java service loader
+ // finds our ExecutionControlProvider implementation
+ Thread.currentThread().setContextClassLoader(cmsJShellBundleCL);
+ //
+ // START JSHELL
+ //
+ int exitCode = builder.start("--execution", "osgi:bundle(" + bundleId + ")", "--class-path",
+ classpath, "--startup", bundleStartupScript.toString(), "--feedback", feedbackMode);
+ //
+ log.debug("JShell " + sessionDir + " completed with exit code " + exitCode);
+ } finally {
+ Thread.currentThread().setContextClassLoader(currentContextClassLoader);
+ }
+ } finally {
+ }
+ }
+ } catch (Exception e) {
+ throw new RuntimeException("JShell " + sessionDir + " failed", e);
+ } finally {
+ cleanUp();
+ }
+ }
+
+ private void cleanUp() {
+ try {
+ if (Files.exists(socketsDir))
+ FsUtils.delete(socketsDir);
+ if (Files.exists(sessionDir))
+ FsUtils.delete(sessionDir);
+ } catch (IOException e) {
+ log.error("Cannot clean up JShell " + sessionDir, e);
+ }
+
+ if (loginContext != null)
+ try {
+ loginContext.logout();
+ } catch (LoginException e) {
+ log.error("Cannot log out JShell " + sessionDir, e);
+ }
+ }
+}
--- /dev/null
+package org.argeo.cms.jshell;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.AsynchronousCloseException;
+import java.nio.channels.Channels;
+import java.nio.channels.Pipe;
+import java.nio.channels.SocketChannel;
+
+class SocketPipeMirror implements Closeable {
+ private final Pipe inPipe;
+ private final Pipe outPipe;
+
+ private final InputStream in;
+ private final OutputStream out;
+
+ private Thread readInThread;
+ private Thread writeOutThread;
+
+ private final String id;
+
+ public SocketPipeMirror(String id) throws IOException {
+ this.id = id;
+ inPipe = Pipe.open();
+ outPipe = Pipe.open();
+ in = Channels.newInputStream(inPipe.source());
+ out = Channels.newOutputStream(outPipe.sink());
+ }
+
+ public void open(SocketChannel channel) {
+ readInThread = new Thread(() -> {
+
+ try {
+ ByteBuffer buffer = ByteBuffer.allocate(1024);
+ while (!readInThread.isInterrupted() && channel.isConnected()) {
+ if (channel.read(buffer) < 0) {
+ in.close();
+ break;
+ }
+ buffer.flip();
+ inPipe.sink().write(buffer);
+ buffer.rewind();
+ }
+ } catch (AsynchronousCloseException e) {
+ // ignore
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }, "JShell read " + id);
+ readInThread.start();
+
+ writeOutThread = new Thread(() -> {
+
+ try {
+ ByteBuffer buffer = ByteBuffer.allocate(1024);
+ while (!writeOutThread.isInterrupted() && channel.isConnected()) {
+ if (outPipe.source().read(buffer) < 0) {
+ out.close();
+ break;
+ }
+ buffer.flip();
+ channel.write(buffer);
+ buffer.rewind();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }, "JShell write " + id);
+ writeOutThread.start();
+
+ }
+
+ @Override
+ public void close() throws IOException {
+ // TODO make it more robust
+// readInThread.interrupt();
+// writeOutThread.interrupt();
+ in.close();
+ out.close();
+ try {
+ readInThread.join();
+ } catch (InterruptedException e) {
+ // silent
+ }
+ try {
+ writeOutThread.join();
+ } catch (InterruptedException e) {
+ // silent
+ }
+ }
+
+ public InputStream getInputStream() {
+ return in;
+ }
+
+ public OutputStream getOutputStream() {
+ return out;
+ }
+}
--- /dev/null
+package org.argeo.internal.cms.jshell.osgi;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Writer;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.Objects;
+import java.util.Set;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.argeo.api.cms.CmsLog;
+import org.argeo.cms.jshell.CmsExecutionControl;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.Version;
+import org.osgi.framework.namespace.PackageNamespace;
+import org.osgi.framework.wiring.BundleRevision;
+import org.osgi.framework.wiring.BundleWire;
+import org.osgi.framework.wiring.BundleWiring;
+
+import jdk.jshell.spi.ExecutionControl;
+import jdk.jshell.spi.ExecutionControlProvider;
+import jdk.jshell.spi.ExecutionEnv;
+
+public class OsgiExecutionControlProvider implements ExecutionControlProvider {
+ private final static CmsLog log = CmsLog.getLog(OsgiExecutionControlProvider.class);
+
+ public final static String PROVIDER_NAME = "osgi";
+ public final static String BUNDLE_PARAMETER = "bundle";
+
+ @Override
+ public String name() {
+ return PROVIDER_NAME;
+ }
+
+ @Override
+ public Map<String, String> defaultParameters() {
+ Map<String, String> defaultParameters = new HashMap<>();
+ defaultParameters.put(BUNDLE_PARAMETER, null);
+ return defaultParameters;
+ }
+
+ @Override
+ public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters) throws Throwable {
+ Long bundleId = Long.parseLong(parameters.get(BUNDLE_PARAMETER));
+ Bundle fromBundle = getBundleFromId(bundleId);
+
+ BundleWiring fromBundleWiring = fromBundle.adapt(BundleWiring.class);
+ ClassLoader fromBundleClassLoader = fromBundleWiring.getClassLoader();
+
+ ExecutionControl executionControl = new CmsExecutionControl(env,
+ new WrappingLoaderDelegate(env, fromBundleClassLoader));
+ log.trace(() -> "JShell from " + fromBundle.getSymbolicName() + "_" + fromBundle.getVersion() + " ["
+ + fromBundle.getBundleId() + "]");
+ return executionControl;
+ }
+
+ public static Bundle getBundleFromSn(String symbolicName) {
+ BundleContext bc = FrameworkUtil.getBundle(OsgiExecutionControlProvider.class).getBundleContext();
+ Objects.requireNonNull(symbolicName);
+ NavigableMap<Version, Bundle> bundles = new TreeMap<Version, Bundle>();
+ for (Bundle b : bc.getBundles()) {
+ if (symbolicName.equals(b.getSymbolicName()))
+ bundles.put(b.getVersion(), b);
+ }
+ if (bundles.isEmpty())
+ return null;
+ Bundle fromBundle = bundles.lastEntry().getValue();
+ return fromBundle;
+ }
+
+ public static Bundle getBundleFromId(Long bundleId) {
+ BundleContext bc = FrameworkUtil.getBundle(OsgiExecutionControlProvider.class).getBundleContext();
+ Bundle fromBundle = bc.getBundle(bundleId);
+ return fromBundle;
+ }
+
+ public static Path getBundleStartupScript(Long bundleId) {
+ BundleContext bc = FrameworkUtil.getBundle(OsgiExecutionControlProvider.class).getBundleContext();
+ Bundle fromBundle = bc.getBundle(bundleId);
+ Path bundleStartupScript = fromBundle.getDataFile("BUNDLE.jsh").toPath();
+
+ BundleWiring fromBundleWiring = fromBundle.adapt(BundleWiring.class);
+ ClassLoader fromBundleClassLoader = fromBundleWiring.getClassLoader();
+
+ Set<String> packagesToImport = new TreeSet<>();
+
+ // from bundle packages
+ for (Package pkg : fromBundleClassLoader.getDefinedPackages()) {
+ packagesToImport.add(pkg.getName());
+ }
+
+ List<BundleWire> bundleWires = fromBundleWiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
+ for (BundleWire bw : bundleWires) {
+ packagesToImport.add(bw.getCapability().getAttributes().get(PackageNamespace.PACKAGE_NAMESPACE).toString());
+ }
+
+ try (Writer writer = Files.newBufferedWriter(bundleStartupScript, StandardCharsets.UTF_8)) {
+ for (String p : packagesToImport) {
+ writer.write("import " + p + ".*;\n");
+ }
+
+ String std = """
+ /open DEFAULT
+ import jdk.jshell.spi.ExecutionEnv;
+ import java.util.function.*;
+
+ /** Redirected standard IO. */
+ public class Std {
+ final static InputStream in = new Supplier<InputStream>() {
+
+ @Override
+ public InputStream get() {
+ return ((ExecutionEnv) getClass().getClassLoader()).userIn();
+ }
+
+ }.get();
+ final static PrintStream out = new Supplier<PrintStream>() {
+
+ @Override
+ public PrintStream get() {
+ return ((ExecutionEnv) getClass().getClassLoader()).userOut();
+ }
+
+ }.get();
+ final static PrintStream err = new Supplier<PrintStream>() {
+
+ @Override
+ public PrintStream get() {
+ return ((ExecutionEnv) getClass().getClassLoader()).userErr();
+ }
+
+ }.get();
+
+ }
+ """;
+ writer.write(std);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot writer bundle startup script to " + bundleStartupScript, e);
+ }
+
+ return bundleStartupScript;
+ }
+
+ public static String getBundleClasspath(Long bundleId) throws IOException {
+ String framework = System.getProperty("osgi.framework");
+ Path frameworkLocation = Paths.get(URI.create(framework)).toAbsolutePath();
+ BundleContext bc = FrameworkUtil.getBundle(OsgiExecutionControlProvider.class).getBundleContext();
+ Bundle fromBundle = bc.getBundle(bundleId);
+
+ BundleWiring fromBundleWiring = fromBundle.adapt(BundleWiring.class);
+
+ Set<Bundle> bundlesToAddToCompileClasspath = new TreeSet<>();
+
+ // from bundle
+ bundlesToAddToCompileClasspath.add(fromBundle);
+
+ List<BundleWire> bundleWires = fromBundleWiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE);
+ for (BundleWire bw : bundleWires) {
+ bundlesToAddToCompileClasspath.add(bw.getProviderWiring().getBundle());
+ }
+
+ StringJoiner classpath = new StringJoiner(File.pathSeparator);
+ bundles: for (Bundle b : bundlesToAddToCompileClasspath) {
+ if (b.getBundleId() == 0) {// system bundle
+ classpath.add(frameworkLocation.toString());
+ continue bundles;
+ }
+ Path p = bundleToPath(frameworkLocation, b);
+ classpath.add(p.toString());
+ }
+
+ return classpath.toString();
+ }
+
+ static Path bundleToPath(Path frameworkLocation, Bundle bundle) throws IOException {
+ String location = bundle.getLocation();
+ if (location.startsWith("initial@reference:file:")) {
+ location = location.substring("initial@reference:file:".length());
+ Path p = frameworkLocation.getParent().resolve(location).toRealPath();
+ // TODO load dev.properties from OSGi configuration directory
+ if (Files.isDirectory(p))
+ p = p.resolve("bin");
+ return p;
+ }
+ Path p = Paths.get(location);
+ return p;
+ }
+}
--- /dev/null
+package org.argeo.internal.cms.jshell.osgi;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.security.CodeSource;
+import java.security.SecureClassLoader;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import jdk.jshell.execution.LoaderDelegate;
+import jdk.jshell.spi.ExecutionControl.ClassBytecodes;
+import jdk.jshell.spi.ExecutionControl.ClassInstallException;
+import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
+import jdk.jshell.spi.ExecutionEnv;
+
+/** A {@link LoaderDelegate} using a parent {@link ClassLoader}. */
+class WrappingLoaderDelegate implements LoaderDelegate {
+ private final WrappingClassloader loader;
+ private final Map<String, Class<?>> klasses = new HashMap<>();
+
+ private final ExecutionEnv env;
+
+ public WrappingLoaderDelegate(ExecutionEnv env, ClassLoader parentClassLoader) {
+ this.env = env;
+ this.loader = new WrappingClassloader(parentClassLoader);
+
+ Thread.currentThread().setContextClassLoader(loader);
+ }
+
+ @Override
+ public void load(ClassBytecodes[] cbcs) throws ClassInstallException, EngineTerminationException {
+ boolean[] loaded = new boolean[cbcs.length];
+ try {
+ for (ClassBytecodes cbc : cbcs) {
+ loader.declare(cbc.name(), cbc.bytecodes());
+ }
+ for (int i = 0; i < cbcs.length; ++i) {
+ ClassBytecodes cbc = cbcs[i];
+ Class<?> klass = loader.loadClass(cbc.name());
+ klasses.put(cbc.name(), klass);
+ loaded[i] = true;
+ // Get class loaded to the point of, at least, preparation
+ klass.getDeclaredMethods();
+ }
+ } catch (Throwable ex) {
+ throw new ClassInstallException("load: " + ex.getMessage(), loaded);
+ }
+ }
+
+ @Override
+ public void classesRedefined(ClassBytecodes[] cbcs) {
+ for (ClassBytecodes cbc : cbcs) {
+ loader.declare(cbc.name(), cbc.bytecodes());
+ }
+ }
+
+ @Override
+ public void addToClasspath(String cp) {
+ // ignore
+ }
+
+ @Override
+ public Class<?> findClass(String name) throws ClassNotFoundException {
+ Class<?> klass = klasses.get(name);
+ if (klass == null) {
+ throw new ClassNotFoundException(name + " not found");
+ } else {
+ return klass;
+ }
+ }
+
+ private class WrappingClassloader extends SecureClassLoader implements ExecutionEnv {
+
+ private final Map<String, ClassFile> classFiles = new HashMap<>();
+
+ public WrappingClassloader(ClassLoader parent) {
+ super(parent);
+ }
+
+ private class ResourceURLStreamHandler extends URLStreamHandler {
+
+ private final String name;
+
+ ResourceURLStreamHandler(String name) {
+ this.name = name;
+ }
+
+ @Override
+ protected URLConnection openConnection(URL u) throws IOException {
+ return new URLConnection(u) {
+ private InputStream in;
+ private Map<String, List<String>> fields;
+ private List<String> fieldNames;
+
+ @Override
+ public void connect() {
+ if (connected) {
+ return;
+ }
+ connected = true;
+ ClassFile file = classFiles.get(name);
+ in = new ByteArrayInputStream(file.data);
+ fields = new LinkedHashMap<>();
+ fields.put("content-length", List.of(Integer.toString(file.data.length)));
+ Instant instant = new Date(file.timestamp).toInstant();
+ ZonedDateTime time = ZonedDateTime.ofInstant(instant, ZoneId.of("GMT"));
+ String timeStamp = DateTimeFormatter.RFC_1123_DATE_TIME.format(time);
+ fields.put("date", List.of(timeStamp));
+ fields.put("last-modified", List.of(timeStamp));
+ fieldNames = new ArrayList<>(fields.keySet());
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ connect();
+ return in;
+ }
+
+ @Override
+ public String getHeaderField(String name) {
+ connect();
+ return fields.getOrDefault(name, List.of()).stream().findFirst().orElse(null);
+ }
+
+ @Override
+ public Map<String, List<String>> getHeaderFields() {
+ connect();
+ return fields;
+ }
+
+ @Override
+ public String getHeaderFieldKey(int n) {
+ return n < fieldNames.size() ? fieldNames.get(n) : null;
+ }
+
+ @Override
+ public String getHeaderField(int n) {
+ String name = getHeaderFieldKey(n);
+
+ return name != null ? getHeaderField(name) : null;
+ }
+
+ };
+ }
+ }
+
+ void declare(String name, byte[] bytes) {
+ classFiles.put(toResourceString(name), new ClassFile(bytes, System.currentTimeMillis()));
+ }
+
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
+ ClassFile file = classFiles.get(toResourceString(name));
+ if (file == null) {
+ return super.findClass(name);
+ }
+ return super.defineClass(name, file.data, 0, file.data.length, (CodeSource) null);
+ }
+
+ @Override
+ public URL findResource(String name) {
+ URL u = doFindResource(name);
+ return u != null ? u : super.findResource(name);
+ }
+
+ @Override
+ public Enumeration<URL> findResources(String name) throws IOException {
+ URL u = doFindResource(name);
+ Enumeration<URL> sup = super.findResources(name);
+
+ if (u == null) {
+ return sup;
+ }
+
+ List<URL> result = new ArrayList<>();
+
+ while (sup.hasMoreElements()) {
+ result.add(sup.nextElement());
+ }
+
+ result.add(u);
+
+ return Collections.enumeration(result);
+ }
+
+ private URL doFindResource(String name) {
+ if (classFiles.containsKey(name)) {
+ try {
+ return new URL(null, new URI("jshell", null, "/" + name, null).toString(),
+ new ResourceURLStreamHandler(name));
+ } catch (MalformedURLException | URISyntaxException ex) {
+ throw new InternalError(ex);
+ }
+ }
+
+ return null;
+ }
+
+ private String toResourceString(String className) {
+ return className.replace('.', '/') + ".class";
+ }
+
+ private static class ClassFile {
+ public final byte[] data;
+ public final long timestamp;
+
+ ClassFile(byte[] data, long timestamp) {
+ this.data = data;
+ this.timestamp = timestamp;
+ }
+
+ }
+
+ @Override
+ public InputStream userIn() {
+ return env.userIn();
+ }
+
+ @Override
+ public PrintStream userOut() {
+ return env.userOut();
+ }
+
+ @Override
+ public PrintStream userErr() {
+ return env.userErr();
+ }
+
+ @Override
+ public List<String> extraRemoteVMOptions() {
+ return env.extraRemoteVMOptions();
+ }
+
+ @Override
+ public void closeDown() {
+ // env.closeDown();
+ }
+
+ }
+
+}
.
additional.bundles = org.eclipse.jetty.io,\
org.eclipse.jetty.security,\
- org.argeo.ext.slf4j,\
- org.slf4j.api
+ org.argeo.tp.syslogger
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
public class JettyHttpServer extends HttpsServer {
private final static CmsLog log = CmsLog.getLog(JettyHttpServer.class);
- private static final int DEFAULT_IDLE_TIMEOUT = 30000;
+ /** Long timeout since our users may have poor connections. */
+ private static final int DEFAULT_IDLE_TIMEOUT = 120 * 1000;
private Server server;
@Override
public void start() {
+ String httpPortStr = getDeployProperty(CmsDeployProperty.HTTP_PORT);
+ String httpsPortStr = getDeployProperty(CmsDeployProperty.HTTPS_PORT);
+ if (httpPortStr != null && httpsPortStr != null)
+ throw new IllegalArgumentException("Either an HTTP or an HTTPS port should be configured, not both");
+ if (httpPortStr == null && httpsPortStr == null) {
+ log.warn("Neither an HTTP or an HTTPS port was configured, not starting Jetty");
+ }
+
+ /// TODO make it more generic
+ String httpHost = getDeployProperty(CmsDeployProperty.HOST);
+
try {
ThreadPool threadPool = null;
server = new Server(threadPool);
- configureConnectors();
+ configureConnectors(httpPortStr, httpsPortStr, httpHost);
if (httpConnector != null) {
httpConnector.open();
//
// Addresses
- String httpHost = getDeployProperty(CmsDeployProperty.HOST);
String fallBackHostname = cmsState != null ? cmsState.getHostname() : "::1";
if (httpConnector != null) {
httpAddress = new InetSocketAddress(httpHost != null ? httpHost : fallBackHostname,
}
}
- protected void configureConnectors() {
- String httpPortStr = getDeployProperty(CmsDeployProperty.HTTP_PORT);
- String httpsPortStr = getDeployProperty(CmsDeployProperty.HTTPS_PORT);
- if (httpPortStr != null && httpsPortStr != null)
- throw new IllegalArgumentException("Either an HTTP or an HTTPS port should be configured, not both");
- if (httpPortStr == null && httpsPortStr == null)
- throw new IllegalArgumentException("Neither an HTTP or HTTPS port was configured");
-
- /// TODO make it more generic
- String httpHost = getDeployProperty(CmsDeployProperty.HOST);
+ protected void configureConnectors(String httpPortStr, String httpsPortStr, String httpHost) {
// try {
if (httpPortStr != null || httpsPortStr != null) {
int httpsPort = Integer.parseInt(httpsPortStr);
httpsConnector.setPort(httpsPort);
httpsConnector.setHost(httpHost);
+ httpsConnector.setIdleTimeout(DEFAULT_IDLE_TIMEOUT);
}
}
}
/hostkey.ser
/id_rsa
/id_rsa.pub
+/*.p12
\ No newline at end of file
org.apache.sshd.common.channel,\
org.apache.sshd.common.helpers,\
org.apache.sshd.common.file.util,\
+org.bouncycastle.jcajce.provider;resolution:="optional",\
+org.bouncycastle.jce.provider;resolution:="optional",\
+org.bouncycastle.*;resolution:="optional",\
+!java.*,\
*
+# NOTE: making the provider packages optional leaves open to switch back to BC non-fips provider.
+
Service-Component: \
OSGI-INF/cmsSshServer.xml
.,\
OSGI-INF/
source.. = src/
-additional.bundles = org.slf4j.api,\
- org.argeo.ext.slf4j,\
+additional.bundles = org.argeo.tp.syslogger,\
org.apache.tomcat.jni
\ No newline at end of file
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
+import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.file.Files;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
+import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.Certificate;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
public class BcUtils {
private final static CmsLog log = CmsLog.getLog(BcUtils.class);
- private final static String BC_SECURITY_PROVIDER;
+ private final static String BC_SECURITY_PROVIDER_FIPS = "BCFIPS";
+// private final static String BC_SECURITY_PROVIDER_NON_FIPS = "BC";
+ public final static String BC_SECURITY_PROVIDER;
static {
- Security.addProvider(new BouncyCastleProvider());
- BC_SECURITY_PROVIDER = "BC";
+ Class<?> clss = null;
+ try {
+ clss = Class.forName("org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider");
+ } catch (ClassNotFoundException e) {
+ log.warn("Bouncy Castle FIPS provider could not be initialised,"
+ + " we assume the non-FIPS provider is configured externally. (" + e + ")");
+ try {
+ clss = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
+ } catch (ClassNotFoundException e1) {
+ // silent
+ }
+ }
+ if (clss != null) {
+ try {
+ Provider provider = (Provider) clss.getDeclaredConstructor().newInstance();
+ Security.addProvider(provider);
+ BC_SECURITY_PROVIDER = provider.getName();
+ } catch (IllegalAccessException | InstantiationException | IllegalArgumentException
+ | InvocationTargetException | NoSuchMethodException | SecurityException e) {
+ throw new IllegalStateException("Cannot load Bouncy Castle provider " + clss, e);
+ }
+ } else {
+ throw new IllegalStateException("Cannot load any Bouncy Castle provider");
+ }
}
+ public static boolean isFipsProvider() {
+ return BC_SECURITY_PROVIDER.equals(BC_SECURITY_PROVIDER_FIPS);
+ }
+
+ /*
+ * openssl req -x509 -newkey rsa:3072 -keyout node.key -out node.crt -sha256 -days 365 -nodes -subj "/O=UNSECURE/OU=UNSECURE/CN=$(hostname)"
+ */
public static void createSelfSignedKeyStore(Path keyStorePath, char[] keyStorePassword, String keyStoreType) {
// for (Provider provider : Security.getProviders())
// System.out.println(provider.getName());
KeyStore keyStore = getKeyStore(keyStorePath, keyStorePassword, keyStoreType);
generateSelfSignedCertificate(keyStore,
new X500Principal("CN=" + InetAddress.getLocalHost().getHostName() + ",OU=UNSECURE,O=UNSECURE"),
- 1024, keyPwd);
+ 3072, keyPwd);
saveKeyStore(keyStorePath, keyStorePassword, keyStore);
if (log.isDebugEnabled())
log.debug("Created self-signed unsecure keystore " + keyStorePath);
/** singleton */
private BcUtils() {
}
+
+// public static void main(String args[]) {
+// createSelfSignedKeyStore(Paths.get("./selfsigned.p12"), "demo".toCharArray(), "PKCS12");
+// }
}
import org.apache.sshd.common.config.keys.KeyUtils;
import org.apache.sshd.common.config.keys.PublicKeyEntry;
+import org.argeo.cms.bc.BcUtils;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PKCS8Generator;
-import org.bouncycastle.openssl.bc.BcPEMDecryptorProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.openssl.jcajce.JcaPKCS8Generator;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8EncryptorBuilder;
+import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OutputEncryptor;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
- PEMDecryptorProvider decryptorProvider = new BcPEMDecryptorProvider(password);
+ JcePEMDecryptorProviderBuilder decryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
+ decryptorProviderBuilder.setProvider(BcUtils.BC_SECURITY_PROVIDER);
+ PEMDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password);
PEMKeyPair pemKp = ekp.decryptKeyPair(decryptorProvider);
kp = converter.getKeyPair(pemKp);
} else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
import java.util.Locale;
import java.util.Map;
+import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
@Override
public ContentSession get(Locale locale) {
- if (!CmsSession.hasCmsSession(CurrentSubject.current())) {
- if (DataAdminPrincipal.isDataAdmin(CurrentSubject.current())) {
+ Subject subject = CurrentSubject.current();
+ if (subject == null)
+ throw new IllegalStateException("Caller must be authenticated");
+ if (!CmsSession.hasCmsSession(subject)) {
+ if (DataAdminPrincipal.isDataAdmin(subject)) {
// TODO open multiple data admin sessions?
return getSystemSession();
}
import java.util.HashSet;
import java.util.Locale;
+import java.util.Map;
+import java.util.NavigableMap;
import java.util.Set;
+import java.util.Spliterator;
+import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
import javax.security.auth.Subject;
import org.argeo.api.acr.Content;
import org.argeo.api.acr.ContentSession;
import org.argeo.api.acr.DName;
+import org.argeo.api.acr.search.BasicSearch;
+import org.argeo.api.acr.search.BasicSearch.Scope;
import org.argeo.api.acr.spi.ContentProvider;
import org.argeo.api.acr.spi.ProvidedContent;
import org.argeo.api.acr.spi.ProvidedRepository;
}
return sessionRunDir;
}
+
+ /*
+ * SEARCH
+ */
+ @Override
+ public Stream<Content> search(Consumer<BasicSearch> search) {
+ BasicSearch s = new BasicSearch();
+ search.accept(s);
+ NavigableMap<String, SearchPartition> searchPartitions = new TreeMap<>();
+ for (Scope scope : s.getFrom()) {
+ String scopePath = scope.getUri().getPath();
+ NavigableMap<String, ContentProvider> contentProviders = contentRepository.getMountManager()
+ .findContentProviders(scopePath);
+ for (Map.Entry<String, ContentProvider> contentProvider : contentProviders.entrySet()) {
+ // TODO deal with depth
+ String relPath;
+ if (scopePath.startsWith(contentProvider.getKey())) {
+ relPath = scopePath.substring(contentProvider.getKey().length());
+ } else {
+ relPath = null;
+ }
+ SearchPartition searchPartition = new SearchPartition(s, relPath, contentProvider.getValue());
+ searchPartitions.put(contentProvider.getKey(), searchPartition);
+ }
+ }
+ return StreamSupport.stream(new SearchPartitionsSpliterator(searchPartitions), true);
+ }
+
+ class SearchPartition {
+ BasicSearch search;
+ String relPath;
+ ContentProvider contentProvider;
+
+ public SearchPartition(BasicSearch search, String relPath, ContentProvider contentProvider) {
+ super();
+ this.search = search;
+ this.relPath = relPath;
+ this.contentProvider = contentProvider;
+ }
+
+ public BasicSearch getSearch() {
+ return search;
+ }
+
+ public String getRelPath() {
+ return relPath;
+ }
+
+ public ContentProvider getContentProvider() {
+ return contentProvider;
+ }
+
+ }
+
+ class SearchPartitionsSpliterator implements Spliterator<Content> {
+ NavigableMap<String, SearchPartition> searchPartitions;
+
+ Spliterator<Content> currentSpliterator;
+
+ public SearchPartitionsSpliterator(NavigableMap<String, SearchPartition> searchPartitions) {
+ super();
+ this.searchPartitions = searchPartitions;
+ SearchPartition searchPartition = searchPartitions.pollFirstEntry().getValue();
+ currentSpliterator = searchPartition.getContentProvider().search(CmsContentSession.this,
+ searchPartition.getSearch(), searchPartition.getRelPath());
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer<? super Content> action) {
+ boolean remaining = currentSpliterator.tryAdvance(action);
+ if (remaining)
+ return true;
+ if (searchPartitions.isEmpty())
+ return false;
+ SearchPartition searchPartition = searchPartitions.pollFirstEntry().getValue();
+ currentSpliterator = searchPartition.getContentProvider().search(CmsContentSession.this,
+ searchPartition.getSearch(), searchPartition.getRelPath());
+ return true;
+ }
+
+ @Override
+ public Spliterator<Content> trySplit() {
+ if (searchPartitions.isEmpty()) {
+ return null;
+ } else if (searchPartitions.size() == 1) {
+ NavigableMap<String, SearchPartition> newSearchPartitions = new TreeMap<>(searchPartitions);
+ searchPartitions.clear();
+ return new SearchPartitionsSpliterator(newSearchPartitions);
+ } else {
+ NavigableMap<String, SearchPartition> newSearchPartitions = new TreeMap<>();
+ for (int i = 0; i < searchPartitions.size() / 2; i++) {
+ Map.Entry<String, SearchPartition> searchPartition = searchPartitions.pollLastEntry();
+ newSearchPartitions.put(searchPartition.getKey(), searchPartition.getValue());
+ }
+ return new SearchPartitionsSpliterator(newSearchPartitions);
+ }
+ }
+
+ @Override
+ public long estimateSize() {
+ return Long.MAX_VALUE;
+ }
+
+ @Override
+ public int characteristics() {
+ return NONNULL;
+ }
+
+ }
}
\ No newline at end of file
return partitions.get(mountPath);
}
+ /** The content provider for this path. */
synchronized ContentProvider findContentProvider(String path) {
// if (ContentUtils.EMPTY.equals(path))
// return partitions.firstEntry().getValue();
assert mountPath.equals(contentProvider.getMountPath());
return contentProvider;
}
+
+ /** All content provider under this path. */
+ synchronized NavigableMap<String, ContentProvider> findContentProviders(String path) {
+ NavigableMap<String, ContentProvider> res = new TreeMap<>();
+ tail: for (Map.Entry<String, ContentProvider> provider : partitions.tailMap(path).entrySet()) {
+ if (!provider.getKey().startsWith(path))
+ break tail;
+ res.put(provider.getKey(), provider.getValue());
+ }
+ return res;
+
+ }
+
}
@Override
public void remove() {
- FsUtils.delete(path);
+ try {
+ FsUtils.delete(path);
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot delete " + path, e);
+ }
}
@Override
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
+import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
log.debug("## CMS starting... (" + uuid + ")\n" + sb + "\n");
}
+ if (log.isTraceEnabled()) {
+ // print system properties
+ StringJoiner sb = new StringJoiner("\n");
+ for (Object key : new TreeMap<>(System.getProperties()).keySet()) {
+ sb.add(key + "=" + System.getProperty(key.toString()));
+ }
+ log.trace("System properties:\n" + sb + "\n");
+
+ }
+
} catch (RuntimeException | IOException e) {
log.error("## FATAL: CMS state failed", e);
}
// explicitly load JAAS configuration
Configuration.getConfiguration();
- boolean initSsl = getDeployProperty(CmsDeployProperty.HTTPS_PORT) != null;
- if (initSsl) {
+ boolean initCertificates = (getDeployProperty(CmsDeployProperty.HTTPS_PORT) != null)
+ || (getDeployProperty(CmsDeployProperty.SSHD_PORT) != null);
+ if (initCertificates) {
initCertificates();
}
}
log.error("Cannot trust CA certificate", e);
}
}
-
-// if (!Files.exists(keyStorePath))
-// PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
}
public void stop() {
return KernelUtils.getOsgiInstancePath(relativePath);
}
+ @Override
+ public Path getStatePath(String relativePath) {
+ return KernelUtils.getOsgiConfigurationPath(relativePath);
+ }
+
@Override
public Long getAvailableSince() {
return availableSince;
return Paths.get(uri);
}
+ public static Path getOsgiConfigurationPath(String relativePath) {
+ URI uri = getOsgiConfigurationUri(relativePath);
+ if (uri == null) // no data area available
+ return null;
+ return Paths.get(uri);
+ }
+
public static URI getOsgiInstanceUri(String relativePath) {
String osgiInstanceBaseUri = getFrameworkProp(OSGI_INSTANCE_AREA);
if (osgiInstanceBaseUri == null) // no data area available
return safeUri(osgiInstanceBaseUri + (relativePath != null ? relativePath : ""));
}
+ public static URI getOsgiConfigurationUri(String relativePath) {
+ String osgiInstanceBaseUri = getFrameworkProp(OSGI_CONFIGURATION_AREA);
+ if (osgiInstanceBaseUri == null) // no data area available
+ return null;
+
+ if (!osgiInstanceBaseUri.endsWith("/"))
+ osgiInstanceBaseUri = osgiInstanceBaseUri + "/";
+ return safeUri(osgiInstanceBaseUri + (relativePath != null ? relativePath : ""));
+ }
+
static String getFrameworkProp(String key, String def) {
String value;
if (CmsActivator.getBundleContext() != null)
* Deletes this path, recursively if needed. Does nothing if the path does not
* exist.
*/
- public static void delete(Path path) {
- try {
- if (!Files.exists(path))
- return;
- Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
- if (e != null)
- throw e;
- Files.delete(directory);
- return FileVisitResult.CONTINUE;
- }
+ public static void delete(Path path) throws IOException {
+ if (!Files.exists(path))
+ return;
+ Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
+ if (e != null)
+ throw e;
+ Files.delete(directory);
+ return FileVisitResult.CONTINUE;
+ }
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
- Files.delete(file);
- return FileVisitResult.CONTINUE;
- }
- });
- } catch (IOException e) {
- throw new RuntimeException("Cannot delete " + path, e);
- }
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+ });
}
/** Singleton. */
import java.nio.file.Path;
import java.nio.file.Paths;
-/** When OS specific informations are needed. */
+/**
+ * Wrapper around system properties and portable Java APIS, for when OS specific
+ * informations are needed.
+ */
public class OS {
public final static OS LOCAL = new OS();
return new String[] { "cmd.exe", "/C" };
}
- public static long getJvmPid() {
- return ProcessHandle.current().pid();
-// String pidAndHost = ManagementFactory.getRuntimeMXBean().getName();
-// return Integer.parseInt(pidAndHost.substring(0, pidAndHost.indexOf('@')));
- }
+// public static long getJvmPid() {
+// return ProcessHandle.current().pid();
+//// String pidAndHost = ManagementFactory.getRuntimeMXBean().getName();
+//// return Integer.parseInt(pidAndHost.substring(0, pidAndHost.indexOf('@')));
+// }
/**
* Get the runtime directory. It will be the environment variable
- * XDG_RUNTIME_DIR if it is set, or ~/.cache/argeo if not.
+ * XDG_RUNTIME_DIR if it is set, or /run if the user is 'root', or
+ * ~/.cache/argeo if not.
*/
public static Path getRunDir() {
Path runDir;
// TODO support multiple names
runDir = Paths.get(xdgRunDir);
} else {
- runDir = Paths.get(System.getProperty("user.home"), ".cache/argeo");
+ if (System.getProperty("user.name").equals("root")) {
+ runDir = Paths.get("/run");
+ } else {
+ runDir = Paths.get(System.getProperty("user.home"), ".cache/argeo");
+ }
}
return runDir;
}
--- /dev/null
+org.argeo.init.jshell.DirectExecutionControlProvider
\ No newline at end of file
package org.argeo.init;
+/** A runtime context with a life cycle. */
public interface RuntimeContext extends Runnable {
+ /** Wait until this runtime context has closed. */
void waitForStop(long timeout) throws InterruptedException;
+ /** Close this runtime context. */
void close() throws Exception;
}
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
+import java.util.TreeMap;
import org.argeo.init.logging.ThinLoggerFinder;
import org.argeo.init.osgi.OsgiBoot;
public class Service {
private final static Logger logger = System.getLogger(Service.class.getName());
+ final static String FILE_SYSTEM_PROPERTIES = "system.properties";
+
public final static String PROP_ARGEO_INIT_MAIN = "argeo.init.main";
private static RuntimeContext runtimeContext = null;
if (configArea != null) {
Path configAreaPath = Paths.get(configArea);
- Path additionalSystemPropertiesPath = configAreaPath.resolve("system.properties");
+ Path additionalSystemPropertiesPath = configAreaPath.resolve(FILE_SYSTEM_PROPERTIES);
if (Files.exists(additionalSystemPropertiesPath)) {
Properties properties = new Properties();
try (InputStream in = Files.newInputStream(additionalSystemPropertiesPath)) {
+ currentValue + " instead of " + value + ". Ignoring new value.");
} else {
System.setProperty(key.toString(), value);
+ logger.log(Logger.Level.TRACE, () -> "Added " + key + "=" + value
+ + " to system properties, from " + additionalSystemPropertiesPath.getFileName());
}
}
ThinLoggerFinder.reloadConfiguration();
Map<String, String> config = new HashMap<>();
config.put(PROP_ARGEO_INIT_MAIN, "true");
+ // add OSGi system properties to the configuration
+ sysprops: for (Object key : new TreeMap<>(System.getProperties()).keySet()) {
+ String keyStr = key.toString();
+ switch (keyStr) {
+ case OsgiBoot.PROP_OSGI_CONFIGURATION_AREA:
+ case OsgiBoot.PROP_OSGI_SHARED_CONFIGURATION_AREA:
+ case OsgiBoot.PROP_OSGI_INSTANCE_AREA:
+ // we should already have dealt with those
+ continue sysprops;
+ default:
+ }
+
+ if (keyStr.startsWith("osgi.") || keyStr.startsWith("org.osgi.") || keyStr.startsWith("eclipse.")
+ || keyStr.startsWith("org.eclipse.equinox.") || keyStr.startsWith("felix.")) {
+ String value = System.getProperty(keyStr);
+ config.put(keyStr, value);
+ logger.log(Logger.Level.TRACE,
+ () -> "Added " + key + "=" + value + " to configuration, from system properties");
+ }
+ }
+
try {
try {
if (stateArea != null)
logger.log(Logger.Level.DEBUG, "Argeo Init stopped with PID " + pid);
}
+ /** The root runtime context in this JVM. */
public static RuntimeContext getRuntimeContext() {
return runtimeContext;
}
final static String CLASSPATH = "classpath";
final static String DEFAULT = "default";
+ final static String LIB = "lib";
private final ProvisioningSource source;
private final String id;
}
}
+ static String localOsArchRelativePath() {
+ return Os.local().toString() + "/" + Arch.local().toString();
+ }
+
+ static enum Os {
+ LINUX, WIN32, MACOSX, UNKOWN;
+
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
+
+ public static Os local() {
+ String osStr = System.getProperty("os.name").toLowerCase();
+ if (osStr.startsWith("linux"))
+ return LINUX;
+ if (osStr.startsWith("win"))
+ return WIN32;
+ if (osStr.startsWith("mac"))
+ return MACOSX;
+ return UNKOWN;
+ }
+
+ }
+
+ static enum Arch {
+ X86_64, AARCH64, X86, POWERPC, UNKOWN;
+
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
+
+ public static Arch local() {
+ String archStr = System.getProperty("os.arch").toLowerCase();
+ return switch (archStr) {
+ case "x86_64":
+ case "amd64":
+ case "x86-64": {
+ yield X86_64;
+ }
+ case "aarch64":
+ case "arm64": {
+ yield AARCH64;
+ }
+ case "x86":
+ case "i386":
+ case "i686": {
+ yield X86;
+ }
+ case "powerpc":
+ case "ppc": {
+ yield POWERPC;
+ }
+ default:
+ yield UNKOWN;
+ };
+ }
+ }
+
}
if (variantPath == null)
continue contributions;
- // a variant was found, let's collect its contributions (also common ones in its
- // parent)
- for (Path variantContributionPath : Files.newDirectoryStream(variantPath.getParent())) {
- String variantContributionId = variantContributionPath.getFileName().toString();
- if (variantContributionId.contains(".")) {
- A2Contribution contribution = getOrAddContribution(variantContributionId);
- contributions.put(variantContributionPath, contribution);
+ if (Files.exists(variantPath)) {
+ // a variant was found, let's collect its contributions (also common ones in its
+ // parent)
+ for (Path variantContributionPath : Files.newDirectoryStream(variantPath.getParent())) {
+ String variantContributionId = variantContributionPath.getFileName().toString();
+ if (variantContributionId.contains(".")) {
+ A2Contribution contribution = getOrAddContribution(variantContributionId);
+ contributions.put(variantContributionPath, contribution);
+ }
}
- }
- for (Path variantContributionPath : Files.newDirectoryStream(variantPath)) {
- String variantContributionId = variantContributionPath.getFileName().toString();
- if (variantContributionId.contains(".")) {
- A2Contribution contribution = getOrAddContribution(variantContributionId);
- contributions.put(variantContributionPath, contribution);
+ for (Path variantContributionPath : Files.newDirectoryStream(variantPath)) {
+ String variantContributionId = variantContributionPath.getFileName().toString();
+ if (variantContributionId.contains(".")) {
+ A2Contribution contribution = getOrAddContribution(variantContributionId);
+ contributions.put(variantContributionPath, contribution);
+ }
}
}
}
source.load();
addSource(source);
OsgiBootUtils.info("Registered " + uri + " as source");
+
+ // OS specific / native
+ String localRelPath = A2Contribution.localOsArchRelativePath();
+ Path localLibBase = base.resolve(A2Contribution.LIB).resolve(localRelPath);
+ if (Files.exists(localLibBase)) {
+ FsA2Source libSource = new FsA2Source(localLibBase, xOr,
+ SCHEME_A2_REFERENCE.equals(u.getScheme()));
+ libSource.load();
+ addSource(libSource);
+ OsgiBootUtils.info("Registered OS-specific " + uri + " as source (" + localRelPath + ")");
+ }
} else {
OsgiBootUtils.debug("Source " + base + " does not exist, ignoring.");
}
--- /dev/null
+package org.argeo.init.jshell;
+
+import java.util.Map;
+
+import jdk.jshell.execution.DirectExecutionControl;
+import jdk.jshell.spi.ExecutionControl;
+import jdk.jshell.spi.ExecutionControlProvider;
+import jdk.jshell.spi.ExecutionEnv;
+import jdk.jshell.tool.JavaShellToolBuilder;
+
+/**
+ * Canonical {@link ExecutionControlProvider} wrapping a
+ * {@link DirectExecutionControl}, so that {@link JavaShellToolBuilder} can run
+ * in the same VM.
+ */
+public class DirectExecutionControlProvider implements ExecutionControlProvider {
+
+ @Override
+ public String name() {
+ return "direct";
+ }
+
+ @Override
+ public ExecutionControl generate(ExecutionEnv env, Map<String, String> parameters) throws Throwable {
+ return new DirectExecutionControl();
+ }
+
+}
queryPart = source.substring(qmIndex);
source = source.substring(0, qmIndex);
}
+ // TODO centralise in A" package?
if (source.trim().equals(A2Source.DEFAULT_A2_URI)) {
if (Files.exists(homePath))
provisioningManager.registerSource(
A2Source.SCHEME_A2 + "://" + homePath.toString() + "/.local/share/a2" + queryPart);
provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/local/share/a2" + queryPart);
+ provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/local/lib/a2" + queryPart);
provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/share/a2" + queryPart);
+ provisioningManager.registerSource(A2Source.SCHEME_A2 + ":///usr/lib/a2" + queryPart);
} else if (source.trim().equals(A2Source.DEFAULT_A2_REFERENCE_URI)) {
if (Files.exists(homePath))
provisioningManager.registerSource(A2Source.SCHEME_A2_REFERENCE + "://" + homePath.toString()
+ "/.local/share/a2" + queryPart);
provisioningManager
.registerSource(A2Source.SCHEME_A2_REFERENCE + ":///usr/local/share/a2" + queryPart);
+ provisioningManager
+ .registerSource(A2Source.SCHEME_A2_REFERENCE + ":///usr/local/lib/a2" + queryPart);
provisioningManager.registerSource(A2Source.SCHEME_A2_REFERENCE + ":///usr/share/a2" + queryPart);
+ provisioningManager.registerSource(A2Source.SCHEME_A2_REFERENCE + ":///usr/lib/a2" + queryPart);
} else {
provisioningManager.registerSource(source + queryPart);
}
public OsgiBootDiagnostics(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
+
/*
* DIAGNOSTICS
*/
if (unresolvedBundles.size() != 0) {
OsgiBootUtils.warn("Unresolved bundles " + unresolvedBundles);
}
+
+ // try to start unresolved bundles in order to trigger diagnostics
+ // (this should not have side-effects since unresolved bundles won't be able to
+ // start)
+ for (Bundle b : unresolvedBundles) {
+ try {
+ b.start();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
/** List packages exported twice. */
-Subproject commit a1d5c8e4bbee31d104fc1151cac4a8e19f5ef1fa
+Subproject commit d9cae87d811258d5a13e43eea8492f3792377ce4
major=2
minor=3
-micro=14
-qualifier=.next
\ No newline at end of file
+micro=17
+qualifier=
+
+Bundle-Copyright= \
+Copyright 2007-2023 Mathieu Baudier, \
+Copyright 2012-2023 Argeo GmbH
+
+SPDX-License-Identifier= \
+LGPL-2.1-or-later \
+OR EPL-2.0 \
+OR LicenseRef-argeo2-GPL-2.0-or-later-with-EPL-and-JCR-permissions
org.argeo.cms.lib.equinox,\
org.argeo.cms.lib.jetty,\
+#argeo.osgi.start.5=\
+#org.argeo.cms.jshell
# Local
argeo.node.repo.type=h2
-org.osgi.service.http.port=7070
-#org.eclipse.equinox.http.jetty.http.host=[IP address to listen to]
-#org.osgi.service.http.port.secure=7073
-#org.eclipse.equinox.http.jetty.websocket.enabled=true
+argeo.http.port=7070
+#argeo.http.host=[IP address to listen to]
+#argeo.https.port=7073
+#argeo.sshd.port=2222
# Logging
log.org.argeo=DEBUG
# DON'T CHANGE BELOW
org.eclipse.equinox.http.jetty.autostart=false
org.osgi.framework.system.packages.extra=\
+sun.security.internal.spec,\
+sun.security.provider,\
com.sun.net.httpserver,\
com.sun.jndi.ldap,\
com.sun.jndi.ldap.sasl,\
-Dosgi.configuration.area=${STATE_DIRECTORY}/state/ \
-Dosgi.instance.area=${STATE_DIRECTORY}/data/ \
-Dargeo.node.repo.indexesBase=${CACHE_DIRECTORY}/indexes \
+-Dorg.osgi.framework.system.packages.extra=sun.security.internal.spec,sun.security.provider,com.sun.net.httpserver,com.sun.jndi.ldap,com.sun.jndi.ldap.sasl,com.sun.jndi.dns,com.sun.security.jgss,com.sun.nio.file,com.sun.nio.sctp \
-Declipse.ignoreApp=true \
-Dosgi.noShutdown=true \
-Dorg.eclipse.equinox.http.jetty.autostart=false \
-Dosgi.configuration.area=${STATE_DIRECTORY}/state/ \
-Dosgi.instance.area=${STATE_DIRECTORY}/data/ \
-Dargeo.node.repo.indexesBase=${CACHE_DIRECTORY}/indexes \
+-Dorg.osgi.framework.system.packages.extra=sun.security.internal.spec,sun.security.provider,com.sun.net.httpserver,com.sun.jndi.ldap,com.sun.jndi.ldap.sasl,com.sun.jndi.dns,com.sun.security.jgss,com.sun.nio.file,com.sun.nio.sctp \
-Declipse.ignoreApp=true \
-Dosgi.noShutdown=true \
-Dorg.eclipse.equinox.http.jetty.autostart=false \
--- /dev/null
+dn: uid=coworker,ou=People,dc=example,dc=com
+objectClass: inetOrgPerson
+objectClass: organizationalPerson
+objectClass: person
+objectClass: top
+givenName: John
+sn: Coworker
+userPassword:: e1NIQX1pZVNWNTVRYytlUU9hWURSU2hhL0Fqek5USkU9
+mail: coworker@localhost
+uid: coworker
+cn: John Coworker
+description: A regular coworker
+
+dn: uid=manager,ou=People,dc=example,dc=com
+objectClass: inetOrgPerson
+objectClass: organizationalPerson
+objectClass: person
+objectClass: top
+givenName: Mary
+sn: Manager
+userPassword:: e1NIQX1pZVNWNTVRYytlUU9hWURSU2hhL0Fqek5USkU9
+mail: manager@localhost
+uid: manager
+cn: Mary Manager
+description: A manager
+
+dn: uid=root,ou=People,dc=example,dc=com
+objectClass: inetOrgPerson
+objectClass: person
+objectClass: organizationalPerson
+objectClass: top
+givenName: Super
+sn: User
+userPassword:: e1NIQX1pZVNWNTVRYytlUU9hWURSU2hhL0Fqek5USkU9
+mail: root@localhost
+uid: root
+cn: Super User
+description: Superuser
+
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.cms.e4</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ds.core.builder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="Default CallbackHandler">
- <implementation class="org.argeo.cms.swt.auth.DynamicCallbackHandler"/>
- <service>
- <provide interface="javax.security.auth.callback.CallbackHandler"/>
- </service>
-</scr:component>
+++ /dev/null
-Service-Component: OSGI-INF/defaultCallbackHandler.xml
-Bundle-ActivationPolicy: lazy
-
-Import-Package: \
-org.argeo.api.acr,\
-org.eclipse.swt,\
-org.eclipse.swt.widgets;version="0.0.0",\
-org.eclipse.e4.ui.model.application.ui;resolution:=optional,\
-org.eclipse.e4.ui.model.application;resolution:=optional,\
-org.argeo.cms,\
-org.eclipse.core.commands.common,\
-org.eclipse.jface.window,\
-org.eclipse.jface.dialogs,\
-org.argeo.cms.swt.auth,\
-org.argeo.cms.ux.widgets,\
-javax.servlet.*;version="[3,5)",\
-org.eclipse.*;resolution:=optional,\
-javax.*;resolution:=optional,\
-*
-
+++ /dev/null
-output.. = bin/
-bin.includes = META-INF/,\
- OSGI-INF/,\
- .,\
- OSGI-INF/homeRepository.xml,\
- OSGI-INF/userAdminWrapper.xml,\
- OSGI-INF/defaultCallbackHandler.xml,\
- e4xmi/cms-demo.e4xmi
-source.. = src/
+++ /dev/null
-package org.argeo.cms.e4;
-
-import java.util.List;
-
-import org.argeo.cms.swt.CmsException;
-import org.eclipse.e4.ui.model.application.MApplication;
-import org.eclipse.e4.ui.model.application.commands.MCommand;
-import org.eclipse.e4.ui.model.application.ui.basic.MPart;
-import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
-import org.eclipse.e4.ui.model.application.ui.menu.MHandledMenuItem;
-import org.eclipse.e4.ui.workbench.modeling.EModelService;
-import org.eclipse.e4.ui.workbench.modeling.EPartService;
-import org.eclipse.e4.ui.workbench.modeling.EPartService.PartState;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.FrameworkUtil;
-
-/** Static utilities simplifying recurring Eclipse 4 patterns. */
-public class CmsE4Utils {
- /** Open an editor based on its id. */
- public static void openEditor(EPartService partService, String editorId, String key, String state) {
- for (MPart part : partService.getParts()) {
- String id = part.getPersistedState().get(key);
- if (id != null && state.equals(id)) {
- partService.showPart(part, PartState.ACTIVATE);
- return;
- }
- }
-
- // new part
- MPart part = partService.createPart(editorId);
- if (part == null)
- throw new CmsException("No editor found with id " + editorId);
- part.getPersistedState().put(key, state);
- partService.showPart(part, PartState.ACTIVATE);
- }
-
- /** Dynamically creates an handled menu item from a command ID. */
- public static MHandledMenuItem createHandledMenuItem(EModelService modelService, MApplication app,
- String commandId) {
- MCommand command = findCommand(modelService, app, commandId);
- if (command == null)
- return null;
- MHandledMenuItem handledItem = modelService.createModelElement(MHandledMenuItem.class);
- handledItem.setCommand(command);
- return handledItem;
-
- }
-
- /**
- * Finds a command by ID.
- *
- * @return the {@link MCommand} or <code>null</code> if not found.
- */
- public static MCommand findCommand(EModelService modelService, MApplication app, String commandId) {
- List<MCommand> cmds = modelService.findElements(app, null, MCommand.class, null);
- for (MCommand cmd : cmds) {
- if (cmd.getElementId().equals(commandId)) {
- return cmd;
- }
- }
- return null;
- }
-
- /** Dynamically creates a direct menu item from a class. */
- public static MDirectMenuItem createDirectMenuItem(EModelService modelService, Class<?> clss, String label) {
- MDirectMenuItem dynamicItem = modelService.createModelElement(MDirectMenuItem.class);
- dynamicItem.setLabel(label);
- Bundle bundle = FrameworkUtil.getBundle(clss);
- dynamicItem.setContributionURI("bundleclass://" + bundle.getSymbolicName() + "/" + clss.getName());
- return dynamicItem;
- }
-
- /** Singleton. */
- private CmsE4Utils() {
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4;
-
-import org.argeo.cms.swt.CmsException;
-import org.eclipse.e4.core.contexts.ContextFunction;
-import org.eclipse.e4.core.contexts.IEclipseContext;
-import org.eclipse.e4.core.di.IInjector;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.InvalidSyntaxException;
-import org.osgi.framework.ServiceReference;
-
-/** An Eclipse 4 {@link ContextFunction} based on an OSGi filter. */
-public class OsgiFilterContextFunction extends ContextFunction {
-
- private BundleContext bc = FrameworkUtil.getBundle(OsgiFilterContextFunction.class).getBundleContext();
-
- @Override
- public Object compute(IEclipseContext context, String contextKey) {
- ServiceReference<?>[] srs;
- try {
- srs = bc.getServiceReferences((String) null, contextKey);
- } catch (InvalidSyntaxException e) {
- throw new CmsException("Context key " + contextKey + " must be a valid osgi filter", e);
- }
- if (srs == null || srs.length == 0) {
- return IInjector.NOT_A_VALUE;
- } else {
- // return the first one
- return bc.getService(srs[0]);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.Job;
-
-/**
- * Propagate authentication to an eclipse job. Typically to execute a privileged
- * action outside the UI thread
- */
-public abstract class PrivilegedJob extends Job {
- private final Subject subject;
-
- public PrivilegedJob(String jobName) {
- this(jobName, AccessController.getContext());
- }
-
- public PrivilegedJob(String jobName,
- AccessControlContext accessControlContext) {
- super(jobName);
- subject = Subject.getSubject(accessControlContext);
-
- // Must be called *before* the job is scheduled,
- // it is required for the progress window to appear
- setUser(true);
- }
-
- @Override
- protected IStatus run(final IProgressMonitor progressMonitor) {
- PrivilegedAction<IStatus> privilegedAction = new PrivilegedAction<IStatus>() {
- public IStatus run() {
- return doRun(progressMonitor);
- }
- };
- return Subject.doAs(subject, privilegedAction);
- }
-
- /**
- * Implement here what should be executed with default context
- * authentication
- */
- protected abstract IStatus doRun(IProgressMonitor progressMonitor);
-}
+++ /dev/null
-package org.argeo.cms.e4.addons;
-
-import java.security.AccessController;
-import java.util.Iterator;
-
-import javax.annotation.PostConstruct;
-import javax.security.auth.Subject;
-import javax.servlet.http.HttpServletRequest;
-
-import org.argeo.api.cms.CmsLog;
-import org.argeo.cms.CurrentUser;
-import org.argeo.cms.swt.CmsException;
-import org.eclipse.e4.ui.model.application.MApplication;
-import org.eclipse.e4.ui.model.application.ui.MElementContainer;
-import org.eclipse.e4.ui.model.application.ui.MUIElement;
-import org.eclipse.e4.ui.model.application.ui.basic.MTrimBar;
-import org.eclipse.e4.ui.model.application.ui.basic.MTrimmedWindow;
-import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
-
-public class AuthAddon {
- private final static CmsLog log = CmsLog.getLog(AuthAddon.class);
-
- public final static String AUTH = "auth.";
-
- @PostConstruct
- void init(MApplication application) {
- Iterator<MWindow> windows = application.getChildren().iterator();
- boolean atLeastOneTopLevelWindowVisible = false;
- windows: while (windows.hasNext()) {
- MWindow window = windows.next();
- // main window
- boolean windowVisible = process(window);
- if (!windowVisible) {
-// windows.remove();
- continue windows;
- }
- atLeastOneTopLevelWindowVisible = true;
- // trim bars
- if (window instanceof MTrimmedWindow) {
- Iterator<MTrimBar> trimBars = ((MTrimmedWindow) window).getTrimBars().iterator();
- while (trimBars.hasNext()) {
- MTrimBar trimBar = trimBars.next();
- if (!process(trimBar)) {
- trimBars.remove();
- }
- }
- }
- }
-
- if (!atLeastOneTopLevelWindowVisible) {
- log.warn("No top-level window is authorized for user " + CurrentUser.getUsername() + ", logging out..");
- logout();
- }
- }
-
- protected boolean process(MUIElement element) {
- for (String tag : element.getTags()) {
- if (tag.startsWith(AUTH)) {
- String role = tag.substring(AUTH.length(), tag.length());
- if (!CurrentUser.isInRole(role)) {
- element.setVisible(false);
- element.setToBeRendered(false);
- return false;
- }
- }
- }
-
- // children
- if (element instanceof MElementContainer) {
- @SuppressWarnings("unchecked")
- MElementContainer<? extends MUIElement> container = (MElementContainer<? extends MUIElement>) element;
- Iterator<? extends MUIElement> children = container.getChildren().iterator();
- while (children.hasNext()) {
- MUIElement child = children.next();
- boolean visible = process(child);
- if (!visible)
- children.remove();
- }
-
- for (Object child : container.getChildren()) {
- if (child instanceof MUIElement) {
- boolean visible = process((MUIElement) child);
- if (!visible)
- container.getChildren().remove(child);
- }
- }
- }
-
- return true;
- }
-
- protected void logout() {
- Subject subject = Subject.getSubject(AccessController.getContext());
- try {
- CurrentUser.logoutCmsSession(subject);
- } catch (Exception e) {
- throw new CmsException("Cannot log out", e);
- }
-
- // FIXME make it more generic
- HttpServletRequest request = org.argeo.eclipse.ui.specific.UiContext.getHttpRequest();
- if (request != null)
- request.getSession().setMaxInactiveInterval(0);
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4.addons;
-
-import java.security.AccessController;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import javax.annotation.PostConstruct;
-import javax.security.auth.Subject;
-
-import org.argeo.eclipse.ui.specific.UiContext;
-import org.eclipse.e4.core.services.nls.ILocaleChangeService;
-import org.eclipse.e4.ui.model.application.MApplication;
-import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
-import org.eclipse.e4.ui.workbench.modeling.EModelService;
-import org.eclipse.e4.ui.workbench.modeling.ElementMatcher;
-import org.eclipse.swt.SWT;
-
-/** Integrate workbench with the locale provided at log in. */
-public class LocaleAddon {
- private final static String STYLE_OVERRIDE = "styleOverride";
-
- // Right to left languages
- private final static String ARABIC = "ar";
- private final static String HEBREW = "he";
-
- @PostConstruct
- public void init(ILocaleChangeService localeChangeService, EModelService modelService, MApplication application) {
- Subject subject = Subject.getSubject(AccessController.getContext());
- Set<Locale> locales = subject.getPublicCredentials(Locale.class);
- if (!locales.isEmpty()) {
- Locale locale = locales.iterator().next();
- localeChangeService.changeApplicationLocale(locale);
- UiContext.setLocale(locale);
-
- if (locale.getLanguage().equals(ARABIC) || locale.getLanguage().equals(HEBREW)) {
- List<MWindow> windows = modelService.findElements(application, MWindow.class, EModelService.ANYWHERE,
- new ElementMatcher(null, null, (String) null));
- for (MWindow window : windows) {
- String currentStyle = window.getPersistedState().get(STYLE_OVERRIDE);
- int style = 0;
- if (currentStyle != null) {
- style = Integer.parseInt(currentStyle);
- }
- style = style | SWT.RIGHT_TO_LEFT;
- window.getPersistedState().put(STYLE_OVERRIDE, Integer.toString(style));
- }
- }
- }
- }
-}
+++ /dev/null
-/** Eclipse 4 addons to integrate with Argeo CMS. */
-package org.argeo.cms.e4.addons;
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import java.util.Locale;
-
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.core.services.nls.ILocaleChangeService;
-
-public class ChangeLanguage {
- @Execute
- public void execute(ILocaleChangeService localeChangeService) {
- localeChangeService.changeApplicationLocale(Locale.FRENCH);
- }
-}
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import static org.argeo.cms.CmsMsg.changePassword;
-import static org.argeo.cms.CmsMsg.currentPassword;
-import static org.argeo.cms.CmsMsg.newPassword;
-import static org.argeo.cms.CmsMsg.passwordChanged;
-import static org.argeo.cms.CmsMsg.repeatNewPassword;
-
-import java.util.Arrays;
-
-import javax.inject.Inject;
-import javax.naming.InvalidNameException;
-import javax.naming.ldap.LdapName;
-
-import org.argeo.api.cms.keyring.CryptoKeyring;
-import org.argeo.api.cms.transaction.WorkTransaction;
-import org.argeo.cms.CurrentUser;
-import org.argeo.cms.swt.dialogs.CmsFeedback;
-import org.argeo.cms.swt.dialogs.CmsMessageDialog;
-import org.argeo.cms.ux.widgets.CmsDialog;
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.core.di.annotations.Optional;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.osgi.service.useradmin.User;
-import org.osgi.service.useradmin.UserAdmin;
-
-/** Change the password of the logged-in user. */
-public class ChangePassword {
- @Inject
- private UserAdmin userAdmin;
- @Inject
- private WorkTransaction userTransaction;
- @Inject
- @Optional
- private CryptoKeyring keyring = null;
-
- @Execute
- public void execute() {
- ChangePasswordDialog dialog = new ChangePasswordDialog(Display.getCurrent().getActiveShell(), userAdmin);
- if (dialog.open() == CmsDialog.OK) {
- new CmsMessageDialog(Display.getCurrent().getActiveShell(), passwordChanged.lead(),
- CmsMessageDialog.INFORMATION).open();
- }
- }
-
- protected void changePassword(char[] oldPassword, char[] newPassword) {
- String name = CurrentUser.getUsername();
- LdapName dn;
- try {
- dn = new LdapName(name);
- } catch (InvalidNameException e) {
- throw new IllegalArgumentException("Invalid user dn " + name, e);
- }
- User user = (User) userAdmin.getRole(dn.toString());
- if (!user.hasCredential(null, oldPassword))
- throw new IllegalArgumentException("Invalid password");
- if (Arrays.equals(newPassword, new char[0]))
- throw new IllegalArgumentException("New password empty");
- try {
- userTransaction.begin();
- user.getCredentials().put(null, newPassword);
- if (keyring != null) {
- keyring.changePassword(oldPassword, newPassword);
- // TODO change secret keys in the CMS session
- }
- userTransaction.commit();
- } catch (Exception e) {
- try {
- userTransaction.rollback();
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- if (e instanceof RuntimeException)
- throw (RuntimeException) e;
- else
- throw new IllegalStateException("Cannot change password", e);
- }
- }
-
- class ChangePasswordDialog extends CmsMessageDialog {
- private Text oldPassword, newPassword1, newPassword2;
-
- public ChangePasswordDialog(Shell parentShell, UserAdmin securityService) {
- super(parentShell, changePassword.lead(), CONFIRM);
- }
-
-// protected Point getInitialSize() {
-// return new Point(400, 450);
-// }
-
- protected Control createDialogArea(Composite parent) {
- Composite dialogarea = (Composite) super.createDialogArea(parent);
- dialogarea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- Composite composite = new Composite(dialogarea, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- oldPassword = createLP(composite, currentPassword.lead());
- newPassword1 = createLP(composite, newPassword.lead());
- newPassword2 = createLP(composite, repeatNewPassword.lead());
-
-// parent.pack();
- oldPassword.setFocus();
- return composite;
- }
-
- @Override
- protected void okPressed() {
- try {
- if (!newPassword1.getText().equals(newPassword2.getText()))
- throw new IllegalArgumentException("New passwords are different");
- changePassword(oldPassword.getTextChars(), newPassword1.getTextChars());
- closeShell(CmsDialog.OK);
- } catch (Exception e) {
- CmsFeedback.error("Cannot change password", e);
- }
- }
-
- /** Creates label and password. */
- protected Text createLP(Composite parent, String label) {
- new Label(parent, SWT.NONE).setText(label);
- Text text = new Text(parent, SWT.SINGLE | SWT.LEAD | SWT.PASSWORD | SWT.BORDER);
- text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- return text;
- }
-
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import org.eclipse.e4.core.di.annotations.CanExecute;
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.ui.model.application.ui.basic.MPart;
-import org.eclipse.e4.ui.workbench.modeling.EPartService;
-
-public class CloseAllParts {
-
- @Execute
- void execute(EPartService partService) {
- for (MPart part : partService.getParts()) {
- if (part.isCloseable()) {
- if (part.isDirty()) {
- if (partService.savePart(part, true)) {
- partService.hidePart(part, true);
- }
- } else {
- partService.hidePart(part, true);
- }
- }
- }
- }
-
- @CanExecute
- boolean canExecute(EPartService partService) {
- boolean atLeastOnePart = false;
- for (MPart part : partService.getParts()) {
- if (part.isVisible() && part.isCloseable()) {
- atLeastOnePart = true;
- break;
- }
- }
- return atLeastOnePart;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import javax.security.auth.Subject;
-
-import org.argeo.cms.CurrentUser;
-import org.argeo.cms.util.CurrentSubject;
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.ui.workbench.IWorkbench;
-
-public class CloseWorkbench {
- @Execute
- public void execute(IWorkbench workbench) {
- logout();
- workbench.close();
- }
-
- protected void logout() {
- Subject subject = CurrentSubject.current();
- try {
- CurrentUser.logoutCmsSession(subject);
- } catch (Exception e) {
- throw new IllegalStateException("Cannot log out", e);
- }
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import org.eclipse.e4.core.di.annotations.Execute;
-
-public class DoNothing {
- @Execute
- public void execute() {
-
- }
-}
+++ /dev/null
-
-package org.argeo.cms.e4.handlers;
-
-import java.util.Date;
-import java.util.List;
-
-import org.eclipse.e4.ui.di.AboutToHide;
-import org.eclipse.e4.ui.di.AboutToShow;
-import org.eclipse.e4.ui.model.application.ui.menu.MDirectMenuItem;
-import org.eclipse.e4.ui.model.application.ui.menu.MMenuElement;
-import org.eclipse.e4.ui.workbench.modeling.EModelService;
-
-public class LanguageMenuContribution {
- @AboutToShow
- public void aboutToShow(List<MMenuElement> items, EModelService modelService) {
- MDirectMenuItem dynamicItem = modelService.createModelElement(MDirectMenuItem.class);
- dynamicItem.setLabel("Dynamic Menu Item (" + new Date() + ")");
- //dynamicItem.setContributorURI("platform:/plugin/org.argeo.cms.e4");
- //dynamicItem.setContributionURI("bundleclass://org.argeo.cms.e4/" + ChangeLanguage.class.getName());
- dynamicItem.setEnabled(true);
- dynamicItem.setContributionURI("bundleclass://org.argeo.cms.e4/org.argeo.cms.e4.handlers.ChangeLanguage");
- items.add(dynamicItem);
- }
-
- @AboutToHide
- public void aboutToHide() {
-
- }
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.ui.model.application.MApplication;
-import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
-import org.eclipse.e4.ui.workbench.modeling.EModelService;
-import org.eclipse.e4.ui.workbench.modeling.EPartService;
-
-public class OpenPerspective {
- @Inject
- MApplication application;
- @Inject
- EPartService partService;
- @Inject
- EModelService modelService;
-
- @Execute
- public void execute(@Named("perspectiveId") String perspectiveId) {
- List<MPerspective> perspectives = modelService.findElements(application, perspectiveId, MPerspective.class,
- null);
- if (perspectives.size() == 0)
- return;
- MPerspective perspective = perspectives.get(0);
- partService.switchPerspective(perspective);
- }
-}
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import org.eclipse.e4.core.di.annotations.CanExecute;
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.ui.workbench.modeling.EPartService;
-
-public class SaveAllParts {
-
- @Execute
- void execute(EPartService partService) {
- partService.saveAll(false);
- }
-
- @CanExecute
- boolean canExecute(EPartService partService) {
- return partService.getDirtyParts().size() > 0;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-package org.argeo.cms.e4.handlers;
-
-import org.eclipse.e4.core.di.annotations.CanExecute;
-import org.eclipse.e4.core.di.annotations.Execute;
-import org.eclipse.e4.ui.model.application.ui.basic.MPart;
-import org.eclipse.e4.ui.workbench.modeling.EPartService;
-
-public class SavePart {
- @Execute
- void execute(EPartService partService, MPart part) {
- partService.savePart(part, false);
- }
-
- @CanExecute
- boolean canExecute(MPart part) {
- return part.isDirty();
- }
-}
\ No newline at end of file
+++ /dev/null
-/** Generic Eclipse 4 handlers. */
-package org.argeo.cms.e4.handlers;
\ No newline at end of file
+++ /dev/null
-/** Eclipse 4 user interfaces. */
-package org.argeo.cms.e4;
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.cms.e4.rap</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ds.core.builder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-Import-Package: \
-org.argeo.api.acr, \
-org.eclipse.swt,\
-org.eclipse.swt.graphics,\
-org.eclipse.e4.ui.workbench,\
-org.eclipse.rap.rwt.client,\
-org.eclipse.nebula.widgets.richtext;resolution:=optional,\
-org.eclipse.*;resolution:=optional,\
-*
+++ /dev/null
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- OSGI-INF/
+++ /dev/null
-package org.argeo.cms.e4.rap;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.argeo.cms.swt.dialogs.CmsFeedback;
-import org.eclipse.rap.e4.E4ApplicationConfig;
-import org.eclipse.rap.rwt.application.Application;
-import org.eclipse.rap.rwt.application.Application.OperationMode;
-import org.eclipse.rap.rwt.application.ApplicationConfiguration;
-import org.eclipse.rap.rwt.application.ExceptionHandler;
-import org.eclipse.rap.rwt.client.WebClient;
-import org.osgi.framework.BundleContext;
-
-/** Base class for CMS RAP applications. */
-public abstract class AbstractRapE4App implements ApplicationConfiguration {
- private String e4Xmi;
- private String path;
- private String lifeCycleUri = "bundleclass://org.argeo.cms.e4.rap/org.argeo.cms.e4.rap.CmsLoginLifecycle";
-
- private Map<String, String> baseProperties = new HashMap<String, String>();
-
- private BundleContext bundleContext;
- public final static String CONTEXT_NAME_PROPERTY = "contextName";
- private String contextName;
-
- /**
- * To be overridden in order to add multiple entry points, directly or using
- * {@link #addE4EntryPoint(Application, String, String, Map)}.
- */
- protected void addEntryPoints(Application application) {
- }
-
- public void configure(Application application) {
- application.setExceptionHandler(new ExceptionHandler() {
-
- @Override
- public void handleException(Throwable throwable) {
- CmsFeedback.error("Unexpected RWT exception", throwable);
- }
- });
-
- if (e4Xmi != null) {// backward compatibility
- addE4EntryPoint(application, path, e4Xmi, getBaseProperties());
- } else {
- addEntryPoints(application);
- }
- }
-
- protected Map<String, String> getBaseProperties() {
- return baseProperties;
- }
-
-// protected void addEntryPoint(Application application, E4ApplicationConfig config, Map<String, String> properties) {
-// CmsE4EntryPointFactory entryPointFactory = new CmsE4EntryPointFactory(config);
-// application.addEntryPoint(path, entryPointFactory, properties);
-// application.setOperationMode(OperationMode.SWT_COMPATIBILITY);
-// }
-
- protected void addE4EntryPoint(Application application, String path, String e4Xmi, Map<String, String> properties) {
- E4ApplicationConfig config = createE4ApplicationConfig(e4Xmi);
- CmsE4EntryPointFactory entryPointFactory = new CmsE4EntryPointFactory(config);
- application.addEntryPoint(path, entryPointFactory, properties);
- application.setOperationMode(OperationMode.SWT_COMPATIBILITY);
- }
-
- /**
- * To be overridden for further configuration.
- *
- * @see E4ApplicationConfig
- */
- protected E4ApplicationConfig createE4ApplicationConfig(String e4Xmi) {
- return new E4ApplicationConfig(e4Xmi, lifeCycleUri, null, null, false, true, true);
- }
-
- @Deprecated
- public void setPageTitle(String pageTitle) {
- if (pageTitle != null)
- baseProperties.put(WebClient.PAGE_TITLE, pageTitle);
- }
-
- /** Returns a new map used to customise and entry point. */
- public Map<String, String> customise(String pageTitle) {
- Map<String, String> custom = new HashMap<>(getBaseProperties());
- if (pageTitle != null)
- custom.put(WebClient.PAGE_TITLE, pageTitle);
- return custom;
- }
-
- @Deprecated
- public void setE4Xmi(String e4Xmi) {
- this.e4Xmi = e4Xmi;
- }
-
- @Deprecated
- public void setPath(String path) {
- this.path = path;
- }
-
- public void setLifeCycleUri(String lifeCycleUri) {
- this.lifeCycleUri = lifeCycleUri;
- }
-
- protected BundleContext getBundleContext() {
- return bundleContext;
- }
-
- protected void setBundleContext(BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- public String getContextName() {
- return contextName;
- }
-
- public void setContextName(String contextName) {
- this.contextName = contextName;
- }
-
- public void init(BundleContext bundleContext, Map<String, Object> properties) {
- this.bundleContext = bundleContext;
- for (String key : properties.keySet()) {
- Object value = properties.get(key);
- if (value != null)
- baseProperties.put(key, value.toString());
- }
-
- if (properties.containsKey(CONTEXT_NAME_PROPERTY)) {
- assert properties.get(CONTEXT_NAME_PROPERTY) != null;
- contextName = properties.get(CONTEXT_NAME_PROPERTY).toString();
- } else {
- contextName = "<unknown context>";
- }
- }
-
- public void destroy(Map<String, Object> properties) {
-
- }
-}
+++ /dev/null
-package org.argeo.cms.e4.rap;
-
-import java.security.PrivilegedAction;
-
-import javax.security.auth.Subject;
-
-import org.eclipse.rap.e4.E4ApplicationConfig;
-import org.eclipse.rap.e4.E4EntryPointFactory;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.application.EntryPoint;
-import org.eclipse.rap.rwt.client.service.JavaScriptExecutor;
-
-public class CmsE4EntryPointFactory extends E4EntryPointFactory {
- public final static String DEFAULT_LIFECYCLE_URI = "bundleclass://org.argeo.cms.e4.rap/org.argeo.cms.e4.rap.CmsLoginLifecycle";
-
- public CmsE4EntryPointFactory(E4ApplicationConfig config) {
- super(config);
- }
-
- public CmsE4EntryPointFactory(String e4Xmi, String lifeCycleUri) {
- super(defaultConfig(e4Xmi, lifeCycleUri));
- }
-
- public CmsE4EntryPointFactory(String e4Xmi) {
- this(e4Xmi, DEFAULT_LIFECYCLE_URI);
- }
-
- public static E4ApplicationConfig defaultConfig(String e4Xmi, String lifeCycleUri) {
- E4ApplicationConfig config = new E4ApplicationConfig(e4Xmi, lifeCycleUri, null, null, false, true, true);
- return config;
- }
-
- @Override
- public EntryPoint create() {
- EntryPoint ep = createEntryPoint();
- EntryPoint authEp = new EntryPoint() {
-
- @Override
- public int createUI() {
- Subject subject = new Subject();
- return Subject.doAs(subject, new PrivilegedAction<Integer>() {
-
- @Override
- public Integer run() {
- // SPNEGO
- // HttpServletRequest request = RWT.getRequest();
- // String authorization = request.getHeader(HEADER_AUTHORIZATION);
- // if (authorization == null || !authorization.startsWith("Negotiate")) {
- // HttpServletResponse response = RWT.getResponse();
- // response.setStatus(401);
- // response.setHeader(HEADER_WWW_AUTHENTICATE, "Negotiate");
- // response.setDateHeader("Date", System.currentTimeMillis());
- // response.setDateHeader("Expires", System.currentTimeMillis() + (24 * 60 * 60
- // * 1000));
- // response.setHeader("Accept-Ranges", "bytes");
- // response.setHeader("Connection", "Keep-Alive");
- // response.setHeader("Keep-Alive", "timeout=5, max=97");
- // // response.setContentType("text/html; charset=UTF-8");
- // }
-
- JavaScriptExecutor jsExecutor = RWT.getClient().getService(JavaScriptExecutor.class);
- Integer exitCode = ep.createUI();
- jsExecutor.execute("location.reload()");
- return exitCode;
- }
-
- });
- }
- };
- return authEp;
- }
-
- protected EntryPoint createEntryPoint() {
- return super.create();
- }
-}
+++ /dev/null
-package org.argeo.cms.e4.rap;
-
-import java.security.AccessController;
-import java.util.UUID;
-import java.util.concurrent.Callable;
-
-import javax.inject.Inject;
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.CmsContext;
-import org.argeo.api.cms.CmsLog;
-import org.argeo.api.cms.ux.CmsImageManager;
-import org.argeo.api.cms.ux.CmsView;
-import org.argeo.api.cms.ux.UxContext;
-import org.argeo.cms.CurrentUser;
-import org.argeo.cms.swt.CmsSwtUtils;
-import org.argeo.cms.swt.SimpleSwtUxContext;
-import org.argeo.cms.swt.acr.AcrSwtImageManager;
-import org.argeo.cms.swt.auth.CmsLoginShell;
-import org.argeo.cms.swt.dialogs.CmsFeedback;
-import org.eclipse.e4.core.services.events.IEventBroker;
-import org.eclipse.e4.ui.workbench.UIEvents;
-import org.eclipse.e4.ui.workbench.lifecycle.PostContextCreate;
-import org.eclipse.e4.ui.workbench.lifecycle.PreSave;
-import org.eclipse.rap.rwt.RWT;
-import org.eclipse.rap.rwt.client.service.BrowserNavigation;
-import org.eclipse.rap.rwt.client.service.BrowserNavigationEvent;
-import org.eclipse.rap.rwt.client.service.BrowserNavigationListener;
-import org.eclipse.swt.widgets.Display;
-import org.osgi.service.event.Event;
-import org.osgi.service.event.EventHandler;
-
-@SuppressWarnings("restriction")
-public class CmsLoginLifecycle implements CmsView {
- private final static CmsLog log = CmsLog.getLog(CmsLoginLifecycle.class);
-
- @Inject
- private CmsContext cmsContext;
-
- private UxContext uxContext;
- private CmsImageManager imageManager;
-
- private LoginContext loginContext;
- private BrowserNavigation browserNavigation;
-
- private String state = null;
- private String uid;
-
- @PostContextCreate
- boolean login(final IEventBroker eventBroker) {
- uid = UUID.randomUUID().toString();
- browserNavigation = RWT.getClient().getService(BrowserNavigation.class);
- if (browserNavigation != null)
- browserNavigation.addBrowserNavigationListener(new BrowserNavigationListener() {
- private static final long serialVersionUID = -3668136623771902865L;
-
- @Override
- public void navigated(BrowserNavigationEvent event) {
- state = event.getState();
- if (uxContext != null)// is logged in
- stateChanged();
- }
- });
-
- Subject subject = Subject.getSubject(AccessController.getContext());
- Display display = Display.getCurrent();
-// UiContext.setData(CmsView.KEY, this);
- CmsLoginShell loginShell = new CmsLoginShell(this, cmsContext);
- CmsSwtUtils.registerCmsView(loginShell.getShell(), this);
- loginShell.setSubject(subject);
- try {
- // try pre-auth
- loginContext = new LoginContext(CmsAuth.LOGIN_CONTEXT_USER, subject, loginShell);
- loginContext.login();
- } catch (LoginException e) {
- loginShell.createUi();
- loginShell.open();
-
- while (!loginShell.getShell().isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
- if (CurrentUser.getUsername(getSubject()) == null)
- return false;
- uxContext = new SimpleSwtUxContext();
- imageManager = (CmsImageManager) new AcrSwtImageManager();
-
- eventBroker.subscribe(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE, new EventHandler() {
- @Override
- public void handleEvent(Event event) {
- startupComplete();
- eventBroker.unsubscribe(this);
- }
- });
-
- // lcs.changeApplicationLocale(Locale.FRENCH);
- return true;
- }
-
- @PreSave
- void destroy() {
- // logout();
- }
-
- @Override
- public UxContext getUxContext() {
- return uxContext;
- }
-
- @Override
- public void navigateTo(String state) {
- browserNavigation.pushState(state, state);
- }
-
- @Override
- public void authChange(LoginContext loginContext) {
- if (loginContext == null)
- throw new IllegalArgumentException("Login context cannot be null");
- // logout previous login context
- // if (this.loginContext != null)
- // try {
- // this.loginContext.logout();
- // } catch (LoginException e1) {
- // System.err.println("Could not log out: " + e1);
- // }
- this.loginContext = loginContext;
- }
-
- @Override
- public void logout() {
- if (loginContext == null)
- throw new IllegalStateException("Login context should not be null");
- try {
- CurrentUser.logoutCmsSession(loginContext.getSubject());
- loginContext.logout();
- } catch (LoginException e) {
- throw new IllegalStateException("Cannot log out", e);
- }
- }
-
- @Override
- public void exception(Throwable e) {
- String msg = "Unexpected exception in Eclipse 4 RAP";
- log.error(msg, e);
- CmsFeedback.error(msg, e);
- }
-
- @Override
- public CmsImageManager getImageManager() {
- return imageManager;
- }
-
- protected Subject getSubject() {
- return loginContext.getSubject();
- }
-
- @Override
- public boolean isAnonymous() {
- return CurrentUser.isAnonymous(getSubject());
- }
-
- @Override
- public String getUid() {
- return uid;
- }
-
- // CALLBACKS
- protected void startupComplete() {
- }
-
- protected void stateChanged() {
-
- }
-
- // GETTERS
- protected BrowserNavigation getBrowserNavigation() {
- return browserNavigation;
- }
-
- protected String getState() {
- return state;
- }
-
- @Override
- public <T> T doAs(Callable<T> action) {
- throw new UnsupportedOperationException();
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4.rap;
-
-import java.util.Enumeration;
-
-import org.argeo.api.cms.CmsLog;
-import org.eclipse.rap.rwt.application.Application;
-import org.osgi.framework.Bundle;
-
-/** Simple RAP app which loads all e4xmi files. */
-public class SimpleRapE4App extends AbstractRapE4App {
- private final static CmsLog log = CmsLog.getLog(SimpleRapE4App.class);
-
- private String baseE4xmi = "/e4xmi";
-
- @Override
- protected void addEntryPoints(Application application) {
- Bundle bundle = getBundleContext().getBundle();
- Enumeration<String> paths = bundle.getEntryPaths(baseE4xmi);
- while (paths.hasMoreElements()) {
- String p = paths.nextElement();
- if (p.endsWith(".e4xmi")) {
- String e4xmiPath = bundle.getSymbolicName() + '/' + p;
- // FIXME deal with base name
- String name=null;// = '/' + FilenameUtils.removeExtension(FilenameUtils.getName(p));
- addE4EntryPoint(application, name, e4xmiPath, getBaseProperties());
- if (log.isDebugEnabled())
- log.debug("Registered " + e4xmiPath + " as " + getContextName() + name);
- }
- }
- }
-
-}
+++ /dev/null
-/** Eclipse 4 RAP specific extensions. */
-package org.argeo.cms.e4.rap;
\ No newline at end of file
.,\
OSGI-INF/cmsWebAppFactory.xml
source.. = src/
-additional.bundles = org.argeo.ext.slf4j,\
- org.slf4j.api
+additional.bundles = org.argeo.tp.syslogger
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-/bin/
-/target/
-/exec
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.argeo.cms.e4.rcp</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.8
+++ /dev/null
-eclipse.preferences.version=1
-pluginProject.extensions=false
-resolve.requirebundle=false
+++ /dev/null
-/MANIFEST.MF
+++ /dev/null
-<?xml version="1.0" encoding="ASCII"?>
-<application:Application xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:advanced="http://www.eclipse.org/ui/2010/UIModel/application/ui/advanced" xmlns:application="http://www.eclipse.org/ui/2010/UIModel/application" xmlns:basic="http://www.eclipse.org/ui/2010/UIModel/application/ui/basic" xmi:id="_c4iAgCnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.application">
- <children xsi:type="basic:TrimmedWindow" xmi:id="_hSGBwCnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.trimmedwindow.argeocompanion" label="Argeo Companion">
- <children xsi:type="advanced:PerspectiveStack" xmi:id="_nxzQICnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.perspectivestack.0">
- <children xsi:type="advanced:Perspective" xmi:id="_oI_oICnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.perspective.cmsadmin" label="CMS Admin">
- <children xsi:type="basic:PartSashContainer" xmi:id="_qc16ECnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.partsashcontainer.0" horizontal="true">
- <children xsi:type="basic:PartStack" xmi:id="_RE87kDsXEeiUntFYWh-hFg" elementId="org.argeo.cms.e4.rcp.partstack.1">
- <children xsi:type="basic:Part" xmi:id="_V1WvgDsXEeiUntFYWh-hFg" elementId="org.argeo.cms.e4.rcp.part.files" contributionURI="bundleclass://org.argeo.cms.jcr.e4/org.argeo.cms.e4.files.NodeFsBrowserView" label="Files"/>
- <children xsi:type="basic:Part" xmi:id="_vOqDQCnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.part.jcr" containerData="4000" contributionURI="bundleclass://org.argeo.cms.jcr.e4/org.argeo.cms.e4.jcr.JcrBrowserView" label="JCR"/>
- </children>
- <children xsi:type="basic:PartStack" xmi:id="_0eRiwCnCEei1F8sdBz8Mpw" elementId="org.argeo.cms.e4.rcp.partstack.0" containerData="6000">
- <tags>editorArea</tags>
- </children>
- </children>
- </children>
- </children>
- </children>
- <descriptors xmi:id="__9SDsC8JEeq0koquN4xGyg" elementId="org.argeo.cms.e4.partdescriptor.nodeEditor" allowMultiple="true" category="editorArea" closeable="true" contributionURI="bundleclass://org.argeo.cms.jcr.e4/org.argeo.cms.e4.jcr.JcrNodeEditor"/>
- <addons xmi:id="_c4iAgSnCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.core.commands.service" contributionURI="bundleclass://org.eclipse.e4.core.commands/org.eclipse.e4.core.commands.CommandServiceAddon"/>
- <addons xmi:id="_c4iAginCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.contexts.service" contributionURI="bundleclass://org.eclipse.e4.ui.services/org.eclipse.e4.ui.services.ContextServiceAddon"/>
- <addons xmi:id="_c4iAgynCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.bindings.service" contributionURI="bundleclass://org.eclipse.e4.ui.bindings/org.eclipse.e4.ui.bindings.BindingServiceAddon"/>
- <addons xmi:id="_c4iAhCnCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.workbench.commands.model" contributionURI="bundleclass://org.eclipse.e4.ui.workbench/org.eclipse.e4.ui.internal.workbench.addons.CommandProcessingAddon"/>
- <addons xmi:id="_c4iAhSnCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.workbench.contexts.model" contributionURI="bundleclass://org.eclipse.e4.ui.workbench/org.eclipse.e4.ui.internal.workbench.addons.ContextProcessingAddon"/>
- <addons xmi:id="_c4iAhinCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.workbench.bindings.model" contributionURI="bundleclass://org.eclipse.e4.ui.workbench.swt/org.eclipse.e4.ui.workbench.swt.util.BindingProcessingAddon"/>
- <addons xmi:id="_c4iAhynCEei1F8sdBz8Mpw" elementId="org.eclipse.e4.ui.workbench.handler.model" contributionURI="bundleclass://org.eclipse.e4.ui.workbench/org.eclipse.e4.ui.internal.workbench.addons.HandlerProcessingAddon"/>
-</application:Application>
+++ /dev/null
-argeo.osgi.start.2.node=\
-org.eclipse.equinox.http.servlet,\
-org.eclipse.equinox.metatype,\
-org.eclipse.equinox.cm,\
-org.argeo.init
-
-argeo.osgi.start.3.node=\
-org.argeo.cms,\
-org.argeo.cms.jcr,\
-
-applicationXMI=org.argeo.cms.e4.rcp/argeo-companion.e4xmi
-lifeCycleURI=bundleclass://org.argeo.cms.e4.rcp/org.argeo.cms.e4.rcp.CmsRcpLifeCycle
-clearPersistedState=true
-#argeo.cms.desktop.inTray=true
-
-# Remote node:
-#argeo.node.repo.labeledUri=http://root:demo@localhost:7070/jcr/node
-
-# Logging
-log.org.argeo=DEBUG
-
-argeo.node.useradmin.uris=os:///
-eclipse.application=org.argeo.cms.e4.rcp.CmsE4Application
+++ /dev/null
-Bundle-SymbolicName: org.argeo.cms.e4.rcp;singleton=true
-
-Require-Bundle: org.eclipse.core.runtime
-
-Import-Package: !org.eclipse.core.runtime,\
-org.eclipse.swt,\
-org.eclipse.*;resolution:=optional,\
-*
+++ /dev/null
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- argeo-companion.e4xmi
-source.. = src/
+++ /dev/null
-log4j.rootLogger=WARN, development
-
-## Levels
-log4j.logger.org.argeo=DEBUG
-log4j.logger.org.argeo.jackrabbit.remote.ExtendedDispatcherServlet=WARN
-log4j.logger.org.argeo.server.webextender.TomcatDeployer=INFO
-
-#log4j.logger.org.springframework.security=DEBUG
-#log4j.logger.org.apache.commons.exec=DEBUG
-#log4j.logger.org.apache.jackrabbit.webdav=DEBUG
-#log4j.logger.org.apache.jackrabbit.remote=DEBUG
-#log4j.logger.org.apache.jackrabbit.core.observation=DEBUG
-
-log4j.logger.org.apache.catalina=INFO
-log4j.logger.org.apache.coyote=INFO
-
-log4j.logger.org.apache.directory=INFO
-log4j.logger.org.apache.directory.server=ERROR
-log4j.logger.org.apache.jackrabbit.core.query.lucene=ERROR
-
-## Appenders
-# console is set to be a ConsoleAppender.
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-
-# console uses PatternLayout.
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern= %-5p %d{ISO8601} %m - %c - [%t]%n
-
-# development appender (slow!)
-log4j.appender.development=org.apache.log4j.ConsoleAppender
-log4j.appender.development.layout=org.apache.log4j.PatternLayout
-log4j.appender.development.layout.ConversionPattern=%d{HH:mm:ss} [%16.16t] %5p %m (%F:%L) %c%n
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- id="CmsE4Application"
- name="CMS E4 Application"
- point="org.eclipse.core.runtime.applications">
- <application
- cardinality="singleton-global"
- thread="main"
- visible="true">
- <run class="org.argeo.cms.e4.rcp.CmsE4Application"></run>
- </application>
- </extension>
-</plugin>
+++ /dev/null
-package org.argeo.cms.e4.rcp;
-
-import java.security.PrivilegedExceptionAction;
-import java.util.UUID;
-import java.util.concurrent.Callable;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.argeo.api.cms.CmsAuth;
-import org.argeo.api.cms.ux.CmsImageManager;
-import org.argeo.api.cms.ux.CmsView;
-import org.argeo.api.cms.ux.UxContext;
-import org.argeo.cms.CurrentUser;
-import org.argeo.cms.swt.CmsSwtUtils;
-import org.argeo.cms.swt.SimpleSwtUxContext;
-import org.argeo.cms.swt.auth.CmsLoginShell;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtension;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-import org.eclipse.swt.widgets.Display;
-
-public class CmsE4Application implements IApplication, CmsView {
- private LoginContext loginContext;
- private IApplication e4Application;
- private UxContext uxContext;
- private String uid;
-
- @Override
- public Object start(IApplicationContext context) throws Exception {
- // TODO wait for CMS to be ready
- Thread.sleep(5000);
-
- uid = UUID.randomUUID().toString();
- Subject subject = new Subject();
- Display display = createDisplay();
- CmsLoginShell loginShell = new CmsLoginShell(this, null);
- // TODO customize CmsLoginShell to be smaller and centered
- loginShell.setSubject(subject);
- try {
- // try pre-auth
- loginContext = new LoginContext(CmsAuth.LOGIN_CONTEXT_SINGLE_USER, subject, loginShell);
- loginContext.login();
- } catch (LoginException e) {
- e.printStackTrace();
- loginShell.createUi();
- loginShell.open();
-
- while (!loginShell.getShell().isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
- if (CurrentUser.getUsername(getSubject()) == null)
- throw new IllegalStateException("Cannot log in");
-
- // try {
- // CallbackHandler callbackHandler = new DefaultLoginDialog(
- // display.getActiveShell());
- // loginContext = new LoginContext(
- // NodeConstants.LOGIN_CONTEXT_SINGLE_USER, subject,
- // callbackHandler);
- // } catch (LoginException e1) {
- // throw new CmsException("Cannot initialize login context", e1);
- // }
- //
- // // login
- // try {
- // loginContext.login();
- // subject = loginContext.getSubject();
- // } catch (LoginException e) {
- // e.printStackTrace();
- // display.dispose();
- // try {
- // Thread.sleep(2000);
- // } catch (InterruptedException e1) {
- // // silent
- // }
- // return null;
- // }
-
- uxContext = new SimpleSwtUxContext();
- // UiContext.setData(CmsView.KEY, this);
- CmsSwtUtils.registerCmsView(loginShell.getShell(), this);
- e4Application = getApplication(null);
- Object res = Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
-
- @Override
- public Object run() throws Exception {
- return e4Application.start(context);
- }
-
- });
- return res;
- }
-
- @Override
- public void stop() {
- if (e4Application != null)
- e4Application.stop();
- }
-
- static IApplication getApplication(String[] args) {
- IExtension extension = Platform.getExtensionRegistry().getExtension(Platform.PI_RUNTIME,
- Platform.PT_APPLICATIONS, "org.eclipse.e4.ui.workbench.swt.E4Application");
- try {
- IConfigurationElement[] elements = extension.getConfigurationElements();
- if (elements.length > 0) {
- IConfigurationElement[] runs = elements[0].getChildren("run");
- if (runs.length > 0) {
- Object runnable;
- runnable = runs[0].createExecutableExtension("class");
- if (runnable instanceof IApplication)
- return (IApplication) runnable;
- }
- }
- } catch (Exception e) {
- throw new IllegalStateException("Cannot find e4 application", e);
- }
- throw new IllegalStateException("Cannot find e4 application");
- }
-
- public static Display createDisplay() {
- Display.setAppName("Argeo CMS RCP");
-
- // create the display
- Display newDisplay = Display.getCurrent();
- if (newDisplay == null) {
- newDisplay = new Display();
- }
- // Set the priority higher than normal so as to be higher
- // than the JobManager.
- Thread.currentThread().setPriority(Math.min(Thread.MAX_PRIORITY, Thread.NORM_PRIORITY + 1));
- return newDisplay;
- }
-
- //
- // CMS VIEW
- //
-
- @Override
- public UxContext getUxContext() {
- return uxContext;
- }
-
- @Override
- public void navigateTo(String state) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void authChange(LoginContext loginContext) {
- if (loginContext == null)
- throw new IllegalStateException("Login context cannot be null");
- // logout previous login context
- // if (this.loginContext != null)
- // try {
- // this.loginContext.logout();
- // } catch (LoginException e1) {
- // System.err.println("Could not log out: " + e1);
- // }
- this.loginContext = loginContext;
- }
-
- @Override
- public void logout() {
- if (loginContext == null)
- throw new IllegalStateException("Login context should not bet null");
- try {
- CurrentUser.logoutCmsSession(loginContext.getSubject());
- loginContext.logout();
- } catch (LoginException e) {
- throw new IllegalStateException("Cannot log out", e);
- }
- }
-
- @Override
- public void exception(Throwable e) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public CmsImageManager getImageManager() {
- // TODO Auto-generated method stub
- return null;
- }
-
- protected Subject getSubject() {
- return loginContext.getSubject();
- }
-
- @Override
- public boolean isAnonymous() {
- return CurrentUser.isAnonymous(getSubject());
- }
-
- @Override
- public String getUid() {
- return uid;
- }
-
- @Override
- public <T> T doAs(Callable<T> action) {
- throw new UnsupportedOperationException();
- }
-
-}
+++ /dev/null
-package org.argeo.cms.e4.rcp;
-
-import org.eclipse.e4.core.contexts.IEclipseContext;
-import org.eclipse.e4.ui.workbench.lifecycle.PostContextCreate;
-import org.eclipse.e4.ui.workbench.lifecycle.PreSave;
-import org.eclipse.e4.ui.workbench.lifecycle.ProcessAdditions;
-import org.eclipse.e4.ui.workbench.lifecycle.ProcessRemovals;
-
-@SuppressWarnings("restriction")
-public class CmsRcpLifeCycle {
-
- @PostContextCreate
- void postContextCreate(IEclipseContext workbenchContext) {
- }
-
- @PreSave
- void preSave(IEclipseContext workbenchContext) {
- }
-
- @ProcessAdditions
- void processAdditions(IEclipseContext workbenchContext) {
- }
-
- @ProcessRemovals
- void processRemovals(IEclipseContext workbenchContext) {
- }
-}
OSGI-INF/,\
OSGI-INF/cmsRcpHttpLauncher.xml,\
OSGI-INF/cmsRcpDBusLauncher.xml
-additional.bundles = org.slf4j.api
+additional.bundles = org.argeo.tp.syslogger
source.. = src/
output.. = bin/