From 273e1a864701be38b4df27179dbe7455b51ff512 Mon Sep 17 00:00:00 2001 From: Robert Vokac Date: Sat, 18 Mar 2023 11:13:51 +0100 Subject: [PATCH] Released: power-framework 1.0.0 --- CREDITS | 16 + LICENSE | 502 +++++++ README.md | 7 + pom.xml | 73 + .../powerframework/PowerRuntimeException.java | 39 + .../collections/Dictionary.java | 214 +++ .../collections/DictionaryKeyIterator.java | 87 ++ .../collections/DictionaryNode.java | 63 + .../powerframework/collections/Queue.java | 107 ++ .../powerframework/collections/Stack.java | 141 ++ .../powerframework/database/Database.java | 127 ++ .../database/DatabaseConnection.java | 351 +++++ .../database/ResultOfSqlQuery.java | 172 +++ .../database/SqlCommandQueue.java | 56 + .../powerframework/datetime/DateTime.java | 189 +++ .../datetime/DateUnitsValidator.java | 158 +++ .../powerframework/datetime/Duration.java | 626 +++++++++ .../powerframework/datetime/LocalDate.java | 132 ++ .../datetime/LocalDateTime.java | 112 ++ .../powerframework/datetime/LocalTime.java | 115 ++ .../powerframework/datetime/TimeSource.java | 104 ++ .../datetime/TimeUnitsValidator.java | 118 ++ .../powerframework/datetime/TimeZone.java | 92 ++ .../datetime/UniversalDateTime.java | 131 ++ .../datetime/ZonedDateTime.java | 160 +++ .../powerframework/datetime/package-info.java | 4 + .../powerframework/json/JsonArray.java | 424 ++++++ .../powerframework/json/JsonArrayParser.java | 88 ++ .../powerframework/json/JsonArrayPrinter.java | 98 ++ .../powerframework/json/JsonBoolean.java | 48 + .../powerframework/json/JsonChar.java | 48 + .../powerframework/json/JsonDouble.java | 44 + .../powerframework/json/JsonFloat.java | 44 + .../nanoboot/powerframework/json/JsonInt.java | 45 + .../powerframework/json/JsonLong.java | 44 + .../powerframework/json/JsonObject.java | 540 ++++++++ .../powerframework/json/JsonObjectParser.java | 110 ++ .../json/JsonObjectPrinter.java | 108 ++ .../powerframework/json/JsonParser.java | 176 +++ .../powerframework/json/JsonPrinter.java | 47 + .../json/JsonSpecialCharSequences.java | 99 ++ .../powerframework/json/JsonString.java | 48 + .../powerframework/json/JsonValue.java | 290 ++++ .../powerframework/json/JsonValueType.java | 71 + .../json/SerializableToJsonObject.java | 30 + .../nanoboot/powerframework/package-info.java | 5 + .../pseudorandom/PseudoRandomGenerator.java | 131 ++ .../powerframework/pseudorandom/Seed.java | 48 + .../powerframework/simplicity/EnumColour.java | 176 +++ .../simplicity/JavaFXApplication.java | 47 + .../powerframework/simplicity/Screen.java | 146 ++ .../powerframework/simplicity/Simplicity.java | 110 ++ .../simplicity/SimplicityRunnerI.java | 36 + .../simplicity/boxes/AlertBox.java | 70 + .../powerframework/simplicity/boxes/Box.java | 105 ++ .../simplicity/boxes/MessageBox.java | 70 + .../simplicity/window/CellLayout.java | 189 +++ .../simplicity/window/ColourVariant.java | 39 + .../simplicity/window/MoveableArea.java | 104 ++ .../simplicity/window/ResizingGrid.java | 54 + .../window/ResizingGridRectangle.java | 41 + .../simplicity/window/SLayout.java | 89 ++ .../simplicity/window/TitleBar.java | 192 +++ .../simplicity/window/TitleIcon.java | 63 + .../simplicity/window/Window.java | 417 ++++++ .../simplicity/window/WindowColourSkin.java | 188 +++ .../simplicity/window/WindowSizeMode.java | 45 + .../simplicity/window/controls/Button.java | 75 + .../window/controls/NumericMinusPlus.java | 30 + .../window/controls/PasswordField.java | 41 + .../window/controls/RadioButton.java | 46 + .../window/controls/RadioButtonGroup.java | 29 + .../simplicity/window/controls/SCheckBox.java | 133 ++ .../simplicity/window/controls/SComboBox.java | 50 + .../simplicity/window/controls/SLabel.java | 63 + .../simplicity/window/controls/TabPane.java | 32 + .../simplicity/window/controls/TextField.java | 61 + .../window/titlebuttons/CloseButton.java | 68 + .../titlebuttons/LineInWindowTitleButton.java | 43 + .../titlebuttons/MaximizeRestoreButton.java | 107 ++ .../window/titlebuttons/MinimizeButton.java | 64 + .../titlebuttons/WindowTitleButton.java | 89 ++ .../powerframework/utilities/.gitkeep | 0 src/main/resources/.gitkeep | 0 .../DictionaryKeyIteratorTest.java | 205 +++ .../collections/DictionaryNodeTest.java | 137 ++ .../collections/DictionaryTest.java | 381 ++++++ .../powerframework/collections/QueueTest.java | 292 ++++ .../powerframework/collections/StackTest.java | 340 +++++ .../database/DatabaseConnectionTest.java | 228 ++++ .../powerframework/database/DatabaseTest.java | 211 +++ .../database/ResultOfSqlQueryTest.java | 315 +++++ .../database/SqlCommandQueueTest.java | 119 ++ .../powerframework/datetime/DateTimeTest.java | 342 +++++ .../datetime/DateUnitsValidatorTest.java | 218 +++ .../powerframework/datetime/DurationTest.java | 878 ++++++++++++ .../datetime/LocalDateTest.java | 435 ++++++ .../datetime/LocalDateTimeTest.java | 166 +++ .../datetime/LocalTimeTest.java | 290 ++++ .../datetime/TimeUnitsValidatorTest.java | 288 ++++ .../powerframework/datetime/TimeZoneTest.java | 129 ++ .../datetime/UniversalDateTimeTest.java | 148 ++ .../datetime/ZonedDateTimeTest.java | 157 +++ .../powerframework/json/JsonArrayTest.java | 796 +++++++++++ .../powerframework/json/JsonObjectTest.java | 1214 +++++++++++++++++ .../powerframework/json/JsonValueTest.java | 432 ++++++ .../PseudoRandomGeneratorTest.java | 125 ++ .../powerframework/pseudorandom/SeedTest.java | 71 + 108 files changed, 17511 insertions(+) create mode 100644 CREDITS create mode 100755 LICENSE create mode 100644 README.md create mode 100644 pom.xml create mode 100644 src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java create mode 100644 src/main/java/org/nanoboot/powerframework/collections/Dictionary.java create mode 100644 src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java create mode 100644 src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java create mode 100644 src/main/java/org/nanoboot/powerframework/collections/Queue.java create mode 100644 src/main/java/org/nanoboot/powerframework/collections/Stack.java create mode 100644 src/main/java/org/nanoboot/powerframework/database/Database.java create mode 100644 src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java create mode 100644 src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java create mode 100644 src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/DateTime.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/Duration.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java create mode 100644 src/main/java/org/nanoboot/powerframework/datetime/package-info.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonArray.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonChar.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonDouble.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonFloat.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonInt.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonLong.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonObject.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonParser.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonString.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonValue.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/JsonValueType.java create mode 100644 src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java create mode 100644 src/main/java/org/nanoboot/powerframework/package-info.java create mode 100644 src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java create mode 100644 src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/Screen.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java create mode 100644 src/main/java/org/nanoboot/powerframework/utilities/.gitkeep create mode 100644 src/main/resources/.gitkeep create mode 100644 src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/collections/QueueTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/collections/StackTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java create mode 100644 src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java diff --git a/CREDITS b/CREDITS new file mode 100644 index 0000000..73773aa --- /dev/null +++ b/CREDITS @@ -0,0 +1,16 @@ + This file partially lists people, that have contributed to + the "Power Framework" project. They are sorted by name. + The fields are: name (N), e-mail (E), web-address (W), + PGP key ID and fingerprint (P), description (D) and + snail-mail address (S). + Thanks, + + Vokac +---------- + +N: Robert Vokac +E: robertvokac@nanoboot.org +W: https://nanoboot.org +P: 4096R/E3329055 322B D109 0AA8 C324 EA9C 72F5 693D 30BE E332 9055 +D: Founder +S: Czech Republic diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..4362b49 --- /dev/null +++ b/LICENSE @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + 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 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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. + + 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 + + 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. + + + Copyright (C) + + 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. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/README.md b/README.md new file mode 100644 index 0000000..0a849e2 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +# power-framework + +## Requirements + * Maven + * Java 8 (for example: Amazon Corretto 8 - https://docs.aws.amazon.com/corretto/latest/corretto-8-ug/downloads-list.html) + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..7aa605e --- /dev/null +++ b/pom.xml @@ -0,0 +1,73 @@ + + + + 4.0.0 + + org.nanoboot.powerframework + power-framework + 1.0.0 + jar + + Power Framework + A library with many possibilities + + + UTF-8 + true + 8 + + + + + + + + junit + junit + 4.12 + test + + + org.xerial + sqlite-jdbc + 3.39.3.0 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${javase.version} + ${javase.version} + + + + + diff --git a/src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java b/src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java new file mode 100644 index 0000000..d18127f --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework; + +/** + * Exception for Power library + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class PowerRuntimeException extends RuntimeException { + + /** + * Constructor with message. + * + * @param message + */ + public PowerRuntimeException(String message) { + super(message); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java b/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java new file mode 100644 index 0000000..561a2c0 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java @@ -0,0 +1,214 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents dictionary data structure. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @param + */ +public class Dictionary { + + private int countOfItems = 0; + + private DictionaryNode currentNode = null; + private DictionaryNode stopNode = null; + + private DictionaryNode firstNode = null; + private DictionaryNode lastNode = null; + + private DictionaryNode tempNode = null; + private DictionaryNode previousTempNode = null; + + /** + * + * @return size of this dictionary + */ + public int getCountOfItems() { + return countOfItems; + } + + /** + * + * @return result of this control + */ + public boolean isEmpty() { + return getCountOfItems() == 0; + } + + /** + * + * @param key + * @return result of this control + */ + public boolean containsValueWithKey(String key) { + DictionaryKeyIterator dictionaryKeyIterator = this.getKeyIterator(); + boolean result = false; + while (dictionaryKeyIterator.hasNext()) { + if (dictionaryKeyIterator.getNextKey().equals(key)) { + result = true; + } + } + + return result; + } + + /** + * Add new dictionary entry. + * + * @param key + * @param value + * @return + */ + public Dictionary addValue(String key, T value) { + + DictionaryNode nodeToAdd = new DictionaryNode<>(key, value); + tempNode = lastNode; + lastNode = nodeToAdd; + if (isEmpty()) { + firstNode = nodeToAdd; + } else { + tempNode.setNext(lastNode); + } + countOfItems++; + return this; + } + + /** + * Return a dictionary entry with the given key. + * + * @param key + * @return + */ + public T getValue(String key) { + moveCurrentNodeToTheNodeWithTheKey(key); + + return currentNode.getElement(); + + } + + private void moveCurrentNodeToTheNodeWithTheKey(String key) { + stopNode = stopNode == null ? firstNode : stopNode; + currentNode = stopNode; + + while (!currentNodeIsAtTheEnd(key)) { + + if (currentNode.getNext() == null) { + currentNode = firstNode; + } else { + currentNode = currentNode.getNext(); + } + } + this.stopNode = currentNode; + + if (!currentNodeHasTheKey(key)) { + throw new PowerRuntimeException("There is no element with key: " + key); + } + } + + private boolean currentNodeIsAtTheEnd(String key) { + return (currentNodeHasTheKey(key)) || (currentNodeIsBeforeStopNode()); + } + + private boolean currentNodeHasTheKey(String key) { + return currentNode.getKey().equals(key); + } + + private boolean currentNodeIsBeforeStopNode() { + if ((currentNode == lastNode) && (stopNode == firstNode)) { + return true; + } + return currentNode.getNext() == stopNode; + } + + /** + * Updates the dictionary entry with the given key to the given value. + * + * @param key + * @param value + */ + public void updateValue(String key, T value) { + moveCurrentNodeToTheNodeWithTheKey(key); + currentNode.setElement(value); + } + + /** + * Removes the dictionary entry with the given key. + * + * @param key + * @return dictionary + */ + public Dictionary removeValue(String key) { + if (isEmpty()) { + throw new PowerRuntimeException("This dictionary is empty. No dictionary entry can be removed."); + } + tempNode = firstNode; + while ((!(tempNode.getKey().equals(key))) && (tempNode.getNext() != null)) { + this.previousTempNode = tempNode; + tempNode = tempNode.getNext(); + } + if (!(tempNode.getKey().equals(key))) { + throw new PowerRuntimeException("There is no key: " + key); + } else if (tempNode == firstNode) { + firstNode = firstNode.getNext(); + } else if (tempNode == lastNode) { + lastNode = previousTempNode; + lastNode.setNext(null); + } else { + this.previousTempNode.setNext(tempNode.getNext()); + } + countOfItems--; + return this; + } + + /** + * + * @return KeyIterator for this dictionary + */ + public DictionaryKeyIterator getKeyIterator() { + return new DictionaryKeyIterator(firstNode); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + DictionaryKeyIterator dictionaryKeyIterator = this.getKeyIterator(); + String key; + T value; + String valueAsString; + final char colon = ':'; + final String newLine = "\n"; + + while (dictionaryKeyIterator.hasNext()) { + key = dictionaryKeyIterator.getNextKey(); + value = this.getValue(key); + valueAsString = value.toString(); + stringBuilder.append(key); + stringBuilder.append(colon); + stringBuilder.append(valueAsString); + stringBuilder.append(newLine); + } + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java b/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java new file mode 100644 index 0000000..3db1ac3 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java @@ -0,0 +1,87 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Is used to iterate entries through dictionary. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DictionaryKeyIterator { + + private final DictionaryNode firstNode; + private DictionaryNode currentNode; + private boolean currentNodeIsNotFirst = false; + + DictionaryKeyIterator(DictionaryNode value) { + this.firstNode = value; + this.reset(); + } + + /** + * + * @return next key + */ + public String getNextKey() { + String key; + if (firstNode == null) { + throw new PowerRuntimeException("Dictionary is empty. There is no key."); + } + if ((currentNode == firstNode) && (!this.currentNodeIsNotFirst)) { + key = currentNode.getKey(); + this.currentNodeIsNotFirst = true; + } else { + if (!hasNext()) { + throw new PowerRuntimeException("There is no next key."); + } + this.currentNode = this.currentNode.getNext(); + key = currentNode.getKey(); + } + return key; + } + + /** + * + * @return true if there is a next key, otherwise false + */ + public boolean hasNext() { + if (this.firstNode == null) { + return false; + } + if ((firstNode.getNext() == null) && (!currentNodeIsNotFirst)) { + return true; + } + if ((firstNode.getNext() == null) && (currentNodeIsNotFirst)) { + return false; + } + return this.currentNode.getNext() != null; + } + + /** + * Moves the current key to the first. + */ + public void reset() { + this.currentNode = this.firstNode; + currentNodeIsNotFirst = false; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java b/src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java new file mode 100644 index 0000000..bdb4c73 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +/** + * Represents one dictionary entry. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class DictionaryNode { + + private String key; + private T element; + private DictionaryNode next = null; + + DictionaryNode(String key, T element) { + this.key = key; + this.element = element; + } + + T getElement() { + return element; + } + + void setElement(T element) { + this.element = element; + } + + DictionaryNode getNext() { + return next; + } + + void setNext(DictionaryNode next) { + this.next = next; + } + + String getKey() { + return key; + } + + void setKey(String key) { + this.key = key; + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/Queue.java b/src/main/java/org/nanoboot/powerframework/collections/Queue.java new file mode 100644 index 0000000..4d0de9f --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/collections/Queue.java @@ -0,0 +1,107 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents Queue- linear data structure. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @param object + */ +public class Queue { + + private int total; + + private Node first; + private Node last; + + private class Node { + + private T element; + private Node next; + } + + /** + * + * @return size of this queue + */ + public int getCountOfItems() { + return this.total; + } + + /** + * + * @return true if this queue is empty, otherwise false + */ + public boolean isEmpty() { + return this.getCountOfItems() == 0; + } + + /** + * Enqueues new element. + * + * @param element + * @return new element + */ + public Queue enqueue(T element) { + Node current = last; + last = new Node(); + last.element = element; + + if (total++ == 0) { + first = last; + } else { + current.next = last; + } + + return this; + } + + /** + * Dequeues element. + * + * @return removed element + */ + public T dequeue() { + if (total == 0) { + throw new PowerRuntimeException("No such element"); + } + T ele = first.element; + first = first.next; + if (--total == 0) { + last = null; + } + return ele; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + Node tmp = first; + while (tmp != null) { + sb.append(tmp.element).append(", "); + tmp = tmp.next; + } + return sb.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/Stack.java b/src/main/java/org/nanoboot/powerframework/collections/Stack.java new file mode 100644 index 0000000..bdfce77 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/collections/Stack.java @@ -0,0 +1,141 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents Stack- linear data structure. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @param object + */ +public class Stack implements Iterable { + + private int total = 0; + + private Node first; + + @Override + public Iterator iterator() { + return new StackIterator(); + } + + private class Node { + + private T element; + private Node next; + } + + private class StackIterator implements Iterator { + + @Override + public boolean hasNext() { + return !isEmpty(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return pop(); + } + } + + /** + * + * @return size of this stack + */ + public int getCountOfItems() { + return this.total; + } + + /** + * + * @return true if this stack is empty, otherwise false + */ + public boolean isEmpty() { + return this.getCountOfItems() == 0; + } + + /** + * Pushes new element. + * + * @param element + * @return pushed element + */ + public Stack push(T element) { + Node current = first; + first = new Node(); + first.element = element; + first.next = current; + total++; + return this; + } + + /** + * Pops element. + * + * @return popped element + */ + public T pop() { + if (first == null) { + throw new PowerRuntimeException("No such element"); + } + T element = first.element; + first = first.next; + total--; + return element; + } + + /** + * + * @return the top element of this stack without removing this element + */ + public T peek() { + if (first == null) { + throw new PowerRuntimeException("No such element"); + } + return first.element; + } +/** + * Deletes all items of this stack. + */ + public void clear() { + total = 0; + first = null; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + Node tmp = first; + while (tmp != null) { + sb.append(tmp.element).append(", "); + tmp = tmp.next; + } + return sb.toString(); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/database/Database.java b/src/main/java/org/nanoboot/powerframework/database/Database.java new file mode 100644 index 0000000..88654ff --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/database/Database.java @@ -0,0 +1,127 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Manipulates with database. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class Database { + + private static final String SQLITEEXTENSION = ".sqlite"; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Database() { + //Not meant to be instantiated. + } + + /** + * Creates new database with the given name. + * + * @param databaseName + */ + public static void createDatabase(String databaseName) { + if (existsDatabase(databaseName)) { + throw new PowerRuntimeException("A database with the given name already exists."); + } + Connection connection = null; + try { + Class.forName("org.sqlite.JDBC"); + connection = DriverManager.getConnection("jdbc:sqlite:" + convertDatabaseNameToFileName(databaseName)); + } catch (Exception e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + throw new PowerRuntimeException("New database was not created."); + } finally { + if (connection != null) { + try { + connection.close(); + } catch (SQLException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + } + + /** + * Deletes forever the database with the given name. + * + * @param databaseName + */ + public static void dropDatabase(String databaseName) { + if (!existsDatabase(databaseName)) { + throw new PowerRuntimeException("There is no database with the given name."); + } + File file = new File("./" + convertDatabaseNameToFileName(databaseName)); + boolean delete = file.delete(); + if (!delete) { + throw new PowerRuntimeException("The database was not dropped."); + } + } + + /** + * @param databaseName + * @return true, if a database with the name exists, otherwise false. + */ + public static boolean existsDatabase(String databaseName) { + File file = new File("./" + convertDatabaseNameToFileName(databaseName)); + return (file.exists()) && !(file.isDirectory()); + } + + /** + * Creates a database connection for the database with the given name. + * + * @param databaseName + * @return database connection to the database with the given name + */ + public static DatabaseConnection createDatabaseConnection(String databaseName) { + if ((databaseName != "") && (!existsDatabase(databaseName))) { + throw new PowerRuntimeException("There is no database with the given name."); + } + return new DatabaseConnection(databaseName); + } + + /** + * Creates a new in memory database and return its connection + * + * @return database connection + */ + public static DatabaseConnection createInMemoryDatabaseConnection() { + return createDatabaseConnection(""); + } + + private static String convertDatabaseNameToFileName(String databaseName) { + return databaseName + SQLITEEXTENSION; + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java b/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java new file mode 100644 index 0000000..f67e4bc --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java @@ -0,0 +1,351 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.json.*; + +/** + * Represents connection to a database. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DatabaseConnection { + + private Connection connection = null; + private Statement statement = null; + private final String databaseName; + + private final String jdbcUrl; + + DatabaseConnection(String databaseName) { + this.databaseName = databaseName; + StringBuilder stringBuilder = new StringBuilder().append("jdbc:sqlite:"); + if (databaseName != "") { + stringBuilder.append(databaseName).append(".sqlite").toString(); + } + this.jdbcUrl = stringBuilder.toString(); + } + + /** + * + * @return name of the database of this database connection + */ + public String getDatabaseName() { + return databaseName; + } + + private void setConnection() { + try { + Class.forName("org.sqlite.JDBC"); + connection = DriverManager.getConnection(jdbcUrl); + statement = connection.createStatement(); + statement.execute("PRAGMA foreign_keys = ON;"); + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } + } + + /** + * Executes sql command, which returns no result. + * + * @param command + * @return last inserted row id + */ + public int execute(String command) { + int lastInsertedRowId = 0; + setConnection(); + ResultSet resultSet = null; + try { + statement.executeUpdate(command); + resultSet = statement.executeQuery("SELECT last_insert_rowid() AS LASTINSERTEDROWID;"); + resultSet.next(); + lastInsertedRowId = resultSet.getInt(1); + resultSet.close(); + connection.close(); + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } finally { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException ex) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); + } + } + + } + return lastInsertedRowId; + } + + /** + * Executes sql commands from the command queue. + * + * @param commandQueue + */ + public void executeMoreCommands(SqlCommandQueue commandQueue) { + setConnection(); + + try { + connection.setAutoCommit(false); + while (commandQueue.isThereANextCommand()) { + String command = commandQueue.loadNextCommand(); + statement.executeUpdate(command); + + } + + //No changes has been made in the database yet, so now we will commit + //the changes. + connection.commit(); + } catch (SQLException ex) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); + try { + //An error occured so we rollback the changes. + connection.rollback(); + } catch (SQLException ex1) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex1); + throw new PowerRuntimeException("Fatal error happened. I was not able to rollback"); + } + } finally { + try { + if (statement != null) { + statement.close(); + connection.close(); + } + } catch (SQLException ex) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + /** + * Executes sql commands from the given String, which is split by ; + * character. + * + * @param commands + */ + public void executeMoreCommands(String commands) { + SqlCommandQueue commandQueue = new SqlCommandQueue(); + String[] commandsArray = commands.split(";"); + for (String part : commandsArray) { + commandQueue.add(part); + } + this.executeMoreCommands(commandQueue); + } + + /** + * Executes sql command, which returns result. + * + * @param command + * @return + */ + public ResultOfSqlQuery executeAndReturn(String command) { + JsonObject table = new JsonObject(); + + JsonArray columns = new JsonArray(); + JsonArray rows = new JsonArray(); + + table.addString("query", command); + table.addArray("columns", columns); + table.addArray("rows", rows); + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rsmd.getColumnName(i); + columns.addString(columnName); + } + + while (resultSet.next()) { + JsonArray row = new JsonArray(); + for (int i = 0; i < columns.getCountOfItems(); i++) { + String columnName = columns.getString(i); + String value = resultSet.getString(columnName); + row.addString(value); + } + rows.addArray(row); + } + + connection.close(); + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } finally { + closeConnectionAndResultSet(resultSet); + } + return new ResultOfSqlQuery(table); + } + + private void closeConnectionAndResultSet(ResultSet resultSet) { + try { + if (resultSet != null) { + resultSet.close(); + } + if (!connection.isClosed()) { + connection.close(); + } + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } + } + + /** + * Updates value. + * + * @param tableName + * @param id + * @param columnName + * @param newValue + */ + public void updateValue(String tableName, int id, String columnName, String newValue) { + String string + = "UPDATE " + tableName + " SET " + columnName + " = '" + newValue + "' WHERE ID = " + id; + this.execute(string); + } + + /** + * Updates value. + * + * @param tableName + * @param id + * @param columnName + * @param newValue + */ + public void updateValue(String tableName, int id, String columnName, int newValue) { + String string + = "UPDATE " + tableName + " SET " + columnName + " = " + newValue + " WHERE ID = " + id; + this.execute(string); + } + + /** + * + * @param tableName + * @param id + * @return row with the given id from the given table as a json object + */ + public JsonObject getRow(String tableName, int id) { + JsonObject row = new JsonObject(); + + JsonArray columns = new JsonArray(); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("select * from "); + stringBuilder.append(tableName); + stringBuilder.append(" where id="); + stringBuilder.append(id); + + String command = stringBuilder.toString(); + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rsmd.getColumnName(i); + columns.addString(columnName); + } + + if (!resultSet.next()) { + throw new PowerRuntimeException("There is no row with id " + id + " in table " + tableName); + } + + for (int i = 0; i < columns.getCountOfItems(); i++) { + String columnName = columns.getString(i); + String value = resultSet.getString(columnName); + row.addString(columnName, value); + } + + connection.close(); + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + throw new IllegalStateException(); + } finally { + + try { + if (resultSet != null) { + resultSet.close(); + } + if (!connection.isClosed()) { + connection.close(); + } + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } + } + return row; + } + + /** + * + * @param tableName + * @return true, if the table is empty, otherwise false. + */ + public boolean isTableEmpty(String tableName) { + ResultOfSqlQuery resultOfSqlQuery = this.executeAndReturn("SELECT * FROM " + tableName); + return resultOfSqlQuery.isEmpty(); + } + + /** + * + * @param table table name + * @param column column name + * @param whereClause for example: year_of_birth>1995 + * @return String value from a table and first row + */ + public String getString(String table, String column, String whereClause) { + String command = "SELECT " + column + " FROM " + table + " WHERE " + whereClause; + String value = null; + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + + if (resultSet.next()) { + value = resultSet.getString(column); + } + connection.close(); + } catch (Exception e) { + Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); + } finally { + + closeConnectionAndResultSet(resultSet); + + } + + return value; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java b/src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java new file mode 100644 index 0000000..254de5a --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java @@ -0,0 +1,172 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.collections.Dictionary; +import org.nanoboot.powerframework.json.*; + +/** + * Represents the result of a sql query. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class ResultOfSqlQuery { + + private final JsonObject table; + private final JsonArray columns; + private final JsonArray rows; + private int currentRowIndex = -1; + private final Dictionary dictionaryOfColumnNamesIndexes = new Dictionary(); + + ResultOfSqlQuery(JsonObject jsonObject) { + this.table = jsonObject; + this.columns = table.getArray("columns"); + this.rows = table.getArray("rows"); + fillDictionaryOfColumnNamesIndexes(); + } + + private void fillDictionaryOfColumnNamesIndexes() { + for (int i = 0; i < columns.getCountOfItems(); i++) { + String currentColumnName = columns.getString(i); + dictionaryOfColumnNamesIndexes.addValue(currentColumnName, i); + } + } + + /** + * + * @return column names as json array + */ + public JsonArray getColumnNames() { + return columns.getCopy(); + } + + /** + * + * @return rows as json array + */ + public JsonArray getRows() { + return rows.getCopy(); + } + + /** + * + * @return count of rows + */ + public int getCountOfRows() { + return rows.getCountOfItems(); + } + + /** + * + * @return true, if this result has no row, otherwise false. + */ + public boolean isEmpty() { + return this.rows.isEmpty(); + } + + /** + * Resets the position of the current row to the first. + */ + public void resetPositionBeforeFirstRow() { + this.currentRowIndex = -1; + } + + /** + * + * @return true, if there is a row after the current row, otherwise false. + */ + public boolean hasNextRow() { + return currentRowIndex + 1 < this.rows.getCountOfItems(); + } + + /** + * Moves the position of the current Row to the next + */ + public void moveToTheNextRow() { + currentRowIndex++; + } + + private JsonArray getCurrentRow() { + if (currentRowIndex == -1) { + throw new PowerRuntimeException("The position of the current row is before the first row"); + } + return rows.getArray(currentRowIndex); + } + + /** + * + * @return current row as json array + */ + public JsonArray getRow() { + return rows.getArray(currentRowIndex).getCopy(); + } + + private int getIndexForTheColumn(String columnName) { + return this.dictionaryOfColumnNamesIndexes.getValue(columnName); + } + + /** + * + * @param columnName + * @return the value of the column of the current row as int + */ + public int getInt(String columnName) { + int columnIndex = getIndexForTheColumn(columnName); + return Integer.parseInt(getCurrentRow().getString(columnIndex)); + } + + /** + * + * @param columnName + * @return the value of the column of the current row as double + */ + public double getDouble(String columnName) { + int columnIndex = getIndexForTheColumn(columnName); + return Double.parseDouble(getCurrentRow().getString(columnIndex)); + } + + /** + * + * @param columnName + * @return the value of the column of the current row as String + */ + public String getString(String columnName) { + int columnIndex = getIndexForTheColumn(columnName); + return getCurrentRow().getString(columnIndex); + } + + /** + * + * @return query, which was executed and returned this result + */ + public String getQuery() { + return this.table.getString("query"); + } + + /** + * + * @return json object representation of this object + */ + public JsonObject toJsonObject() { + return this.table.getCopy(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java b/src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java new file mode 100644 index 0000000..e9e3a3d --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java @@ -0,0 +1,56 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import org.nanoboot.powerframework.collections.Queue; + +/** + * Used to execute more sql commands at once to achieve better performance. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SqlCommandQueue { + + private final Queue queue = new Queue<>(); + + /** + * Adds sql command. + * + * @param command + */ + public void add(String command) { + this.queue.enqueue(command); + } + + String loadNextCommand() { + return this.queue.dequeue(); + } + + boolean isThereANextCommand() { + return !this.queue.isEmpty(); + } + + @Override + public String toString() { + return this.queue.toString(); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java new file mode 100644 index 0000000..7f8fdff --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java @@ -0,0 +1,189 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.text.SimpleDateFormat; + +/** + * This class represents date and time and is immutable. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public abstract class DateTime { + + /** + * + */ + protected static class SimpleDateTimeFormatByTimeZone extends SimpleDateFormat { + + /** + * + * @param timeZone + * @param formatText + */ + protected SimpleDateTimeFormatByTimeZone(TimeZone timeZone, String formatText) { + super(formatText); + setTimeZone(java.util.TimeZone.getTimeZone(timeZone.toString())); + } + } + + private final LocalDate date; + private final LocalTime time; + + /** + * Constructor + * + * Sets all values. + * + * @param localDate Represents a date. + * @param localTime Represents a time. + */ + DateTime(LocalDate localDate, LocalTime localTime) { + this.date = localDate; + this.time = localTime; + } + + /** + * Constructor + * + * Sets all values. + * + * @param year Represents a year. + * @param month Represents a month. + * @param day Represents a day. + * @param hour24Format Represents an hour. + * @param minute Represents a minute + * @param second Represents a second. + * @param millisecond Represents a millisecond. + */ + DateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + this.date = new LocalDate(year, month, day); + this.time = new LocalTime(hour24Format, minute, second, millisecond); + } + + /** + * Constructor + * + * Sets all values from another object. + * + * @param dateTime + */ + protected DateTime(DateTime dateTime) { + int year = dateTime.getYear(); + int month = dateTime.getMonth(); + int day = dateTime.getDay(); + date = new LocalDate(year, month, day); + + int hour24Format = dateTime.getHour(); + int minute = dateTime.getMinute(); + int second = dateTime.getSecond(); + int millisecond = dateTime.getMillisecond(); + time = new LocalTime(hour24Format, minute, second, millisecond); + } + + /** + * Constructor + * + * Sets all values from String + * + * @param dateTimeInString This String has following format: 2016-12-31 + * 24:45:14:453 yyyy-MM-dd HH:mm:ss:SSS + */ + public DateTime(String dateTimeInString) { + int year = Integer.parseInt(dateTimeInString.substring(0, 4)); + int month = Integer.parseInt(dateTimeInString.substring(5, 7)); + int day = Integer.parseInt(dateTimeInString.substring(8, 10)); + date = new LocalDate(year, month, day); + + int hour = Integer.parseInt(dateTimeInString.substring(11, 13)); + int minute = Integer.parseInt(dateTimeInString.substring(14, 16)); + int second = Integer.parseInt(dateTimeInString.substring(17, 19)); + int millisecond = Integer.parseInt(dateTimeInString.substring(20, 23)); + time = new LocalTime(hour, minute, second, millisecond); + } + + /** + * + * @return year + */ + public int getYear() { + return this.date.getYear(); + } + + /** + * + * @return month + */ + public int getMonth() { + return this.date.getMonth(); + } + + /** + * + * @return day + */ + public int getDay() { + return this.date.getDay(); + } + + /** + * + * @return hour + */ + public int getHour() { + return this.time.getHour(); + } + + /** + * + * @return minute + */ + public int getMinute() { + return this.time.getMinute(); + } + + /** + * + * @return second + */ + public int getSecond() { + return this.time.getSecond(); + } + + /** + * + * @return millisecond + */ + public int getMillisecond() { + return this.time.getMillisecond(); + } + + @Override + public String toString() { + StringBuilder stringBuffer = new StringBuilder(); + stringBuffer.append(this.date.toString()); + stringBuffer.append(" "); + stringBuffer.append(this.time.toString()); + + return stringBuffer.toString(); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java b/src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java new file mode 100644 index 0000000..2f941d6 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java @@ -0,0 +1,158 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.util.ArrayList; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Validates date units. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class DateUnitsValidator { + + private static final int MONTHLOWERBOUND = 1; + private static final int MONTHHIGHERBOUND = 12; + private static final int DAYLOWERBOUND = 1; + private static final int DAYHIGHERBOUND = 31; + private static final int MAXIMUMDAYFORFEBRUARYANDLEAPYEAR = 29; + private static final int MAXIMUMDAYFORFEBRUARYANDNOTLEAPYEAR = 28; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private DateUnitsValidator() { + } + + /** + * Checks if month has valid format. + * + * @param month + * @return Result of this control. + */ + static boolean isMonthValid(int month) { + return (month >= MONTHLOWERBOUND) && (month <= MONTHHIGHERBOUND); + } + + /** + * Checks if day is not more than the highest possible one- 31. + * + * @param day + * @return Result of this control. + */ + static boolean isDayValid(int day) { + return (day >= DAYLOWERBOUND) && (day <= DAYHIGHERBOUND); + } + + /** + * Checks if date has valid combination. + * + * @param year + * @param month + * @param day + * + * @return true if the date combination is valid, otherwise false. + */ + static boolean hasDateValidCombination(int year, int month, int day) { + return day <= getMaximumDay(year, month); + } + + /** + * + * @param year + * @param month + * @return maximum day for the given month in the given year. + * @exception PowerRuntimeException if month is out of range and is invalid. + */ + private static int getMaximumDay(int year, int month) {//NOSONAR + if (!isMonthValid(month)) { + throw new PowerRuntimeException("Month is not valid."); + } + if (hasMonth31Days(month)) { + return 31; + } + if (hasMonth30Days(month)) { + return 30; + } + if (hasMonth29Days(year, month)) { + return MAXIMUMDAYFORFEBRUARYANDLEAPYEAR; + } + if (hasMonth28Days(year, month)) { + return MAXIMUMDAYFORFEBRUARYANDNOTLEAPYEAR; + } + throw new PowerRuntimeException(year + " " + month + " " + "I am not able to find out the maximum day for the given year and month."); + + } + + /** + * + * @param month + * @return true if the given month in the given year has 31 days, otherwise + * false. + */ + private static boolean hasMonth31Days(int month) { + ArrayList monthWithMaximumDay31 = new ArrayList<>(); + monthWithMaximumDay31.add(1); + monthWithMaximumDay31.add(3); + monthWithMaximumDay31.add(5); + monthWithMaximumDay31.add(7); + monthWithMaximumDay31.add(8); + monthWithMaximumDay31.add(10); + monthWithMaximumDay31.add(12); + return monthWithMaximumDay31.contains(month); + } + + /** + * + * @param month + * @return true if the given month in the given year has 30 days, otherwise + * false. + */ + private static boolean hasMonth30Days(int month) { + return (month == 4) || (month == 6) || (month == 9) || (month == 11); + } + + /** + * + * @param year + * @param month + * @return true if the given month in the given year has 29 days, otherwise + * false. + */ + private static boolean hasMonth29Days(int year, int month) { + return (month == 2) && (LocalDate.isYearLeap(year)); + } + + /** + * + * @param year + * @param month + * @return true if the given month in the given year has 28 days, otherwise + * false. + */ + private static boolean hasMonth28Days(int year, int month) { + return (month == 2) && (!LocalDate.isYearLeap(year)); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/Duration.java b/src/main/java/org/nanoboot/powerframework/datetime/Duration.java new file mode 100644 index 0000000..4d3e0a6 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/Duration.java @@ -0,0 +1,626 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; + +/** + * Is used to do arithmetics with Date and Time. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class Duration { + + private static final int MILLISECONDSPERSECOND = 1000; + private static final int SECONDSPERMINUTE = 60; + private static final int MILLISECONDSPERMINUTE = MILLISECONDSPERSECOND * SECONDSPERMINUTE; + private static final int MINUTESPERHOUR = 60; + private static final int MILLISECONDSPERHOUR = MILLISECONDSPERMINUTE * MINUTESPERHOUR; + private static final int HOURSPERDAY = 24; + private static final int MILLISECONDSPERDAY = MILLISECONDSPERHOUR * HOURSPERDAY; + private static final String PLUS = "+"; + private static final String MINUS = "-"; + private static final String COLON = ":"; + + private final long countOfTotalMilliseconds; + private final int days; + private final int hours; + private final int minutes; + private final int seconds; + private final int milliseconds; + private final boolean positive; + + /** + * Constructor + * + * Creates new Duration from count of milliseconds. + * + * @param countOfMilliseconds + */ + public Duration(long countOfMilliseconds) { + if (countOfMilliseconds >= 0) { + positive = true; + } else { + positive = false; + } + this.countOfTotalMilliseconds = Math.abs(countOfMilliseconds); + + this.days = (int) Math.floor(this.toTotalDays()); + this.hours = (int) Math.floor(this.toTotalHours()) - (days * HOURSPERDAY); + this.minutes = (int) Math.floor(this.toTotalMinutes()) - (days * HOURSPERDAY * MINUTESPERHOUR) - (hours * MINUTESPERHOUR); + this.seconds = (int) Math.floor(this.toTotalSeconds()) - (days * HOURSPERDAY * MINUTESPERHOUR * SECONDSPERMINUTE) - (hours * MINUTESPERHOUR * SECONDSPERMINUTE) - (minutes * SECONDSPERMINUTE); + this.milliseconds = (int) this.toTotalMilliseconds() - (days * HOURSPERDAY * MINUTESPERHOUR * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (hours * MINUTESPERHOUR * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (minutes * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (seconds * MILLISECONDSPERSECOND); + + } + + /** + * Constructor + * + * Creates new Duration from the given values. + * + * @param days + * @param hours + * @param minutes + * @param seconds + * @param milliseconds + */ + public Duration(long days, int hours, int minutes, int seconds, int milliseconds) { + this( + true, days, hours, minutes, seconds, milliseconds + ); + } + + /** + * Constructor + * + * Creates new Duration from the given values. + * + * @param positive + * @param days + * @param hours + * @param minutes + * @param seconds + * @param milliseconds + */ + public Duration(boolean positive, long days, int hours, int minutes, int seconds, int milliseconds) { + this( + (positive ? 1 : (-1)) + * (convertDaysToMilliseconds(days) + + convertHoursToMilliseconds(hours) + + convertMinutesToMilliseconds(minutes) + + convertSecondsToMilliseconds(seconds) + + milliseconds) + ); + TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hours, minutes, seconds, milliseconds); + } + + /** + * Constructor + * + * Creates new Duration from the String. + * + * @param string + */ + public Duration(String string) { + String[] splitString = string.split("\\:+"); + if (splitString.length != 5) { + throw new PowerRuntimeException("Input String has wrong format."); + } + try { + this.days = Integer.parseInt(splitString[0]); + this.hours = Integer.parseInt(splitString[1]); + this.minutes = Integer.parseInt(splitString[2]); + this.seconds = Integer.parseInt(splitString[3]); + this.milliseconds = Integer.parseInt(splitString[4]); + this.countOfTotalMilliseconds = convertDaysToMilliseconds(days) + + convertHoursToMilliseconds(hours) + + convertMinutesToMilliseconds(minutes) + + convertSecondsToMilliseconds(seconds) + + milliseconds; + this.positive = string.charAt(0) == '+'; + } catch (Exception e) {//NOSONAR + throw new PowerRuntimeException("Input String has wrong format."); + } + TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hours, minutes, seconds, milliseconds); + } + + /** + * + * @return random duration + */ + public static Duration createRandomDuration() { + Duration duration; + PseudoRandomGenerator pseudoRandomNumberGenerator = PseudoRandomGenerator.getInstance(); + long days = pseudoRandomNumberGenerator.getInt(0, 6000); + int hours = pseudoRandomNumberGenerator.getInt(0, 23); + int minutes = pseudoRandomNumberGenerator.getInt(0, 59); + int seconds = pseudoRandomNumberGenerator.getInt(0, 59); + int milliseconds = pseudoRandomNumberGenerator.getInt(0, 999); + duration = new Duration(days, hours, minutes, seconds, milliseconds); + return duration; + } + + /** + * Creates new Duration from startUniversalDateTime minus + * endUniversalDateTime. + * + * @param startUniversalDateTime + * @param endUniversalDateTime + * @return new instance of Duration + */ + public static Duration between(UniversalDateTime startUniversalDateTime, UniversalDateTime endUniversalDateTime) { + java.time.LocalDateTime javaStartLocalDateTime = startUniversalDateTime.toLocalDateTime().toJavaLocalDateTime(); + java.time.LocalDateTime javaEndLocalDateTime = endUniversalDateTime.toLocalDateTime().toJavaLocalDateTime(); + java.time.Duration javaDuration = java.time.Duration.between(javaStartLocalDateTime, javaEndLocalDateTime); + return new Duration(javaDuration.toMillis()); + + } + + /** + * Creates new Duration from startZonedDateTime minus endZonedDateTime. + * + * @param startZonedDateTime + * @param endZonedDateTime + * @return new instance of Duration + */ + public static Duration between(ZonedDateTime startZonedDateTime, ZonedDateTime endZonedDateTime) { + return between(startZonedDateTime.toUniversalDateTime(), endZonedDateTime.toUniversalDateTime()); + } + + private static int getMillisecondsPerDay() { + return MILLISECONDSPERDAY; + } + + private static long convertDaysToMilliseconds(long days) { + return days * getMillisecondsPerDay(); + } + + /** + * + * @param days + * @return an instance of Duration class with the given count of days + */ + public static Duration ofDays(long days) { + return new Duration(convertDaysToMilliseconds(days)); + } + + private static int getMillisecondsPerHour() { + return MILLISECONDSPERHOUR; + } + + private static long convertHoursToMilliseconds(long hours) { + return hours * getMillisecondsPerHour(); + } + + /** + * + * @param hours + * @return an instance of Duration class with the given count of hours + */ + public static Duration ofHours(long hours) { + return new Duration(convertHoursToMilliseconds(hours)); + } + + private static int getMillisecondsPerMinute() { + return MILLISECONDSPERMINUTE; + } + + private static long convertMinutesToMilliseconds(long minutes) { + return minutes * getMillisecondsPerMinute(); + } + + /** + * + * @param minutes + * @return an instance of Duration class with the given count of minutes + */ + public static Duration ofMinutes(long minutes) { + return new Duration(convertMinutesToMilliseconds(minutes)); + } + + private static int getMillisecondsPerSecond() { + return MILLISECONDSPERSECOND; + } + + private static long convertSecondsToMilliseconds(long seconds) { + return seconds * getMillisecondsPerSecond(); + } + + /** + * + * @param seconds + * @return an instance of Duration class with the given count of seconds + */ + public static Duration ofSeconds(long seconds) { + return new Duration(convertSecondsToMilliseconds(seconds)); + } + + /** + * + * @param milliseconds + * @return an instance of Duration class with the given count of + * milliseconds + */ + public static Duration ofMilliseconds(long milliseconds) { + return new Duration(milliseconds); + } + + /** + * + * @param universalDateTime + * @param duration + * @return add to universalDateTime duration and return result + */ + public static UniversalDateTime fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(UniversalDateTime universalDateTime, Duration duration) { + return addToUniversalDateTimeDuration(universalDateTime, duration, true); + } + + /** + * + * @param universalDateTime + * @param duration + * @return subtract from universalDateTime duration and return result + */ + public static UniversalDateTime fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(UniversalDateTime universalDateTime, Duration duration) { + return addToUniversalDateTimeDuration(universalDateTime, duration, false); + } + + private static UniversalDateTime addToUniversalDateTimeDuration(UniversalDateTime universalDateTime, Duration duration, boolean trueForAddingFalseForSubtracting) { + java.time.LocalDateTime javaLocalDateTime = universalDateTime.toLocalDateTime().toJavaLocalDateTime(); + java.time.Duration javaDuration = duration.toJavaDuration(); + java.time.LocalDateTime newJavaLocalDateTime; + if (trueForAddingFalseForSubtracting) { + newJavaLocalDateTime = javaLocalDateTime.plus(javaDuration); + } else { + newJavaLocalDateTime = javaLocalDateTime.minus(javaDuration); + } + + int year = newJavaLocalDateTime.getYear(); + int day = newJavaLocalDateTime.getDayOfMonth(); + int month = newJavaLocalDateTime.getMonth().getValue(); + int hour = newJavaLocalDateTime.getHour(); + int minute = newJavaLocalDateTime.getMinute(); + int second = newJavaLocalDateTime.getSecond(); + final int nanosecondspermillisecond; + nanosecondspermillisecond = 1000000; + int millisecond = newJavaLocalDateTime.getNano() / nanosecondspermillisecond; + + return new UniversalDateTime(year, month, day, hour, minute, second, millisecond); + } + + /** + * + * @param zonedDateTime + * @param duration + * @return add to zonedDateTime duration and return result + */ + public static ZonedDateTime fromZonedDateTimePlusDurationCreateNewZonedDateTime(ZonedDateTime zonedDateTime, Duration duration) { + return addToZonedDateTimeDuration(zonedDateTime, duration, true); + } + + /** + * + * @param zonedDateTime + * @param duration + * @return subtract from zonedDateTime duration and return result + */ + public static ZonedDateTime fromZonedDateTimeMinusDurationCreateNewZonedDateTime(ZonedDateTime zonedDateTime, Duration duration) { + return addToZonedDateTimeDuration(zonedDateTime, duration, false); + } + + private static ZonedDateTime addToZonedDateTimeDuration(ZonedDateTime zonedDateTime, Duration duration, boolean trueForAddingFalseForSubtracting) { + UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); + UniversalDateTime newUniversalDateTime; + if (trueForAddingFalseForSubtracting) { + newUniversalDateTime = fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration); + } else { + newUniversalDateTime = fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration); + } + + return new ZonedDateTime(newUniversalDateTime).toZonedDateTime(zonedDateTime.getTimeZone()); + } + + /** + * + * @return count of days + * + *

Example
+ *
+ * Duration duration=new Duration(6,19,46,12,754);
+ * long days=duration.getDays();
+ *
+ * days is 6 + */ + public long getDays() { + return days; + } + + /** + * + * @return count of hours + * + *

Example
+ *
+ * Duration duration=new Duration(6,19,46,12,754);
+ * long hours=duration.getHours();
+ *
+ * hours is 19 + */ + public int getHours() { + return hours; + } + + /** + * + * @return count of minutes + * + *

Example
+ *
+ * Duration duration=new Duration(6,19,46,12,754);
+ * long minutes=duration.getMinutes();
+ *
+ * minutes is 46 + */ + public int getMinutes() { + return minutes; + } + + /** + * + * @return count of seconds + * + *

Example
+ *
+ * Duration duration=new Duration(6,19,46,12,754);
+ * long seconds=duration.getSeconds();
+ *
+ * seconds is 12 + */ + public int getSeconds() { + return seconds; + } + + /** + * + * @return count of milliseconds + * + *

Example
+ *
+ * Duration duration=new Duration(6,19,46,12,754);
+ * long milliseconds=duration.Milliseconds();
+ *
+ * milliseconds is 754 + */ + public int getMilliseconds() { + return milliseconds; + } + + /** + * + * @return result of this control + */ + public boolean isPositive() { + return this.positive; + } + + /** + * + * @return new Duration instance created from negated this object + */ + public Duration negated() { + return new Duration(this.toTotalMilliseconds() * (-1)); + } + + /** + * + * @return new Duration instance created from this object, if this object is + * negative, returned Duration is not negative + */ + public Duration abs() { + long absCountOfTotalMilliseconds; + absCountOfTotalMilliseconds = this.countOfTotalMilliseconds >= 0 ? countOfTotalMilliseconds : (countOfTotalMilliseconds * (-1)); + return new Duration(absCountOfTotalMilliseconds); + } + + /** + * + * @param durationToAdd + * @return from this object plus the given durationToAdd new Duration + */ + public Duration plusDuration(Duration durationToAdd) { + return new Duration(this.toTotalMilliseconds() + durationToAdd.toTotalMilliseconds()); + } + + /** + * + * @param daysToAdd + * @return from this object plus the given daysToAdd new Duration + */ + public Duration plusDays(long daysToAdd) { + return this.plusMilliseconds(Duration.convertDaysToMilliseconds(daysToAdd)); + } + + /** + * + * @param hoursToAdd + * @return from this object plus the given hoursToAdd new Duration + */ + public Duration plusHours(long hoursToAdd) { + return this.plusMilliseconds(Duration.convertHoursToMilliseconds(hoursToAdd)); + } + + /** + * + * @param minutesToAdd + * @return from this object plus the given minutesToAdd new Duration + */ + public Duration plusMinutes(long minutesToAdd) { + return this.plusMilliseconds(Duration.convertMinutesToMilliseconds(minutesToAdd)); + } + + /** + * + * @param secondsToAdd + * @return from this object plus the given secondsToAdd new Duration + */ + public Duration plusSeconds(long secondsToAdd) { + return this.plusMilliseconds(Duration.convertSecondsToMilliseconds(secondsToAdd)); + } + + /** + * + * @param millisecondsToAdd + * @return from this object plus the given millisecondsToAdd new Duration + */ + public Duration plusMilliseconds(long millisecondsToAdd) { + return new Duration(this.toTotalMilliseconds() + millisecondsToAdd); + } + + /** + * + * @param durationToSubtract + * @return from this object minus the given durationToSubtract new Duration + */ + public Duration minusDuration(Duration durationToSubtract) { + return new Duration(this.toTotalMilliseconds() - durationToSubtract.toTotalMilliseconds()); + } + + /** + * + * @param daysToSubtract + * @return from this object minus the given daysToSubtract new Duration + */ + public Duration minusDays(long daysToSubtract) { + return this.minusMilliseconds(Duration.convertDaysToMilliseconds(daysToSubtract)); + } + + /** + * + * @param hoursToSubtract + * @return from this object minus the given hoursToSubtract new Duration + */ + public Duration minusHours(long hoursToSubtract) { + return this.minusMilliseconds(Duration.convertHoursToMilliseconds(hoursToSubtract)); + } + + /** + * + * @param minutesToSubtract + * @return from this object minus the given minutesToSubtract new Duration + */ + public Duration minusMinutes(long minutesToSubtract) { + return this.minusMilliseconds(Duration.convertMinutesToMilliseconds(minutesToSubtract)); + } + + /** + * + * @param secondsToSubtract + * @return from this object minus the given secondsToSubtract new Duration + */ + public Duration minusSeconds(long secondsToSubtract) { + return this.minusMilliseconds(Duration.convertSecondsToMilliseconds(secondsToSubtract)); + } + + /** + * + * @param millisecondsToSubtract + * @return from this object minus the given millisecondsToSubtract new + * Duration + */ + public Duration minusMilliseconds(long millisecondsToSubtract) { + return new Duration(this.toTotalMilliseconds() - millisecondsToSubtract); + } + + /** + * + * @return representation of this object in days + */ + public double toTotalDays() { + return countOfTotalMilliseconds / getMillisecondsPerDay(); + } + + /** + * + * @return representation of this object in hours + */ + public double toTotalHours() { + return countOfTotalMilliseconds / getMillisecondsPerHour(); + } + + /** + * + * @return representation of this object in minutes + */ + public double toTotalMinutes() { + return countOfTotalMilliseconds / getMillisecondsPerMinute(); + } + + /** + * + * @return representation of this object in seconds + */ + public double toTotalSeconds() { + return countOfTotalMilliseconds / getMillisecondsPerSecond(); + } + + /** + * + * @return representation of this object in milliseconds + */ + public long toTotalMilliseconds() { + return countOfTotalMilliseconds; + } + + /** + * + * @return java.time.duration representation of this object + */ + java.time.Duration toJavaDuration() { + java.time.Duration javaDuration = java.time.Duration.ofMillis(this.toTotalMilliseconds()); + if (!this.isPositive()) { + javaDuration.negated(); + } + return javaDuration; + } + + @Override + public String toString() { + StringBuilder stringBuilder; + stringBuilder = new StringBuilder(); + if (this.isPositive()) { + stringBuilder.append(PLUS); + } else { + stringBuilder.append(MINUS); + } + stringBuilder.append(this.getDays()); + stringBuilder.append(COLON); + stringBuilder.append(this.getHours()); + stringBuilder.append(COLON); + stringBuilder.append(this.getMinutes()); + stringBuilder.append(COLON); + stringBuilder.append(this.getSeconds()); + stringBuilder.append(COLON); + stringBuilder.append(this.getMilliseconds()); + return stringBuilder.toString(); + + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java b/src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java new file mode 100644 index 0000000..02fdd47 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java @@ -0,0 +1,132 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents Date without time zone information. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class LocalDate { + + private final int year; + private final int month; + private final int day; + + /** + * Constructor + * + * @param year Year of this date. + * @param month Month of this date. + * @param day Day of this date. + * @exception PowerRuntimeException if parameters are invalid or have wrong + * combination. + */ + public LocalDate(int year, int month, int day) { + LocalDate.checkInputValuesForDateAndIfThereIsAnInvalidOneThrowException(year, month, day); + this.year = year; + this.month = month; + this.day = day; + } + + /** + * Checks input data for date. + * + * @param year + * @param month + * @param day + * @exception PowerRuntimeException if input data for date are invalid or + * have wrong combination.
+ * This will throw PowerRuntimeException: + * {@code new LocalDateTime(2015,2,29)}
+ * This will throw PowerRuntimeException: + * {@code new LocalDateTime(2013,6,31)}
+ * This will not throw PowerRuntimeException: + * {@code new LocalDateTime(2013,6,30)}
+ */ + private static void checkInputValuesForDateAndIfThereIsAnInvalidOneThrowException(int year, int month, int day) { + if (!DateUnitsValidator.isMonthValid(month)) { + throw new PowerRuntimeException("Month is not valid."); + } + if (!DateUnitsValidator.isDayValid(day)) { + throw new PowerRuntimeException("Day is not valid."); + } + if (!DateUnitsValidator.hasDateValidCombination(year, month, day)) { + throw new PowerRuntimeException("Date has not valid combination."); + + } + } + + /** + * Checks if year is leap. A year is leap if this year is divided by 4 and + * there remainder 0. In other words this year is divisible by 4. + * + * @param year + * @return true if the year is leap, otherwise false. + */ + public static boolean isYearLeap(int year) { + return (year % 4) == 0; + } + + /** + * + * @return year of this date. + */ + public int getYear() { + return this.year; + } + + /** + * + * @return month of this date. + */ + public int getMonth() { + return this.month; + } + + /** + * + * @return day of this date. + */ + public int getDay() { + return this.day; + } + + @Override + public String toString() { + StringBuilder stringBuilder; + stringBuilder = new StringBuilder(); + stringBuilder.append(this.getYear()); + stringBuilder.append("-"); + if (month < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getMonth()); + stringBuilder.append("-"); + if (day < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getDay()); + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java new file mode 100644 index 0000000..73432d7 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java @@ -0,0 +1,112 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.time.format.DateTimeFormatter; + +/** + * This class stores date time without time zone information. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class LocalDateTime extends DateTime { + + /** + * Constructor + * + * Creates new LocalDateTime from String. + * + * @param dateTimeInString + */ + protected LocalDateTime(String dateTimeInString) { + super(dateTimeInString); + } + + /** + * Constructor + * + * Creates new LocalDateTime with these parameters. + * + * @param year + * @param month + * @param day + * @param hour24Format + * @param minute + * @param second + * @param millisecond + */ + public LocalDateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + super(year, month, day, hour24Format, minute, second, millisecond); + } + + /** + * Constructor + * + * Creates new LocalDateTime from UniversalDateTime. + * + * @param universalDateTime + */ + public LocalDateTime(UniversalDateTime universalDateTime) { + super(universalDateTime); + } + + /** + * Constructor + * + * Creates new LocalDateTime from ZonedDateTime. + * + * @param zonedDateTime + */ + public LocalDateTime(ZonedDateTime zonedDateTime) { + super(zonedDateTime); + } + + /** + * + * + * @return a UniversalDateTime instance from this object + */ + public UniversalDateTime toUniversalDateTime() { + return new UniversalDateTime(this); + } + + /** + * + * + * @param timeZone time zone of new created ZonedDateTime + * @return a ZonedDateTime instance from this object + */ + public ZonedDateTime toZonedDateTime(org.nanoboot.powerframework.datetime.TimeZone timeZone) { + return new ZonedDateTime(this, timeZone); + } + + /** + * + * + * @return a java.time.LocalDateTime instance from this object + */ + java.time.LocalDateTime toJavaLocalDateTime() { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"); + String stringRepresentationOfThisObject = this.toString(); + return java.time.LocalDateTime.parse(stringRepresentationOfThisObject, dateTimeFormatter); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java b/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java new file mode 100644 index 0000000..de58f35 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java @@ -0,0 +1,115 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents Time without date and time zone information. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class LocalTime { + + private static final String COLON = ":"; + + private final int hour; + private final int minute; + private final int second; + private final int millisecond; + + /** + * Constructor + * + * @param hour + * @param minute + * @param second + * @param millisecond + * @exception PowerRuntimeException if parameters are invalid. + */ + public LocalTime(int hour, int minute, int second, int millisecond) { + TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); + this.hour = hour; + this.minute = minute; + this.second = second; + this.millisecond = millisecond; + } + + /** + * + * @return hour of this time. + */ + public int getHour() { + return hour; + } + + /** + * + * @return minute of this time. + */ + public int getMinute() { + return minute; + } + + /** + * + * @return second of this time. + */ + public int getSecond() { + return second; + } + + /** + * + * @return millisecond of this time. + */ + public int getMillisecond() { + return millisecond; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + + if (hour < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getHour()); + stringBuilder.append(COLON); + if (minute < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getMinute()); + stringBuilder.append(COLON); + if (second < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getSecond()); + stringBuilder.append(COLON); + if (millisecond < 10) { + stringBuilder.append("00"); + } else if (millisecond < 100) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getMillisecond()); + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java b/src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java new file mode 100644 index 0000000..9992e1c --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java @@ -0,0 +1,104 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.text.DateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * Is used to get current universal date and time. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class TimeSource { + + private static final org.nanoboot.powerframework.datetime.TimeZone universalTimeZone = new org.nanoboot.powerframework.datetime.TimeZone("GMT"); + + private static final DateFormat yearFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "yyyy"); + private static final DateFormat monthFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "MM"); + private static final DateFormat dayFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "dd"); + private static final DateFormat hourFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "HH"); + private static final DateFormat minuteFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "mm"); + private static final DateFormat secondFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "ss"); + private static final DateFormat millisecondFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "S"); + + /** + * Represents source for current universal date time. + */ + private Calendar calendar; + private final UniversalDateTime universalDateTime; + + /** + * Constructor + * + * Every time, you want know the current time, you have to create new + * instance of TimeSource class. + */ + private TimeSource() { + this.universalDateTime = this.buildCurrentUniversalDateTime(); + } + + /** + * + * @return current universal date time + */ + public static UniversalDateTime getCurrentUniversalDateTimeInstance() { + TimeSource timeSource = new TimeSource(); + return timeSource.getCurrentUniversalDateTime(); + } + + /** + * + * @return Date instance for current universal date and time + */ + private UniversalDateTime buildCurrentUniversalDateTime() { + Date currentDate = getCurrentDate(); + int year = Integer.parseInt(yearFormat.format(currentDate)); + int month = Integer.parseInt(monthFormat.format(currentDate)); + int day = Integer.parseInt(dayFormat.format(currentDate)); + + int hour = Integer.parseInt(hourFormat.format(currentDate)); + int minute = Integer.parseInt(minuteFormat.format(currentDate)); + int second = Integer.parseInt(secondFormat.format(currentDate)); + int millisecond = Integer.parseInt(millisecondFormat.format(currentDate)); + return new UniversalDateTime(year, month, day, hour, minute, second, millisecond); + } + + /** + * + * @return a new instance of Date class for current universal date and time + */ + private Date getCurrentDate() { + calendar = Calendar.getInstance(); + Date currentDate = calendar.getTime(); + calendar = null; + return currentDate; + } + + /** + * + * @return current universal date time + */ + UniversalDateTime getCurrentUniversalDateTime() { + return this.universalDateTime; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java b/src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java new file mode 100644 index 0000000..44f03b7 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java @@ -0,0 +1,118 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Validates time units. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class TimeUnitsValidator { + + private static final int HOURLOWERBOUND = 0; + private static final int HOURHIGHERBOUND = 23; + private static final int MINUTEORSECONDLOWERBOUND = 0; + private static final int MINUTEORSECONDHIGHERBOUND = 59; + private static final int MILLISECONDLOWERBOUND = 0; + private static final int MILLISECONDHIGHERBOUND = 999; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private TimeUnitsValidator() { + } + + /** + * Checks if hour has valid format. + * + * @param hour + * @return Result of this control. + */ + static boolean isHourValid(int hour) { + return (hour >= HOURLOWERBOUND) && (hour <= HOURHIGHERBOUND); + } + + /** + * Checks if minuteOrSecond has valid format. + * + * @param minuteOrSecond + * @return Result of this control. + */ + private static boolean isMinuteOrSecondValid(int minuteOrSecond) { + return (minuteOrSecond >= MINUTEORSECONDLOWERBOUND) && (minuteOrSecond <= MINUTEORSECONDHIGHERBOUND); + } + + /** + * Checks if minute has valid format. + * + * @param minute + * @return Result of this control. + */ + static boolean isMinuteValid(int minute) { + return isMinuteOrSecondValid(minute); + } + + /** + * Checks if second has valid format. + * + * @param second + * @return Result of this control. + */ + static boolean isSecondValid(int second) { + return isMinuteOrSecondValid(second); + } + + /** + * Checks if millisecond has valid format. + * + * @param millisecond + * @return Result of this control. + */ + static boolean isMillisecondValid(int millisecond) { + return (millisecond >= MILLISECONDLOWERBOUND) && (millisecond <= MILLISECONDHIGHERBOUND); + } + + /** + * Checks if all the given time values are valid. + * + * @param hour + * @param minute + * @param second + * @param millisecond + * * @return Result of this control. + */ + static boolean areAllTimeUnitsValid(int hour, int minute, int second, int millisecond) { + return isHourValid(hour) + && (isMinuteValid(minute)) + && (isSecondValid(second)) + && (isMillisecondValid(millisecond)); + } + + static void checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(int hour, int minute, int second, int millisecond) { + if (!areAllTimeUnitsValid(hour, minute, second, millisecond)) { + throw new PowerRuntimeException("One or more values of time units have invalid format."); + } + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java b/src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java new file mode 100644 index 0000000..cbf4cf2 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java @@ -0,0 +1,92 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents time zone. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TimeZone { + + private static final ArrayList listOfTimeZones = new ArrayList<>(ZoneId.getAvailableZoneIds()); + + private final String timeZoneID; + + /** + * Constructor + * + * Only time zone with valid timeZoneID can be created. + * + * @param timeZoneID + */ + public TimeZone(String timeZoneID) { + if (!TimeZone.isTimeZoneIDValid(timeZoneID)) { + throw new PowerRuntimeException("There is no time zone id with the name " + timeZoneID + "."); + } + this.timeZoneID = timeZoneID; + } + + static { + Collections.sort(listOfTimeZones); + } + + /** + * + * @return list of all available time zone IDs + */ + public static List getListOfTimeZoneIDs() { + return listOfTimeZones; + } + + /** + * + * @param timeZoneID + * @return true if the timeZoneID is valid (available), otherwise false. + */ + public static boolean isTimeZoneIDValid(String timeZoneID) { + return listOfTimeZones.contains(timeZoneID); + } + + /** + * + * @return time zone ID of this time zone + */ + @Override + public String toString() { + return this.timeZoneID; + } + + /** + * + * @return time zone ID of this time zone + */ + public String getTimeZoneID() { + return this.toString(); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java new file mode 100644 index 0000000..a9985a9 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java @@ -0,0 +1,131 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; + +/** + * This class stores universal date time. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class UniversalDateTime extends DateTime { + + /** + * Constructor + * + * Creates new UniversalDateTime from String. + * + * @param stringRepresentationOfNewlyCreatedObject + */ + public UniversalDateTime(String stringRepresentationOfNewlyCreatedObject) { + super(stringRepresentationOfNewlyCreatedObject); + } + + /** + * Constructor + * + * Creates new UniversalDateTime with these parameters. + * + * @param year + * @param month + * @param day + * @param hour24Format + * @param minute + * @param second + * @param millisecond + */ + public UniversalDateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + super(year, month, day, hour24Format, minute, second, millisecond); + } + + /** + * Constructor + * + * Creates new UniversalDateTime from ZonedDateTime. + * + * @param zonedDateTime + */ + public UniversalDateTime(ZonedDateTime zonedDateTime) { + super(zonedDateTime.toUniversalDateTime()); + } + + /** + * Constructor + * + * Creates new UniversalDateTime from LocalDateTime. + * + * @param localDateTime + */ + public UniversalDateTime(LocalDateTime localDateTime) { + super(localDateTime); + } + + /** + * + * @return current universal date time + */ + public static UniversalDateTime getCurrentUniversalDateTime() { + return TimeSource.getCurrentUniversalDateTimeInstance(); + } + + /** + * + * @return random universal date time + */ + public static UniversalDateTime getRandomUniversalDateTime() { + UniversalDateTime universalDateTime; + + int maxPossibleYear = UniversalDateTime.getCurrentUniversalDateTime().getYear(); + + int randomYear = PseudoRandomGenerator.getInstance().getInt(1900, maxPossibleYear); + int randomMonth = PseudoRandomGenerator.getInstance().getInt(1, 12); + int randomDay = PseudoRandomGenerator.getInstance().getInt(1, 31); + + int randomHour = PseudoRandomGenerator.getInstance().getInt(0, 23); + int randomMinute = PseudoRandomGenerator.getInstance().getInt(0, 59); + int randomSecond = PseudoRandomGenerator.getInstance().getInt(0, 59); + int randomMillisecond = PseudoRandomGenerator.getInstance().getInt(0, 999); + + if (!DateUnitsValidator.hasDateValidCombination(randomYear, randomMonth, randomDay)) { + randomDay = randomDay - PseudoRandomGenerator.getInstance().getInt(3, 20); + } + + universalDateTime = new UniversalDateTime(randomYear, randomMonth, randomDay, randomHour, randomMinute, randomSecond, randomMillisecond); + + return universalDateTime; + } + + /** + * @return a ZonedDateTime instance from this object + */ + public ZonedDateTime toZonedDateTime() { + return new ZonedDateTime(this); + } + + /** + * @return a LocalDateTime instance from this object without universal date + * time information. + */ + public LocalDateTime toLocalDateTime() { + return new LocalDateTime(this); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java new file mode 100644 index 0000000..e83366a --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java @@ -0,0 +1,160 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +/** + * Represents date and time with time zone information. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class ZonedDateTime extends DateTime { + + private static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss:SSS"; + private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATETIMEFORMAT); + /** + * Instance of class UniversalDateTime for this ZonedDateTime. + */ + private final UniversalDateTime universalDateTime; + private final TimeZone timeZone; + + /** + * Constructor + * + * Creates ZonedDateTime from UniversalDateTime with universal time zone. + * + * @param universalDateTime + */ + public ZonedDateTime(UniversalDateTime universalDateTime) { + super(universalDateTime); + + TimeZone timeZoneForUniversalTime = new org.nanoboot.powerframework.datetime.TimeZone("UTC"); + this.timeZone = timeZoneForUniversalTime; + this.universalDateTime = universalDateTime; + + } + + /** + * Constructor + * + * Creates ZonedDateTime from LocalDateTime with the given time zone. + * + * @param localDateTime + * @param toTimeZone + */ + public ZonedDateTime(LocalDateTime localDateTime, org.nanoboot.powerframework.datetime.TimeZone toTimeZone) { + super(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDay(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond(), localDateTime.getMillisecond()); + + String stringRepresentationOfLocalDateTime = localDateTime.toString(); + TimeZone timeZoneForUniversalTime = new org.nanoboot.powerframework.datetime.TimeZone("UTC"); + String stringRepresentationOfZonedDateTimeWithUniversalTimeZone = org.nanoboot.powerframework.datetime.ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother( + stringRepresentationOfLocalDateTime, + toTimeZone, + timeZoneForUniversalTime + ); + this.universalDateTime = new UniversalDateTime(stringRepresentationOfZonedDateTimeWithUniversalTimeZone); + + this.timeZone = toTimeZone; + } + + /** + * Constructor + * + * Creates ZonedDateTime from another ZonedDateTime object, but the time + * zone is changed. + * + * @param zonedDateTime + * @param newTimeZone + */ + public ZonedDateTime(ZonedDateTime zonedDateTime, org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { + super(ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother(zonedDateTime.toString(), zonedDateTime.timeZone, newTimeZone)); + + this.universalDateTime = zonedDateTime.toUniversalDateTime(); + this.timeZone = newTimeZone; + } + + /** + * + * @param dateTimeInString + * @param oldTimeZone + * @param newTimeZone + * + * @return String representation from the given String, but old time zone is + * changed to new time zone. + */ + static String convertDateTimeFromOneTimeZoneToAnother(String dateTimeInString, org.nanoboot.powerframework.datetime.TimeZone oldTimeZone, org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { + + java.time.LocalDateTime localDateTime = java.time.LocalDateTime.parse(dateTimeInString, dateTimeFormatter); + + ZoneId oldZoneID = ZoneId.of(oldTimeZone.getTimeZoneID()); + java.time.ZonedDateTime oldZonedDateTime = localDateTime.atZone(oldZoneID); + + ZoneId newZoneId = ZoneId.of(newTimeZone.getTimeZoneID()); + java.time.ZonedDateTime newZonedDateTime = oldZonedDateTime.withZoneSameInstant(newZoneId); + return dateTimeFormatter.format(newZonedDateTime); + } + + /** + * + * @return time zone of this ZonedDateTime + */ + public TimeZone getTimeZone() { + return timeZone; + } + + /** + * + * @return a UniversalDateTime instance from this object + */ + public UniversalDateTime toUniversalDateTime() { + return this.universalDateTime; + } + + /** + * + * @return a LocalDateTime instance from this object + */ + public LocalDateTime toLocalDateTime() { + return new LocalDateTime(this); + } + + /** + * + * @param newTimeZone + * @return a ZonedDateTime instance from this object with the given new time + * zone. + */ + public ZonedDateTime toZonedDateTime(org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { + return new ZonedDateTime(this, newTimeZone); + } + + /** + * + * @return a java.time.ZonedDateTime instance from this object + */ + java.time.ZonedDateTime toJavaZonedDateTime() { + ZoneId zoneId = java.time.ZoneId.of(this.timeZone.getTimeZoneID()); + java.time.LocalDateTime tempLocalDateTime = java.time.LocalDateTime.parse(toString(), dateTimeFormatter); + return tempLocalDateTime.atZone(zoneId); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/package-info.java b/src/main/java/org/nanoboot/powerframework/datetime/package-info.java new file mode 100644 index 0000000..65f290b --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/datetime/package-info.java @@ -0,0 +1,4 @@ +/** + * This package contains date and time utilities. + */ +package org.nanoboot.powerframework.datetime; diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArray.java b/src/main/java/org/nanoboot/powerframework/json/JsonArray.java new file mode 100644 index 0000000..93ee6c9 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonArray.java @@ -0,0 +1,424 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.ArrayList; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents json array. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class JsonArray { + + private ArrayList arrayList = new ArrayList<>(); + + /** + * Constructor + * + * Used to create empty jsonObject. + */ + public JsonArray() { + //Used to create empty jsonObject. + } + + /** + * Constructor + * + * From String creates json array. + * + * @param stringRepresentationOfThisJsonArray + */ + public JsonArray(String stringRepresentationOfThisJsonArray) { + JsonArrayParser.parseStringToJsonArray(this, stringRepresentationOfThisJsonArray); + } + + /** + * + * @return count of items of this json array. + */ + public int getCountOfItems() { + return this.arrayList.size(); + } + + /** + * + * @return result of this control + */ + public boolean isEmpty() { + return this.arrayList.isEmpty(); + } + + /** + * New value is added- object is converted to the most suitable json value + * type and is set as the new value. + * + * @param object + */ + public void add(Object object) {//NOSONAR + if (object == null) { + addNull(); + } else { + switch (object.getClass().getName()) { + case "org.nanoboot.powerframework.json.JsonObject": + addObject((JsonObject) object); + break; + case "org.nanoboot.powerframework.json.JsonArray": + addArray((JsonArray) object); + break; + case "java.lang.Boolean": + addBoolean((boolean) object); + break; + case "java.lang.String": + addString((String) object); + break; + case "java.lang.Character": + addChar((char) object); + break; + case "java.lang.Integer": + addInt((int) object); + break; + case "java.lang.Long": + addLong((long) object); + break; + case "java.lang.Float": + addFloat((float) object); + break; + case "java.lang.Double": + addDouble((double) object); + break; + default: + throw new PowerRuntimeException("I can't add the given object as value."); + } + } + } + + /** + * Adds null. + */ + public void addNull() { + this.arrayList.add(new JsonValue()); + } + + /** + * Adds json object. + * + * @param value + */ + public void addObject(JsonObject value) { + this.arrayList.add(new JsonValue(value)); + } + + /** + * Adds json array. + * + * @param value + * @return + */ + public JsonArray addArray(JsonArray value) {//this + this.arrayList.add(new JsonValue(value)); + return this; + } + + /** + * Adds boolean. + * + * @param value + */ + public void addBoolean(boolean value) { + this.arrayList.add(new JsonValue(new JsonBoolean(value))); + } + + /** + * Adds String. + * + * @param value + * @return + */ + public JsonArray addString(String value) { + this.arrayList.add(new JsonValue(new JsonString(value))); + return this; + } + + /** + * Adds char. + * + * @param value + */ + public void addChar(char value) { + this.arrayList.add(new JsonValue(new JsonChar(value))); + } + + /** + * Adds int. + * + * @param value + */ + public void addInt(int value) { + this.arrayList.add(new JsonValue(new JsonInt(value))); + } + + /** + * Adds long. + * + * @param value + */ + public void addLong(long value) { + this.arrayList.add(new JsonValue(new JsonLong(value))); + } + + /** + * Adds float. + * + * @param value + */ + public void addFloat(float value) { + this.arrayList.add(new JsonValue(new JsonFloat(value))); + } + + /** + * Adds double. + * + * @param value + */ + public void addDouble(double value) { + this.arrayList.add(new JsonValue(new JsonDouble(value))); + } + + /** + * + * @param index + * @return json value type of the value at the given index + */ + public JsonValueType getJsonValueType(int index) { + return this.arrayList.get(index).getJsonValueType(); + } + + /** + * + * @param index + * @return JsonObject + */ + public JsonObject getObject(int index) { + return this.arrayList.get(index).getJsonObject(); + } + + /** + * + * @param index + * @return JsonArraz + */ + public JsonArray getArray(int index) { + return this.arrayList.get(index).getJsonArray(); + } + + /** + * + * @param index + * @return boolean + */ + public boolean getBoolean(int index) { + return this.arrayList.get(index).getJsonBoolean().getBoolean(); + } + + /** + * + * @param index + * @return String + */ + public String getString(int index) { + return this.arrayList.get(index).getJsonString().getString(); + } + + /** + * + * @param index + * @return char + */ + public char getChar(int index) { + return this.arrayList.get(index).getJsonChar().getChar(); + } + + /** + * + * @param index + * @return int + */ + public int getInt(int index) { + return this.arrayList.get(index).getJsonInt().getInt(); + } + + /** + * + * @param index + * @return long + */ + public long getLong(int index) { + return this.arrayList.get(index).getJsonLong().getLong(); + } + + /** + * + * @param index + * @return float + */ + public float getFloat(int index) { + return this.arrayList.get(index).getJsonFloat().getFloat(); + } + + /** + * + * @param index + * @return double + */ + public double getDouble(int index) { + return this.arrayList.get(index).getJsonDouble().getDouble(); + } + + /** + * + * @param index to be updated + */ + public void updateNull(int index) { + this.arrayList.set(index, new JsonValue()); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateObject(int index, JsonObject value) { + this.arrayList.set(index, new JsonValue(value)); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateArray(int index, JsonArray value) { + this.arrayList.set(index, new JsonValue(value)); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateBoolean(int index, boolean value) { + this.arrayList.set(index, new JsonValue(new JsonBoolean(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateString(int index, String value) { + this.arrayList.set(index, new JsonValue(new JsonString(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateChar(int index, char value) { + this.arrayList.set(index, new JsonValue(new JsonChar(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateInt(int index, int value) { + this.arrayList.set(index, new JsonValue(new JsonInt(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateLong(int index, long value) { + this.arrayList.set(index, new JsonValue(new JsonLong(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateFloat(int index, float value) { + this.arrayList.set(index, new JsonValue(new JsonFloat(value))); + } + + /** + * + * @param index + * @param value to be updated + */ + public void updateDouble(int index, double value) { + this.arrayList.set(index, new JsonValue(new JsonDouble(value))); + } + + /** + * Removes value with the given index. + * + * @param index + */ + public void removeJsonValue(int index) { + this.arrayList.remove(index); + } + + JsonValue getJsonValue(int index) { + return this.arrayList.get(index); + } + + /** + * + * @return representation of this json array as minimal String + */ + public String toMinimalString() { + return JsonArrayPrinter.toMinimalString(this); + } + + /** + * + * @return representation of this json array as pretty String + */ + public String toPrettyString() { + return JsonArrayPrinter.toPrettyString(this); + } + + /** + * + * @return copy of this json array + */ + public JsonArray getCopy() { + String stringRepresentationOfThisArray = this.toMinimalString(); + return new JsonArray(stringRepresentationOfThisArray); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java b/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java new file mode 100644 index 0000000..063f0d3 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java @@ -0,0 +1,88 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.ArrayList; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Is used to create json arrays from Strings. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonArrayParser extends JsonParser { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private JsonArrayParser() { + //Not meant to be instantiated. + } + + /** + * Parses String to empty json object. + * + * @param jsonObject + * @param stringRepresentationOfJsonObject + * @return json object from parsed String + */ + static JsonArray parseStringToJsonArray(JsonArray jsonArray, String stringRepresentationOfJsonArray) { + if (!jsonArray.isEmpty()) { + throw new PowerRuntimeException("I can't parse. The json array is not empty."); + } + String trimmedStringRepresentationOfJsonArray = stringRepresentationOfJsonArray.trim(); + if (!isStringJsonArray(trimmedStringRepresentationOfJsonArray)) { + throw new PowerRuntimeException("I can't parse. The trimmed String does not start with [ or does not end with ]"); + } + String collectionsOfValuesOfTheJsonArrayString = deleteTheCharAtTheStartAndTheEnd(trimmedStringRepresentationOfJsonArray); + if ("".equals(collectionsOfValuesOfTheJsonArrayString)) { + return jsonArray; + } + fillJsonArrayWithParsedValues(jsonArray, collectionsOfValuesOfTheJsonArrayString); + return jsonArray; + } + + private static boolean isStringJsonArray(String trimmedStringRepresentationOfJsonArray) { + return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonSpecialCharSequences.getArrayLeft()) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonSpecialCharSequences.getArrayRight()); + } + + private static void fillJsonArrayWithParsedValues(JsonArray jsonArray, String collectionsOfValuesOfTheJsonArrayString) { + + ArrayList listOfCommas = getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(collectionsOfValuesOfTheJsonArrayString); + + int beginIndex; + int indexOfComma = 0; + for (int i = 0; i < listOfCommas.size(); i++) { + beginIndex = ++indexOfComma; + indexOfComma = listOfCommas.get(i); + if (i == 0) { + beginIndex = 0; + } + String fraction = collectionsOfValuesOfTheJsonArrayString.substring(beginIndex, indexOfComma); + Object parsedObject = JsonParser.parseStringToValue(fraction); + jsonArray.add(parsedObject); + } + + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java b/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java new file mode 100644 index 0000000..dc15959 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java @@ -0,0 +1,98 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Used to create String representation of a json array. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonArrayPrinter { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private JsonArrayPrinter() { + //Not meant to be instantiated. + } + + /** + * + * @return representation of the json array as pretty String + */ + static String toMinimalString(JsonArray jsonArray) { + return toString(jsonArray, false); + } + + /** + * + * @return representation of the json array as pretty String + */ + static String toPrettyString(JsonArray jsonArray) { + return toString(jsonArray, true); + + } + + /** + * + * @return representation of the json array as String + */ + static String toString(JsonArray jsonArray, boolean printAsPrettyVersion) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(JsonSpecialCharSequences.getArrayLeft()); + if (printAsPrettyVersion) { + stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + } + int i = 0; + + String value; + while (i != jsonArray.getCountOfItems()) { + if (printAsPrettyVersion) { + value = jsonArray.getJsonValue(i).toPrettyString(); + } else { + value = jsonArray.getJsonValue(i).toMinimalString(); + } + if (printAsPrettyVersion) { + if (!((jsonArray.getJsonValue(i).isArray()) || (jsonArray.getJsonValue(i).isObject()))) { + stringBuilder.append(JsonSpecialCharSequences.getTab()); + } else { + value = JsonPrinter.addTabOnEveryLineStart(value); + } + } + + stringBuilder.append(value); + if ((i + 1) != jsonArray.getCountOfItems()) { + stringBuilder.append(","); + } + if (printAsPrettyVersion) { + stringBuilder.append("\n"); + } + i++; + } + stringBuilder.append(JsonSpecialCharSequences.getArrayRight()); + + return stringBuilder.toString(); + + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java b/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java new file mode 100644 index 0000000..f0b882f --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents boolean json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonBoolean { + + private final boolean value; + + JsonBoolean(boolean value) { + this.value = value; + } + + boolean getBoolean() { + return this.value; + } + + @Override + public String toString() { + if (getBoolean()) { + return JsonSpecialCharSequences.getTrue(); + } else { + return JsonSpecialCharSequences.getFalse(); + } + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonChar.java b/src/main/java/org/nanoboot/powerframework/json/JsonChar.java new file mode 100644 index 0000000..2b406e2 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonChar.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents char json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonChar { + + private final char value; + + JsonChar(char value) { + this.value = value; + } + + char getChar() { + return this.value; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('\"'); + sb.append(Character.toString(getChar())); + sb.append('\"'); + return sb.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java b/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java new file mode 100644 index 0000000..6822cd6 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java @@ -0,0 +1,44 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents double json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonDouble { + + private final double value; + + JsonDouble(double value) { + this.value = value; + } + + double getDouble() { + return this.value; + } + + @Override + public String toString() { + return Double.toString(getDouble()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java b/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java new file mode 100644 index 0000000..88be199 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java @@ -0,0 +1,44 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents float json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonFloat { + + private final float value; + + JsonFloat(float value) { + this.value = value; + } + + float getFloat() { + return this.value; + } + + @Override + public String toString() { + return Float.toString(getFloat()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonInt.java b/src/main/java/org/nanoboot/powerframework/json/JsonInt.java new file mode 100644 index 0000000..58fe21d --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonInt.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents int json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonInt { + + private final int value; + + JsonInt(int value) { + this.value = value; + } + + int getInt() { + return this.value; + } + + @Override + public String toString() { + return Integer.toString(getInt()); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonLong.java b/src/main/java/org/nanoboot/powerframework/json/JsonLong.java new file mode 100644 index 0000000..93fa2ea --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonLong.java @@ -0,0 +1,44 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents long json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonLong { + + private final long value; + + JsonLong(long value) { + this.value = value; + } + + long getLong() { + return this.value; + } + + @Override + public String toString() { + return Long.toString(getLong()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObject.java b/src/main/java/org/nanoboot/powerframework/json/JsonObject.java new file mode 100644 index 0000000..03fe0a7 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonObject.java @@ -0,0 +1,540 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.collections.Dictionary; +import org.nanoboot.powerframework.collections.DictionaryKeyIterator; + +/** + * Represents json object of json. * @author Robert Vokac e-mail: + * robertvokac@nanoboot.org + */ +public class JsonObject { + + private final Dictionary dictionary = new Dictionary<>(); + + /** + * Constructor + * + * Used to create empty jsonObject. + */ + public JsonObject() { + // Used to create empty jsonObject. + } + + /** + * Constructor + * + * From String creates json object. + * + * @param textToParse + */ + public JsonObject(String textToParse) { + JsonObjectParser.parseStringToJsonObject(this, textToParse); + } + + /** + * + * @return count of items(keys and its values) of this json object + */ + public int getCountOfItems() { + return dictionary.getCountOfItems(); + } + + /** + * + * @return result of this control + */ + public boolean isEmpty() { + return dictionary.isEmpty(); + } + + /** + * + * @param key + * @return result of this control + */ + public boolean containsValueWithKey(String key) { + return this.dictionary.containsValueWithKey(key); + } + + /** + * Add to this json object new key, object is converted to the most suitable + * json value type and is set as value of the key. + * + * @param key + * @param object + * @return + */ + public JsonObject add(String key, Object object) {//NOSONAR + if (object == null) { + addNull(key); + } else { + switch (object.getClass().getName()) { + case "org.nanoboot.powerframework.json.JsonObject": + addObject(key, (JsonObject) object); + break; + case "org.nanoboot.powerframework.json.JsonArray": + addArray(key, (JsonArray) object); + break; + case "java.lang.Boolean": + addBoolean(key, (boolean) object); + break; + case "java.lang.String": + addString(key, (String) object); + break; + case "java.lang.Character": + addChar(key, (char) object); + break; + case "java.lang.Integer": + addInt(key, (int) object); + break; + case "java.lang.Long": + addLong(key, (long) object); + break; + case "java.lang.Float": + addFloat(key, (float) object); + break; + case "java.lang.Double": + addDouble(key, (double) object); + break; + default: + throw new PowerRuntimeException("I can't add the given object as value."); + } + } + return this; + } + + /** + * Add to this json object new key with null as value. + * + * @param key + * @return + */ + public JsonObject addNull(String key) { + this.dictionary.addValue(key, new JsonValue()); + return this; + } + + /** + * Add to this json object new key with json object as value. + * + * @param key + * @param value + * @return + */ + public JsonObject addObject(String key, JsonObject value) { + this.dictionary.addValue(key, new JsonValue(value)); + return this; + } + + /** + **Add to this json object new key with json array as value. + * + * @param key + * @param value + * @return + */ + public JsonObject addArray(String key, JsonArray value) { + this.dictionary.addValue(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the boolean as the + * value of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addBoolean(String key, boolean value) { + this.dictionary.addValue(key, new JsonValue(new JsonBoolean(value))); + return this; + } + + /** + * Add to this json object new key with the value of the String as the value + * of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addString(String key, String value) { + this.dictionary.addValue(key, new JsonValue(new JsonString(value))); + return this; + } + + /** + * Add to this json object new key with the value of the char as the value + * of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addChar(String key, char value) { + this.dictionary.addValue(key, new JsonValue(new JsonChar(value))); + return this; + } + + /** + * Add to this json object new key with the value of the int as the value of + * the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addInt(String key, int value) { + this.dictionary.addValue(key, new JsonValue(new JsonInt(value))); + return this; + } + + /** + * Add to this json object new key with the value of the long as the value + * of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addLong(String key, long value) { + this.dictionary.addValue(key, new JsonValue(new JsonLong(value))); + return this; + } + + /** + * Add to this json object new key with the value of the float as the value + * of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addFloat(String key, float value) { + this.dictionary.addValue(key, new JsonValue(new JsonFloat(value))); + return this; + } + + /** + * Add to this json object new key with the value of the double as the value + * of the key. + * + * @param key + * @param value + * @return + */ + public JsonObject addDouble(String key, double value) { + this.dictionary.addValue(key, new JsonValue(new JsonDouble(value))); + return this; + } + + /** + * + * @param key + * @return value type of the value of the given key + */ + public JsonValueType getJsonValueType(String key) { + return dictionary.getValue(key).getJsonValueType(); + } + + /** + * + * @param key + * @return object instance converted from the value of the given key + */ + public Object get(String key) { + return dictionary.getValue(key).toObject(); + } + + /** + * + * @param key + * @return json object from the value of the given key + */ + public JsonObject getObject(String key) { + return this.dictionary.getValue(key).getJsonObject(); + } + + /** + * + * @param key + * @return json array from the value of the given key + */ + public JsonArray getArray(String key) { + return this.dictionary.getValue(key).getJsonArray(); + } + + /** + * + * @param key + * @return boolean from the value of the given key + */ + public boolean getBoolean(String key) { + return this.dictionary.getValue(key).getJsonBoolean().getBoolean(); + } + + /** + * + * @param key + * @return String from the value of the given key + */ + public String getString(String key) { + return this.dictionary.getValue(key).getJsonString().getString(); + } + + /** + * + * @param key + * @return char from the value of the given key + */ + public char getChar(String key) { + return this.dictionary.getValue(key).getJsonChar().getChar(); + } + + /** + * + * @param key + * @return int from the value of the given key + */ + public int getInt(String key) { + return this.dictionary.getValue(key).getJsonInt().getInt(); + } + + /** + * + * @param key + * @return long from the value of the given key + */ + public long getLong(String key) { + return this.dictionary.getValue(key).getJsonLong().getLong(); + } + + /** + * + * @param key + * @return float from the value of the given key + */ + public float getFloat(String key) { + return this.dictionary.getValue(key).getJsonFloat().getFloat(); + } + + /** + * + * @param key + * @return double from the value of the given key + */ + public double getDouble(String key) { + return this.dictionary.getValue(key).getJsonDouble().getDouble(); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param object + */ + public void update(String key, Object object) {//NOSONAR + if (object == null) { + updateNull(key); + } else { + switch (object.getClass().getName()) { + case "org.nanoboot.powerframework.json.JsonObject": + updateObject(key, (JsonObject) object); + break; + case "org.nanoboot.powerframework.json.JsonArray": + updateArray(key, (JsonArray) object); + break; + case "java.lang.Boolean": + updateBoolean(key, (boolean) object); + break; + case "java.lang.String": + updateString(key, (String) object); + break; + case "java.lang.Character": + updateChar(key, (char) object); + break; + case "java.lang.Integer": + updateInt(key, (int) object); + break; + case "java.lang.Long": + updateLong(key, (long) object); + break; + case "java.lang.Float": + updateFloat(key, (float) object); + break; + case "java.lang.Double": + updateDouble(key, (double) object); + break; + default: + throw new PowerRuntimeException("I can't add the given object as value."); + } + } + } + + /** + * Updates the value of the given key. + * + * @param key + */ + public void updateNull(String key) { + this.dictionary.updateValue(key, new JsonValue()); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateObject(String key, JsonObject value) { + this.dictionary.updateValue(key, new JsonValue(value)); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateArray(String key, JsonArray value) { + this.dictionary.updateValue(key, new JsonValue(value)); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateBoolean(String key, boolean value) { + this.dictionary.updateValue(key, new JsonValue(new JsonBoolean(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateString(String key, String value) { + this.dictionary.updateValue(key, new JsonValue(new JsonString(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateChar(String key, char value) { + this.dictionary.updateValue(key, new JsonValue(new JsonChar(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateInt(String key, int value) { + this.dictionary.updateValue(key, new JsonValue(new JsonInt(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateLong(String key, long value) { + this.dictionary.updateValue(key, new JsonValue(new JsonLong(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateFloat(String key, float value) { + this.dictionary.updateValue(key, new JsonValue(new JsonFloat(value))); + } + + /** + * Updates the value of the given key. + * + * @param key + * @param value + */ + public void updateDouble(String key, double value) { + this.dictionary.updateValue(key, new JsonValue(new JsonDouble(value))); + } + + /** + * Removes the key and its value. + * + * @param key + */ + public void removeJsonValue(String key) { + this.dictionary.removeValue(key); + } + + /** + * + * @return String representation of this json object in minimal version + */ + public String toMinimalString() { + return JsonObjectPrinter.toMinimalString(this); + } + + /** + * + * @return String representation of this json object in pretty print version + */ + public String toPrettyString() { + return JsonObjectPrinter.toPrettyString(this); + } + + /** + * + * @return copy of this json object + */ + public JsonObject getCopy() { + String stringRepresentationOfThisObject = this.toMinimalString(); + return new JsonObject(stringRepresentationOfThisObject); + } + + /** + * + * @return key iterator + */ + public DictionaryKeyIterator getKeyIterator() { + return this.dictionary.getKeyIterator(); + } + + JsonValue getJsonValue(String key) { + return this.dictionary.getValue(key); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java b/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java new file mode 100644 index 0000000..c6f6d67 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java @@ -0,0 +1,110 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.ArrayList; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Is used to create json objects from strings. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonObjectParser extends JsonParser { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private JsonObjectParser() { + //Not meant to be instantiated. + } + + /** + * Parses String to empty json object. + * + * @param jsonObject + * @param stringRepresentationOfJsonObject + * @return json object from parsed String + */ + static JsonObject parseStringToJsonObject(JsonObject jsonObject, String stringRepresentationOfJsonObject) { + if (!jsonObject.isEmpty()) { + throw new PowerRuntimeException("I can't parse. The json object is not empty."); + } + String trimmedStringRepresentationOfJsonObject = stringRepresentationOfJsonObject.trim(); + if (!isStringJsonObject(trimmedStringRepresentationOfJsonObject)) { + throw new PowerRuntimeException("I can't parse. The trimmed String does not start with { or does not end with }"); + } + String collectionsOfValuesOfTheJsonObjectString = deleteTheCharAtTheStartAndTheEnd(trimmedStringRepresentationOfJsonObject); + + fillJsonObjectWithParsedValues(jsonObject, collectionsOfValuesOfTheJsonObjectString); + return jsonObject; + } + + private static boolean isStringJsonObject(String trimmedStringRepresentationOfJsonObject) { + return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonSpecialCharSequences.getObjectLeft()) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonSpecialCharSequences.getObjectRight()); + } + + private static void fillJsonObjectWithParsedValues(JsonObject jsonObject, String collectionsOfValuesOfTheJsonObjectString) { + + ArrayList listOfCommas = getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(collectionsOfValuesOfTheJsonObjectString); + int beginIndex; + int indexOfComma = 0; + for (int i = 0; i < listOfCommas.size(); i++) { + beginIndex = ++indexOfComma; + indexOfComma = listOfCommas.get(i); + if (i == 0) { + beginIndex = 0; + } + String fraction = collectionsOfValuesOfTheJsonObjectString.substring(beginIndex, indexOfComma); + + String key = getKeyFromKeyValue(fraction).trim(); + key = key.substring(1, key.length() - 1); + Object parsedObject = JsonParser.parseStringToValue(getValueFromKeyValue(fraction)); + + jsonObject.add(key, parsedObject); + } + + } + + private static String getKeyFromKeyValue(String string) { + return getKeyOrValueFromKeyValue(string, true); + } + + private static String getValueFromKeyValue(String string) { + return getKeyOrValueFromKeyValue(string, false); + } + + private static String getKeyOrValueFromKeyValue(String string, boolean trueForKeyFalseForValue) { + String stringToReturn; + int intToSaveColonIndex; + for (intToSaveColonIndex = 0; intToSaveColonIndex < string.length(); intToSaveColonIndex++) { + char currentChar = string.charAt(intToSaveColonIndex); + if (currentChar == JsonSpecialCharSequences.getColon()) { + break; + } + } + stringToReturn = trueForKeyFalseForValue ? string.substring(0, intToSaveColonIndex) : string.substring(++intToSaveColonIndex, string.length()); + + return stringToReturn; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java b/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java new file mode 100644 index 0000000..ca3cfa6 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java @@ -0,0 +1,108 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.collections.DictionaryKeyIterator; + +/** + * Used to create String representation of a json object. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonObjectPrinter extends JsonPrinter { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private JsonObjectPrinter() { + //Not meant to be instantiated. + } + + /** + * @param jsonObject + * + * @return String representation of this json object in minimal version + */ + static String toMinimalString(JsonObject jsonObject) { + return toString(jsonObject, false); + } + + /** + * @param jsonObject + * + * @return String representation of this json object in pretty print version + */ + static String toPrettyString(JsonObject jsonObject) { + return toString(jsonObject, true); + } + + /** + * @param jsonObject + * @param printAsPrettyVersion + * + * @return String representation of this json object + */ + static String toString(JsonObject jsonObject, boolean printAsPrettyVersion) { + DictionaryKeyIterator keyIterator = jsonObject.getKeyIterator(); + String value; + String key; + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(JsonSpecialCharSequences.getObjectLeft()); + if (printAsPrettyVersion) { + stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + } + + while (keyIterator.hasNext()) { + key = keyIterator.getNextKey(); + if (printAsPrettyVersion) { + value = jsonObject.getJsonValue(key).toPrettyString(); + } else { + value = jsonObject.getJsonValue(key).toMinimalString(); + } + + if (printAsPrettyVersion) { + stringBuilder.append(JsonSpecialCharSequences.getTab()); + } + stringBuilder.append(JsonSpecialCharSequences.getApostrophe()); + stringBuilder.append(key); + stringBuilder.append(JsonSpecialCharSequences.getApostrophe()); + stringBuilder.append(JsonSpecialCharSequences.getColon()); + + if (printAsPrettyVersion && ((jsonObject.getJsonValue(key).isArray()) || (jsonObject.getJsonValue(key).isObject()))) { + value = addTabOnEveryLineStartWithoutFirst(value); + } + + stringBuilder.append(value); + if (keyIterator.hasNext()) { + stringBuilder.append(","); + } + if (printAsPrettyVersion) { + stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + } + } + stringBuilder.append(JsonSpecialCharSequences.getObjectRight()); + + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonParser.java b/src/main/java/org/nanoboot/powerframework/json/JsonParser.java new file mode 100644 index 0000000..e8e5463 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonParser.java @@ -0,0 +1,176 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Used to parse String representation of JsonObject or JsonArray to their + * object representation. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonParser { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + JsonParser() { + //Not meant to be instantiated. + } + + static char getFirstCharOfTheString(String string) { + return string.charAt(0); + } + + static char getLastCharOfTheString(String string) { + return string.charAt(string.length() - 1); + } + + protected static String deleteTheCharAtTheStartAndTheEnd(String string) { + return string.substring(1, string.length() - 1); + } + + protected static Object parseStringToValue(String stringToParse) {//NOSONAR + String trimmedStringToParse = stringToParse.trim(); + if ("null".equals(trimmedStringToParse)) { + return null; + } + if ("{".equals(trimmedStringToParse.substring(0, 1))) { + return new JsonObject(trimmedStringToParse); + } + if ("[".equals(trimmedStringToParse.substring(0, 1))) { + return new JsonArray(trimmedStringToParse); + } + if ("true".equals(trimmedStringToParse)) { + return true; + } + if ("false".equals(trimmedStringToParse)) { + return false; + } + if ("\"".equals(trimmedStringToParse.substring(0, 1))) { + return parseStringToStringOrChar(trimmedStringToParse); + } + try { + return parseStringToIntOrLongOrFloatOrDouble(trimmedStringToParse); + } catch (Exception e) { + throw new PowerRuntimeException("Something went wrong. I am not able to parse: \"" + stringToParse + "\". " + e); + } + + } + + private static Object parseStringToStringOrChar(String stringToParse) { + String stringWithoutQuotes = deleteTheCharAtTheStartAndTheEnd(stringToParse); + if (stringWithoutQuotes.length() == 1) { + return stringWithoutQuotes.charAt(0); + } else { + return stringWithoutQuotes; + } + } + + private static Object parseStringToIntOrLongOrFloatOrDouble(String stringToParse) { + String intOrLongPattern = "[0-9]*"; + String floatOrDoublePattern = "([0-9]*)\\.([0-9]*)"; + + if (Pattern.matches(floatOrDoublePattern, stringToParse)) { + return parseStringToFloatOrDouble(stringToParse); + } + if (Pattern.matches(intOrLongPattern, stringToParse)) { + return parseStringToIntOrLong(stringToParse); + } + throw new PowerRuntimeException("I am not able to parse: \"" + stringToParse + "\"."); + } + + private static Object parseStringToIntOrLong(String stringToParse) { + try { + return Integer.parseInt(stringToParse); + } catch (Exception e) { + Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e); + try { + return Long.parseLong(stringToParse); + } catch (Exception e2) { + Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e2); + throw new PowerRuntimeException("The number is too long."); + } + } + + } + + private static Object parseStringToFloatOrDouble(String stringToParse) { + int digitsPrecision = 0; + for (int i = 0; i < stringToParse.length(); i++) { + char currentChar = stringToParse.charAt(i); + if (currentChar == '.') { + digitsPrecision = stringToParse.length() - 1 - i; + break; + } + } + if (digitsPrecision > 6) { + try { + return Double.parseDouble(stringToParse); + } catch (Exception e) {//NOSONAR + throw new PowerRuntimeException("The number is too long."); + } + } else { + return Float.parseFloat(stringToParse); + } + } + + protected static ArrayList getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(String collectionsOfValuesOfTheJsonArrayString) { + int nesting = 0; + ArrayList listOfCommas = new ArrayList<>(); + char currentChar; + for (int i = 0; i < collectionsOfValuesOfTheJsonArrayString.length(); i++) { + currentChar = collectionsOfValuesOfTheJsonArrayString.charAt(i); + if ((currentChar == '\"') && (nesting == 0)) { + i++;//NOSONAR + while ('\"' != collectionsOfValuesOfTheJsonArrayString.charAt(i)) { + i++;//NOSONAR + } + } + if ((currentChar == ',') && (nesting == 0)) { + listOfCommas.add(i); + } + if (nestingWillBeIncreased(currentChar)) { + nesting++; + } + if (nestingWillBeDecreased(currentChar)) { + nesting--; + } + } + listOfCommas.add(collectionsOfValuesOfTheJsonArrayString.length()); + return listOfCommas; + } + + private static boolean nestingWillBeIncreased(char charToCheck) { + return (charToCheck == '{') || (charToCheck == '['); + } + + private static boolean nestingWillBeDecreased(char charToCheck) { + return (charToCheck == '}') || (charToCheck == ']'); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java b/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java new file mode 100644 index 0000000..509d913 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java @@ -0,0 +1,47 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Used for JsonObjectPrinter and JsonArrayPrinter to extend. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonPrinter { + + /** + * Constructor + * + * Not meant to be instantiated. + */ + JsonPrinter() { + //Not meant to be instantiated. + } + + static String addTabOnEveryLineStart(String value) { + String result = value.replace("\n", new String("\n" + JsonSpecialCharSequences.getTab())); + return JsonSpecialCharSequences.getTab() + result; + } + + static String addTabOnEveryLineStartWithoutFirst(String value) { + return value.replace("\n", new String("\n" + JsonSpecialCharSequences.getTab())); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java b/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java new file mode 100644 index 0000000..d9825bc --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java @@ -0,0 +1,99 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Used to store char and String constants used to parse or print json objects + * or arrays. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonSpecialCharSequences { + + private static final char OBJECTLEFT = '{'; + private static final char OBJECTRIGHT = '}'; + private static final char ARRAYLEFT = '['; + private static final char ARRAYRIGHT = ']'; + private static final char COMMA = ','; + private static final char COLON = ':'; + private static final char APOSTROPHE = '"'; + private static final String LINEBREAK = "\n"; + private static final String NULL = "null"; + private static final String TRUE = "true"; + private static final String FALSE = "false"; + private static final String TAB = " "; + private static final char SPACE = ' '; + + private JsonSpecialCharSequences() { + } + + static char getObjectLeft() { + return OBJECTLEFT; + } + + static char getObjectRight() { + return OBJECTRIGHT; + } + + static char getArrayLeft() { + return ARRAYLEFT; + } + + static char getArrayRight() { + return ARRAYRIGHT; + } + + static char getComma() { + return COMMA; + } + + static char getColon() { + return COLON; + } + + static char getApostrophe() { + return APOSTROPHE; + } + + static String getLineBreak() { + return LINEBREAK; + } + + static String getNull() { + return NULL; + } + + static String getTrue() { + return TRUE; + } + + static String getFalse() { + return FALSE; + } + + static String getTab() { + return TAB; + } + + static char getSpace() { + return SPACE; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonString.java b/src/main/java/org/nanoboot/powerframework/json/JsonString.java new file mode 100644 index 0000000..5b8bb2c --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonString.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents String json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonString { + + private final String value; + + JsonString(String value) { + this.value = value; + } + + String getString() { + return this.value; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('\"'); + sb.append(getString()); + sb.append('\"'); + return sb.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonValue.java b/src/main/java/org/nanoboot/powerframework/json/JsonValue.java new file mode 100644 index 0000000..4336a4c --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonValue.java @@ -0,0 +1,290 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.PowerRuntimeException; + +/** + * Represents json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class JsonValue { + + private JsonValueType jsonValueType = null; + + private JsonObject jsonObject = null; + private JsonArray jsonArray = null; + private JsonBoolean jsonBoolean = null; + private JsonString jsonString = null; + private JsonChar jsonChar = null; + private JsonInt jsonInt = null; + private JsonLong jsonLong = null; + private JsonFloat jsonFloat = null; + private JsonDouble jsonDouble = null; + + JsonValue() { + this.jsonValueType = JsonValueType.NULL; + } + + JsonValue(JsonObject jsonObject) { + this.jsonValueType = JsonValueType.OBJECT; + this.jsonObject = jsonObject; + } + + JsonValue(JsonArray jsonArray) { + this.jsonValueType = JsonValueType.ARRAY; + this.jsonArray = jsonArray; + } + + JsonValue(JsonBoolean jsonBoolean) { + this.jsonValueType = JsonValueType.BOOLEAN; + this.jsonBoolean = jsonBoolean; + } + + JsonValue(JsonString jsonString) { + this.jsonValueType = JsonValueType.STRING; + this.jsonString = jsonString; + } + + JsonValue(JsonChar jsonLiteral) { + this.jsonValueType = JsonValueType.CHAR; + this.jsonChar = jsonLiteral; + } + + JsonValue(JsonInt jsonInt) { + this.jsonValueType = JsonValueType.INT; + this.jsonInt = jsonInt; + } + + JsonValue(JsonLong jsonLong) { + this.jsonValueType = JsonValueType.LONG; + this.jsonLong = jsonLong; + } + + JsonValue(JsonFloat jsonFloat) { + this.jsonValueType = JsonValueType.FLOAT; + this.jsonFloat = jsonFloat; + } + + JsonValue(JsonDouble jsonDouble) { + this.jsonValueType = JsonValueType.DOUBLE; + this.jsonDouble = jsonDouble; + } + + JsonValueType getJsonValueType() { + return this.jsonValueType; + } + + boolean isNull() { + return this.jsonValueType == JsonValueType.NULL; + } + + boolean isObject() { + return this.jsonValueType == JsonValueType.OBJECT; + } + + boolean isArray() { + return this.jsonValueType == JsonValueType.ARRAY; + } + + boolean isBoolean() { + return this.jsonValueType == JsonValueType.BOOLEAN; + } + + boolean isString() { + return this.jsonValueType == JsonValueType.STRING; + } + + boolean isChar() { + return this.jsonValueType == JsonValueType.CHAR; + } + + boolean isInt() { + return this.jsonValueType == JsonValueType.INT; + } + + boolean isLong() { + return this.jsonValueType == JsonValueType.LONG; + } + + boolean isFloat() { + return this.jsonValueType == JsonValueType.FLOAT; + } + + boolean isDouble() { + return this.jsonValueType == JsonValueType.DOUBLE; + } + + JsonObject getJsonObject() { + if (this.isObject()) { + return this.jsonObject; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonObject"); + } + } + + JsonArray getJsonArray() { + if (this.isArray()) { + return this.jsonArray; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonArray"); + } + } + + JsonBoolean getJsonBoolean() { + if (this.isBoolean()) { + return this.jsonBoolean; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonBoolean"); + } + } + + JsonString getJsonString() { + if (this.isString()) { + return this.jsonString; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonString"); + } + } + + JsonChar getJsonChar() { + if (this.isChar()) { + return this.jsonChar; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonChar"); + } + } + + JsonInt getJsonInt() { + if (this.isInt()) { + return this.jsonInt; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonInt"); + } + } + + JsonLong getJsonLong() { + if (this.isLong()) { + return this.jsonLong; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonLong"); + } + } + + JsonFloat getJsonFloat() { + if (this.isFloat()) { + return this.jsonFloat; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonFloat"); + } + } + + JsonDouble getJsonDouble() { + if (this.isDouble()) { + return this.jsonDouble; + } else { + throw new PowerRuntimeException("This JsonValue has no type JsonDouble"); + } + } + + String toPrettyString() { + return toString(true); + } + + String toMinimalString() { + return toString(false); + } + + String toString(boolean printAsPrettyVersion) {//NOSONAR + switch (this.jsonValueType) { + case NULL: + return JsonSpecialCharSequences.getNull(); + case OBJECT: + if (printAsPrettyVersion) { + return this.getJsonObject().toPrettyString(); + } else { + return this.getJsonObject().toMinimalString(); + } + case ARRAY: + if (printAsPrettyVersion) { + return this.getJsonArray().toPrettyString(); + } else { + return this.getJsonArray().toMinimalString(); + } + case BOOLEAN: + return this.getJsonBoolean().toString(); + + case STRING: + return this.getJsonString().toString(); + case CHAR: + return this.getJsonChar().toString(); + case INT: + return this.getJsonInt().toString(); + case LONG: + return this.getJsonLong().toString(); + case FLOAT: + return this.getJsonFloat().toString(); + case DOUBLE: + return this.getJsonDouble().toString(); + default: + throw new IllegalStateException("Enum error."); + } + } + + Object toObject() {//NOSONAR + switch (jsonValueType) { + case NULL: + return null; + + case OBJECT: + return this.getJsonObject(); + + case ARRAY: + return this.getJsonArray(); + + case BOOLEAN: + return this.getJsonBoolean().getBoolean(); + + case STRING: + return this.getJsonString().getString(); + + case CHAR: + return this.getJsonChar().getChar(); + + case INT: + return this.getJsonInt().getInt(); + + case LONG: + return this.getJsonLong().getLong(); + + case FLOAT: + return this.getJsonFloat().getFloat(); + + case DOUBLE: + return this.getJsonDouble().getDouble(); + + default: + throw new IllegalStateException("Enum error."); + } + + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java b/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java new file mode 100644 index 0000000..3f983cf --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java @@ -0,0 +1,71 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Represents the type of a json value. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public enum JsonValueType { + + /** + * json null + */ + NULL, + /** + * json object + */ + OBJECT, + /** + * json array + */ + ARRAY, + /** + * json boolean + */ + BOOLEAN, + /** + * json String + */ + STRING, + /** + * json char + */ + CHAR, + /** + * json int + */ + INT, + /** + * json long + */ + LONG, + /** + * json float + */ + FLOAT, + /** + * jsou double + */ + DOUBLE; + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java b/src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java new file mode 100644 index 0000000..8216581 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public interface SerializableToJsonObject { + public JsonObject toJsonObject(); + public void fromJsonObject(JsonObject jsonObject); +} diff --git a/src/main/java/org/nanoboot/powerframework/package-info.java b/src/main/java/org/nanoboot/powerframework/package-info.java new file mode 100644 index 0000000..fccdfde --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/package-info.java @@ -0,0 +1,5 @@ +/** + * This package represents Power library. + * Power contains many general-purpose packages and classes suitable to more than one use. + */ +package org.nanoboot.powerframework; diff --git a/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java b/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java new file mode 100644 index 0000000..c56f589 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java @@ -0,0 +1,131 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.pseudorandom; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.datetime.DateTime; +import org.nanoboot.powerframework.datetime.UniversalDateTime; + +/** + * Used to generate pseudo random values. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class PseudoRandomGenerator { + + private final Seed magicSeed; + private final Seed[] seed = new Seed[2]; + private static final PseudoRandomGenerator pseudoRandomGenerator; + + /** + * Constructor + * + * @param magicNumber + * @param dateTime + */ + public PseudoRandomGenerator(long magicNumber, DateTime dateTime) { + this.magicSeed = new Seed(magicNumber); + long year = dateTime.getYear(); + long month = dateTime.getMonth(); + long day = dateTime.getDay(); + long hour = dateTime.getHour(); + long minute = dateTime.getMinute(); + long second = dateTime.getSecond(); + long millisecond = dateTime.getMillisecond(); + this.seed[0] = new Seed(1000 * (minute + day) + millisecond); + this.seed[1] = new Seed(hour * 100000000 + year * 10000 + second * 100 + month); + + } + + static { + UniversalDateTime currentUniversalDateTime = UniversalDateTime.getCurrentUniversalDateTime(); + int currentDay = currentUniversalDateTime.getMonth(); + int currentMillisecond = currentUniversalDateTime.getMillisecond(); + long magicNumber = (long) currentDay * 1000 + (long) currentMillisecond; + pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, currentUniversalDateTime); + } + + /** + * @return static instance + */ + public static PseudoRandomGenerator getInstance() { + return pseudoRandomGenerator; + } + + /** + * + * @param from + * @param to + * @return pseudo random long + */ + public long getLong(long from, long to) { + if (from > to) { + throw new IllegalArgumentException("from is greater than to."); + } + + long[] numberFractions = new long[2]; + + for (int i = 0; i <= 1; i++) { + this.seed[0].jump(); + this.seed[1].jump(); + + if (((magicSeed.getNextNumber()) % 2) == 0) { + this.seed[0].jump(); + } + if (((magicSeed.getNextNumber()) % 2) == 1) { + this.seed[1].jump(); + } + long number1 = seed[0].getNextNumber(); + long number2 = seed[1].getNextNumber(); + if ((magicSeed.getNextNumber() % 2) == 1) { + number2 = number2 * (-1); + } + numberFractions[i] = (Math.abs(number1 + number2)) % 1000000000; + } + long number = (numberFractions[0] * 1000000000) + numberFractions[1]; + + number = (number % (to - from + 1)) + from; + + return number; + } + + /** + * + * @param from + * @param to + * @return pseudo random int + */ + public int getInt(int from, int to) { + if (to > Integer.MAX_VALUE) { + throw new PowerRuntimeException("The parameter \"to\" is too big."); + } + return (int) getLong(from, to); + } + + /** + * + * @return pseudo random boolean + */ + public boolean getBoolean() { + int value = getInt(0, 1); + return value == 1; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java b/src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java new file mode 100644 index 0000000..14f6fe2 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.pseudorandom; + +/** + * Represents seed. Uses linear congruential function. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +class Seed { + + private long currentSeed; + private static final int A = 16807; + private static final int C = 0; + private static final long M = 2147483647; + + Seed(long seed) { + this.currentSeed = seed; + } + + long getNextNumber() { + long number = ((A * currentSeed) + C) % M; + this.currentSeed = number; + return number; + } + + void jump() { + getNextNumber(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java b/src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java new file mode 100644 index 0000000..bea95c4 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java @@ -0,0 +1,176 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; + +/** + * Represents one of 16 colours, or there is no colour. + * + * @author Robert Vokac robertvokac@nanoboot.org + */ +public enum EnumColour { + + /** + * No colour is selected. + */ + NOCOLOUR, + /** + * Light Green + */ + LIGHTGREEN, + /** + * Red + */ + RED, + /** + * Dark Blue + */ + DARKBLUE, + /** + * Yellow + */ + YELLOW, + /** + * Light Blue + */ + LIGHTBLUE, + /** + * Purple + */ + PURPLE, + /** + * Brown + */ + BROWN, + /** + * Pink + */ + PINK, + /** + * Green + */ + GREEN, + /** + * Gold + */ + GOLD, + /** + * Orange + */ + ORANGE, + /** + * White + */ + WHITE, + /** + * Grey + */ + GREY, + /** + * Black + */ + BLACK, + /** + * Blue + */ + BLUE, + /** + * OliveGreen + */ + OLIVEGREEN; + + /** + * + * @return + *

+ * ordinal number of enum colour

+ *

+ * Converts EnumColour to int.

+ */ + public int getNumber() { + return this.ordinal(); + } + + /** + * + * @param number + * @return + */ + public static EnumColour convertNumberToEnumColour(int number) {//NOSONAR + if (!isNumberRepresentationValid(number)) { + throw new PowerRuntimeException("Number you want co convert to EnumColour must be at least 0 and at most 16."); + } + switch (number) { + case 0: + return EnumColour.NOCOLOUR; + case 1: + return EnumColour.LIGHTGREEN; + case 2: + return EnumColour.RED; + case 3: + return EnumColour.DARKBLUE; + case 4: + return EnumColour.YELLOW; + case 5: + return EnumColour.LIGHTBLUE; + case 6: + return EnumColour.PURPLE; + case 7: + return EnumColour.BROWN; + case 8: + return EnumColour.PINK; + case 9: + return EnumColour.GREEN; + case 10: + return EnumColour.GOLD; + case 11: + return EnumColour.ORANGE; + case 12: + return EnumColour.WHITE; + case 13: + return EnumColour.GREY; + case 14: + return EnumColour.BLACK; + case 15: + return EnumColour.BLUE; + case 16: + return EnumColour.OLIVEGREEN; + default: + return null; + + } + } + + private static boolean isNumberRepresentationValid(int number) { + return (number >= 0) && (number <= 16); + } + + /** + * + * @return random EnumColour + */ + public static EnumColour getRandom() { + int i = PseudoRandomGenerator.getInstance().getInt(1, 16); + return EnumColour.convertNumberToEnumColour(i); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java b/src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java new file mode 100644 index 0000000..c956140 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java @@ -0,0 +1,47 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity; + +import javafx.application.Application; +import javafx.stage.Stage; + +/** + * Represents Java FX application. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class JavaFXApplication extends Application { + + void launchJavaFXApplication() { + launch(); + } + + static void startJavaFXApplication() { + JavaFXApplication javaFXApplication = new JavaFXApplication(); + javaFXApplication.launchJavaFXApplication(); + } + + @Override + public void start(final Stage stage) { + Screen.initScreen(); + Simplicity.getSimplicityRunner().run(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/Screen.java b/src/main/java/org/nanoboot/powerframework/simplicity/Screen.java new file mode 100644 index 0000000..9e7d43a --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/Screen.java @@ -0,0 +1,146 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity; + +import javafx.geometry.Rectangle2D; + +/** + * Represents screen. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public final class Screen { + + private static double dpmm; + private static double dpi; + private static double zoom = 100; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Screen() { + //Not meant to be instantiated. + } + + /** + * Initialises screen. + */ + static void initScreen() { + setDpi(); + updateDpmm(); + } + + /** + * Sets dots per inch. + */ + private static void setDpi() { + javafx.stage.Screen primaryScreen = javafx.stage.Screen.getPrimary(); + dpi = primaryScreen.getDpi(); + } + + /** + * @return the resolution (dots per inch) of screen. + */ + public static double getDpi() { + return dpi; + } + + /** + * Sets the length of one millimetre long line in dots (dots per + * millimetre.) + */ + private static void updateDpmm() { + double currentDpi = getDpi(); + if (currentDpi > 0) { + dpmm = currentDpi / 25.4; + } else { + dpmm = 6; + } + dpmm = dpmm * (getZoom() / 100); + } + + /** + * @return the length of one millimetre long line in dots (dots per + * millimetre). + */ + public static double getDpmm() { + return dpmm; + } + + /** + * + * @return zoom + */ + public static double getZoom() { + return zoom; + } + + /** + * + * @param zoom 100% is 100, 100% is default + */ + public static void setZoom(double newZoom) { + zoom = newZoom; + updateDpmm(); + } + + private static Rectangle2D getBounds() { + return javafx.stage.Screen.getPrimary().getBounds(); + } + + /** + * + * @return screen width + */ + public static int getWidth() { + return (int) getBounds().getWidth(); + } + + /** + * + * @return screen height + */ + public static int getHeight() { + return (int) getBounds().getHeight(); + } + + private static Rectangle2D getVisualBounds() { + return javafx.stage.Screen.getPrimary().getVisualBounds(); + } + + /** + * + * @return screen visual width + */ + public static int getVisualWidth() { + return (int) getVisualBounds().getWidth(); + } + + /** + * + * @return screen visual height + */ + public static int getVisualHeight() { + return (int) getVisualBounds().getHeight(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java b/src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java new file mode 100644 index 0000000..14fc4da --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java @@ -0,0 +1,110 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity; + +import javafx.application.Platform; +import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; + +/** + * Represents Simplicity package main class. + * + * @author Robert Vokac robertvokac@nanoboot.org + */ +public final class Simplicity { + + private static SimplicityRunnerI simplicityRunner; + private static WindowColourSkin defaultWindowColourSkin; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Simplicity() { + //Not meant to be instantiated. + Platform.setImplicitExit(false); + } + /** + * This method must be called before using Simplicity. + * + * @param runner This object implements runObjectI interface and its method + * run contains some logic. + * @param defaultWindowColourSkin + */ + public static void startSimplicity(SimplicityRunnerI runner, WindowColourSkin defaultWindowColourSkin) { + Simplicity.setDefaultWindowColourSkin(defaultWindowColourSkin); + simplicityRunner = runner; + JavaFXApplication.startJavaFXApplication(); + } + + /** + * Stops Simplicity. + */ + public static void stopSimplicity() { + Platform.exit(); + } + + /** + * + * @return Simplicity runner + */ + public static SimplicityRunnerI getSimplicityRunner() { + return simplicityRunner; + } + + /** + * Returns count of dots per one millimeter on the screen. + * + * @return count of dots per one millimeter on the screen + */ + public static double getDpmm() { + return Screen.getDpmm(); + } + + /** + * + * @return default window colour skin + */ + public static WindowColourSkin getDefaultWindowColourSkin() { + return Simplicity.defaultWindowColourSkin; + } + + /** + * + * @param windowColourSkin + */ + public static void setDefaultWindowColourSkin(WindowColourSkin windowColourSkin) { + Simplicity.defaultWindowColourSkin = windowColourSkin; + } + + public static String getInformation() { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("\ndefaultWindowColourSkin: ").append(Simplicity.getDefaultWindowColourSkin()); + stringBuilder.append("\ndpmm: ").append(Simplicity.getDpmm()); + stringBuilder.append("\nzoom: ").append(Screen.getZoom()); + stringBuilder.append("\ndpi: ").append(Screen.getDpi()); + stringBuilder.append("\nheight: ").append(Screen.getHeight()); + stringBuilder.append("\nwidth: ").append(Screen.getWidth()); + stringBuilder.append("\nvisual height: ").append(Screen.getVisualHeight()); + stringBuilder.append("\nvisual width: ").append(Screen.getVisualWidth()); + return stringBuilder.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java b/src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java new file mode 100644 index 0000000..7fdf9a8 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity; + +/** + * Represents entry point for Simplicity application. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +@FunctionalInterface +public interface SimplicityRunnerI { + + /** + * Contains logic called after Simplicity was started. + */ + public void run(); + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java new file mode 100644 index 0000000..ac2c7b0 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java @@ -0,0 +1,70 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.boxes; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.controls.Button; +import javafx.scene.paint.Color; +import javafx.scene.shape.Rectangle; +import javafx.scene.transform.Rotate; + +/** + * Represents a alert box- a window used to alarm user. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public class AlertBox extends Box { + + private AlertBox(String titleText, String text) { + super(titleText, text); + } + + /** + * + * @param windowColourSkin + * @param titleText + * @param text + */ + public static void showBox(String titleText, String text) { + AlertBox alertBox = new AlertBox(titleText, text); + alertBox.showAndWait(); + } + + void init() { + circle.setFill(Color.rgb(237, 103, 103)); + Rectangle rectangle1 = new Rectangle(2 * Simplicity.getDpmm(), 8 * Simplicity.getDpmm()); + Rectangle rectangle2 = new Rectangle(2 * Simplicity.getDpmm(), 8 * Simplicity.getDpmm()); + Rotate rotate45 = new Rotate(45, 1.0 * Simplicity.getDpmm(), 4.0 * Simplicity.getDpmm()); + Rotate rotateMinus45 = new Rotate(-45, 1.0 * Simplicity.getDpmm(), 4.0 * Simplicity.getDpmm()); + rectangle1.getTransforms().addAll(rotate45); + rectangle2.getTransforms().addAll(rotateMinus45); + this.icon.getChildren().addAll(rectangle1, rectangle2); + + rectangle1.setFill(Color.rgb(238, 238, 238)); + rectangle2.setFill(Color.rgb(238, 238, 238)); + + Button okButton = new Button("OK"); + + this.placeForButtons.getChildren().add(okButton); + okButton.setMaxWidth(20 * Simplicity.getDpmm()); + okButton.setOnAction(this::handleOKButtonAction); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java new file mode 100644 index 0000000..f1cef56 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java @@ -0,0 +1,105 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.boxes; + +import org.nanoboot.powerframework.simplicity.window.SLayout; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.Window; +import javafx.event.ActionEvent; +import javafx.geometry.Pos; +import javafx.geometry.VPos; +import javafx.scene.layout.ColumnConstraints; +import javafx.scene.layout.RowConstraints; +import javafx.scene.layout.StackPane; +import javafx.scene.shape.Circle; +import javafx.scene.text.Font; +import javafx.scene.text.Text; +import javafx.stage.Modality; + +/** + * Represents a box- a window used to give information to user. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +abstract class Box extends Window { + + protected String titleText; + protected String text; + protected StackPane icon = new StackPane(); + protected StackPane icon2 = new StackPane(); + protected SLayout gridLayout = new SLayout(); + Circle circle = new Circle(6 * Simplicity.getDpmm()); + protected StackPane placeForButtons = new StackPane(); + + Box(String titleText, String text) { + initModality(Modality.APPLICATION_MODAL); + this.setWindowTitle(titleText); + this.text = text; + + this.setCloseable(false); + this.showOnlyTheCloseButton(); + + RowConstraints rc2 = new RowConstraints(); + rc2.setMinHeight(12 * Simplicity.getDpmm()); + rc2.setMaxHeight(12 * Simplicity.getDpmm()); + rc2.setValignment(VPos.CENTER); + ColumnConstraints cc1 = new ColumnConstraints(); + cc1.setMinWidth(12 * Simplicity.getDpmm()); + cc1.setMaxWidth(12 * Simplicity.getDpmm()); + + ColumnConstraints cc2 = new ColumnConstraints(); + cc2.setMinWidth(text.length() * 4 * Simplicity.getDpmm()); + cc2.setMaxWidth(text.length() * 4 * Simplicity.getDpmm()); + + this.gridLayout.getRowConstraints().addAll(rc2, this.gridLayout.getDataRowConstraint()); + this.gridLayout.getColumnConstraints().addAll(cc1, cc2); + + this.icon.getChildren().add(circle); + + this.gridLayout.add(icon, 0, 0); + + Text newText = new Text(text); + newText.setFont(Font.font(3 * Simplicity.getDpmm())); + newText.setText(text); + this.gridLayout.add(newText, 1, 0); + this.gridLayout.add(this.placeForButtons, 0, 1, 2, 1); + this.placeForButtons.setAlignment(Pos.CENTER); + this.applicationArea.getChildren().add(gridLayout); + + this.setHeight(4.5 * Simplicity.getDpmm() + 3 * 3 * Simplicity.getDpmm() + 12 * Simplicity.getDpmm() + 6 * Simplicity.getDpmm() + 2 / 3 * Simplicity.getDpmm()); + this.setWidth(text.length() * 2 * Simplicity.getDpmm() + 2 / 3 * Simplicity.getDpmm() + 9 * Simplicity.getDpmm() + 16 * Simplicity.getDpmm()); + + this.init(); + } + + abstract void init(); + + protected void handleOKButtonAction(ActionEvent event) { + // Button was clicked, do something... + + this.close(); + } + + @Override + public void initAreaForUserInteraction() { + + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java new file mode 100644 index 0000000..121fdd3 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java @@ -0,0 +1,70 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.boxes; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.controls.Button; +import javafx.geometry.Pos; +import javafx.scene.paint.Color; +import javafx.scene.shape.Rectangle; + +/** + * Represents a message box- a window used to inform user about something. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public class MessageBox extends Box { + + private MessageBox(String titleText, String text) { + super(titleText, text); + } + + /** + * + * @param windowColourSkin + * @param titleText + * @param text + */ + public static void showBox(String titleText, String text) { + MessageBox messageBox = new MessageBox(titleText, text); + messageBox.showAndWait(); + } + + void init() { + circle.setFill(Color.rgb(114, 159, 207)); + Rectangle rectangle1 = new Rectangle(2 * Simplicity.getDpmm(), 5 * Simplicity.getDpmm()); + Rectangle rectangle2 = new Rectangle(2 * Simplicity.getDpmm(), 2 * Simplicity.getDpmm()); + this.icon2.getChildren().addAll(rectangle1, rectangle2); + this.icon.getChildren().add(icon2); + + this.icon2.setAlignment(rectangle1, Pos.BOTTOM_CENTER); + this.icon2.setAlignment(rectangle2, Pos.TOP_CENTER); + this.icon2.setMaxHeight(8 * Simplicity.getDpmm()); + rectangle1.setFill(Color.rgb(238, 238, 238)); + + rectangle2.setFill(Color.rgb(238, 238, 238)); + Button okButton = new Button("OK"); + + this.placeForButtons.getChildren().add(okButton); + okButton.setMaxWidth(20 * Simplicity.getDpmm()); + okButton.setOnAction(this::handleOKButtonAction); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java new file mode 100644 index 0000000..9432ce7 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java @@ -0,0 +1,189 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import java.util.ArrayList; +import java.util.List; +import javafx.geometry.Insets; +import javafx.geometry.VPos; +import javafx.scene.Node; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.ColumnConstraints; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.RowConstraints; +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.simplicity.Simplicity; + +/** + * + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class CellLayout extends AnchorPane { + + private static final RowConstraints dataRowConstraint = new RowConstraints(); + private static final String PERCENT = "%"; + private static final String MM = "mm"; + + private final GridPane gridPane = new GridPane(); + + static { + dataRowConstraint.setMinHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setMaxHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setValignment(VPos.CENTER); + } + + private final int rows; + private final int columns; + + /** + * + * @param rows + * @param columns + * @param columnConstraintsString + */ + public CellLayout(int columns, int rows, String columnConstraintsString) { + this.getChildren().add(gridPane); + + AnchorPane.setTopAnchor(gridPane, 0d); + AnchorPane.setRightAnchor(gridPane, 0d); + AnchorPane.setBottomAnchor(gridPane, 0d); + AnchorPane.setLeftAnchor(gridPane, 0d); + + this.columns = columns; + setColumnConstraints(columnConstraintsString); + + this.rows = rows; + setRowConstraints(); + + this.setSpacing(true); + this.setWidth(Double.MAX_VALUE); + } + + private void setRowConstraints() { + List list = new ArrayList(); + for (int i = 1; i <= rows; i++) { + list.add(dataRowConstraint); + } + gridPane.getRowConstraints().addAll(list); + } + + private void setColumnConstraints(String columnConstraintsString) { + String[] columnConstraint = columnConstraintsString.split("\\s+"); + List list = new ArrayList(); + for (String element : columnConstraint) { + int number; + ColumnConstraints tempColumnConstraints = new ColumnConstraints(); + if (element.endsWith(PERCENT)) { + number = Integer.parseInt(element.substring(0, element.length() - 1)); + tempColumnConstraints.setPercentWidth(number); + } else if (element.endsWith(MM)) { + number = Integer.parseInt(element.substring(0, element.length() - 2)); + double mmLenght = number * Simplicity.getDpmm(); + tempColumnConstraints.setMaxWidth(mmLenght); + tempColumnConstraints.setMinWidth(mmLenght); + } else { + throw new PowerRuntimeException("Column constraint string is not valid. " + element + " is not valid."); + } + list.add(tempColumnConstraints); + } + gridPane.getColumnConstraints().addAll(list); + } + + /** + * + * @param node + * @param column from 1 + * @param row from 1 + */ + public void addNode(Node node, int column, int row) { + gridPane.add(node, column - 1, row - 1); + } + + /** + * + * @param node + * @param column from 1 + * @param row from 1 + * @param columnSpan + * @param rowSpan + */ + public void addNode(Node node, int column, int row, int columnSpan, int rowSpan) { + gridPane.add(node, column - 1, row - 1, columnSpan, rowSpan); + } + + /** + * Adds collection of nodes. + * + * @param row starting from 1 + * @param nodes + */ + public void addNodes(int row, Node... nodes) { + gridPane.addRow(row - 1, nodes); + } + + /** + * + * @param value + */ + public void setSpacing(boolean value) { + if (value) { + gridPane.setVgap(3 * Simplicity.getDpmm()); + gridPane.setHgap(3 * Simplicity.getDpmm()); + gridPane.setPadding(new Insets(3 * Simplicity.getDpmm())); + } else { + gridPane.setVgap(0); + gridPane.setHgap(0); + gridPane.setPadding(Insets.EMPTY); + } + } + + /** + * + * @return + */ + public int getRows() { + return rows; + } + + /** + * + * @return + */ + public int getColumns() { + return columns; + } + + /** + * + * @param col + * @param row + * @return + */ + public Node getNodeFromGridPane(int col, int row) { + for (Node node : this.getChildren()) { + if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { + return node; + } + } + return null; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java new file mode 100644 index 0000000..2541454 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +/** + * Colour variants of a window colour skin. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public enum ColourVariant { + + /** + * light + * + */ + LIGHT, + /** + * dark + */ + DARK; +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java new file mode 100644 index 0000000..e50c12c --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java @@ -0,0 +1,104 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import static javafx.scene.layout.HBox.setHgrow; +import javafx.scene.layout.Priority; +import javafx.scene.layout.StackPane; +import javafx.scene.text.Font; +import javafx.scene.text.Text; + +/** + * Represents the part of window, where is the window title placed and is used + * to move window + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class MoveableArea extends StackPane { + + private final Text titleText = new Text(""); + private final Window window; + private boolean moveable; + + /** + * Constructor + * + * @param window + */ + public MoveableArea(Window window) { + this.window = window; + getChildren().add(titleText); + setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + setAlignment(Pos.CENTER_LEFT); + + setHgrow(this, Priority.ALWAYS); + + titleText.setFont(Font.font(Simplicity.getDpmm() * 3)); + titleText.setFill(Simplicity.getDefaultWindowColourSkin().getColourForText(ColourVariant.DARK)); + titleText.setScaleX(1.2); + setPadding(new Insets(0, 0, 0, Simplicity.getDpmm())); + this.setCanBeMoved(true); + } + + /** + * + * @param value + */ + public void setCanBeMoved(boolean value) { + moveable = value; + if (value) { + setOnMousePressed(window::handleMovingWindowStarted); + setOnMouseDragged(window::handleMovingWindowEnded); + } else { + setOnMousePressed(null); + setOnMouseDragged(null); + } + + } + + /** + * + * @return true, if this object is able to move window, otherwise false + */ + public boolean canBeMoved() { + return this.moveable; + + } + + /** + * + * @param title + */ + public void setWindowTitle(String title) { + titleText.setText(" " + title); + } + + /** + * + * @return window title + */ + public String getWindowTitle() { + return this.titleText.getText(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java new file mode 100644 index 0000000..87cd570 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java @@ -0,0 +1,54 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import javafx.scene.layout.GridPane; +import org.nanoboot.powerframework.simplicity.Simplicity; + +/** + * Represents place used to resize window. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public class ResizingGrid extends GridPane { + + /** + * + * @param windowColourSkin + */ + public ResizingGrid() { + this.setMaxHeight(Simplicity.getDpmm() * 6); + this.setMaxWidth(Simplicity.getDpmm() * 6); + this.add(new ResizingGridRectangle(), 3, 0); + this.add(new ResizingGridRectangle(), 2, 1); + this.add(new ResizingGridRectangle(), 3, 1); + this.add(new ResizingGridRectangle(), 1, 2); + this.add(new ResizingGridRectangle(), 2, 2); + this.add(new ResizingGridRectangle(), 3, 2); + this.add(new ResizingGridRectangle(), 0, 3); + this.add(new ResizingGridRectangle(), 1, 3); + this.add(new ResizingGridRectangle(), 2, 3); + this.add(new ResizingGridRectangle(), 3, 3); + this.setStyle("-fx-padding: 0;-fx-insets: 0;"); + this.setHgap(Simplicity.getDpmm() / 2); + this.setVgap(Simplicity.getDpmm() / 2); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java new file mode 100644 index 0000000..7b0cb52 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import javafx.scene.shape.Rectangle; +import org.nanoboot.powerframework.simplicity.Simplicity; + +/** + * Represents button used to resize the window. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public class ResizingGridRectangle extends Rectangle { + + /** + * Constructor + */ + public ResizingGridRectangle() { + this.setFill(Simplicity.getDefaultWindowColourSkin().getColour(ColourVariant.DARK)); + this.setHeight(Simplicity.getDpmm()); + this.setWidth(Simplicity.getDpmm()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java new file mode 100644 index 0000000..951666a --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java @@ -0,0 +1,89 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import javafx.geometry.Insets; +import javafx.geometry.VPos; +import javafx.scene.Node; +import javafx.scene.layout.GridPane; +import javafx.scene.layout.RowConstraints; + +/** + * Represents a layout. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SLayout extends GridPane { + + private final RowConstraints dataRowConstraint = new RowConstraints(); + + /** + * Constructor + */ + public SLayout() { + this.setSpacing(true); + + dataRowConstraint.setMinHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setMaxHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setValignment(VPos.CENTER); + } + + /** + * + * @param value + */ + public void setSpacing(boolean value) { + if (value) { + this.setVgap(3 * Simplicity.getDpmm()); + this.setHgap(3 * Simplicity.getDpmm()); + this.setPadding(new Insets(3 * Simplicity.getDpmm())); + } else { + this.setVgap(0); + this.setHgap(0); + this.setPadding(Insets.EMPTY); + } + } + + /** + * + * @return + */ + public RowConstraints getDataRowConstraint() { + return this.dataRowConstraint; + } + + /** + * + * @param gridPane + * @param col + * @param row + * @return + */ + public Node getNodeFromGridPane(GridPane gridPane, int col, int row) { + for (Node node : gridPane.getChildren()) { + if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { + return node; + } + } + return null; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java new file mode 100644 index 0000000..3bb3933 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java @@ -0,0 +1,192 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.titlebuttons.CloseButton; +import org.nanoboot.powerframework.simplicity.window.titlebuttons.MaximizeRestoreButton; +import org.nanoboot.powerframework.simplicity.window.titlebuttons.MinimizeButton; +import javafx.geometry.Insets; +import javafx.scene.layout.HBox; + +/** + * Represents title bar of a window. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TitleBar extends HBox { + + /** + * title bar height in millimeters. + */ + private static final double TITLEBARHEIGHT = 4.5; + /** + * Space between buttons in millimeters. + */ + private final Insets spaceBeforeButtons = new Insets(0, 0, 0, Simplicity.getDpmm() * 1.5); + /** + * StackPane for title bar icon. + */ + private final TitleIcon titleIcon; + /** + * Part of title bar with title of the window. This part is used to move + * window. + */ + private final MoveableArea moveableArea; + + /** + * Button used to minimize Window. + */ + private final MinimizeButton minimizeButton; + /** + * Button used to restore or maximize Window. + */ + private final MaximizeRestoreButton maximizeRestoreButton; + /** + * Button used to close Window. + */ + private final CloseButton closeButton; + private boolean onlyTheCloseButtonIsShowed = false; + + /** + * + * @param windowColourSkin + * @param window + */ + public TitleBar(Window window) { + WindowColourSkin tempWindowColourSkin = Simplicity.getDefaultWindowColourSkin(); + setFillHeight(true); + setMinHeight(Simplicity.getDpmm() * TITLEBARHEIGHT); + setMaxHeight(Simplicity.getDpmm() * TITLEBARHEIGHT); + titleIcon = new TitleIcon(); + moveableArea = new MoveableArea(window); + + minimizeButton = new MinimizeButton(tempWindowColourSkin, window); + maximizeRestoreButton = new MaximizeRestoreButton(tempWindowColourSkin, window); + + closeButton = new CloseButton(tempWindowColourSkin, window); + + getChildren().addAll(titleIcon, moveableArea, minimizeButton, maximizeRestoreButton, closeButton); + + setMargin(minimizeButton, spaceBeforeButtons); + setMargin(maximizeRestoreButton, spaceBeforeButtons); + + setMargin(closeButton, spaceBeforeButtons); + } + + /** + * + * @param path + */ + public void setIcon(String path) { + this.titleIcon.setIcon(path); + } + + /** + * + * @param value + */ + public void setCanBeMoved(boolean value) { + this.moveableArea.setCanBeMoved(value); + } + + /** + * + * @return boolean value + */ + public boolean canBeMoved() { + return this.moveableArea.canBeMoved(); + } + + /** + * + * @param title + */ + public void setWindowTitle(String title) { + this.moveableArea.setWindowTitle(title); + } + + /** + * + * @return title + */ + public String getWindowTitle() { + return this.moveableArea.getWindowTitle(); + } + + /** + * Sets maximize/restore button restored. + */ + public void setMaximizeRestoreButtonRestored() { + this.maximizeRestoreButton.setMaximizeRestoreButtonRestored(); + + } + + /** + * Sets maximize/restore button maximized. + */ + public void setMaximizeRestoreButtonMaximized() { + this.maximizeRestoreButton.setMaximizeRestoreButtonMaximized(); + + } + + /** + * Shows only the close button. + */ + public void showOnlyTheCloseButton() { + + if (!this.isShowedOnlyTheCloseButton()) { + getChildren().removeAll(minimizeButton, maximizeRestoreButton); + } + + this.onlyTheCloseButtonIsShowed = true; + } + + /** + * + * @return boolean value + */ + public boolean isShowedOnlyTheCloseButton() { + return onlyTheCloseButtonIsShowed; + } + + /** + * Shows all title buttons. + */ + public void showAllTitleButtons() { + + if (this.isShowedOnlyTheCloseButton()) { + getChildren().addAll(minimizeButton, maximizeRestoreButton); + setMargin(minimizeButton, spaceBeforeButtons); + setMargin(maximizeRestoreButton, spaceBeforeButtons); + } + + this.onlyTheCloseButtonIsShowed = false; + } + + /** + * + * @return + */ + public boolean areShowedAllTitleButtons() { + return !onlyTheCloseButtonIsShowed; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java new file mode 100644 index 0000000..0bc0412 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.StackPane; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TitleIcon extends StackPane { + + /** + * Title bar icon image. + */ + private final ImageView imageView = new ImageView(); + private static final double TITLEICONHEIGHT = 4.5; + + /** + * Constructor + * + * @param windowColourSkin + */ + TitleIcon() { + setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + imageView.setFitWidth(Simplicity.getDpmm() * TITLEICONHEIGHT); + imageView.setFitHeight(Simplicity.getDpmm() * TITLEICONHEIGHT); + imageView.setPreserveRatio(true); + imageView.setSmooth(true); + imageView.setCache(true); + getChildren().add(imageView); + } + + /** + * + * @param path + */ + public void setIcon(String path) { + Image image = new Image(path); + imageView.setImage(image); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java new file mode 100644 index 0000000..5ec7da5 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java @@ -0,0 +1,417 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import static java.lang.Thread.sleep; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.nanoboot.powerframework.simplicity.Simplicity; +import javafx.event.EventHandler; +import javafx.geometry.Pos; +import javafx.scene.Scene; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.VBox; +import javafx.scene.layout.Priority; +import javafx.scene.layout.StackPane; +import javafx.stage.Stage; +import javafx.stage.StageStyle; +import javafx.geometry.Rectangle2D; +import javafx.stage.Screen; +import javafx.stage.WindowEvent; + +/** + * Represents window. Window is place for everything player sees. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public abstract class Window extends Stage { + + private VBox windowVBox; + private TitleBar titleBar; + protected StackPane applicationArea = new StackPane(); + private ResizingGrid resizingGrid = null; + + private double dragOffsetXForMoving; + private double dragOffsetYXForMoving; + private boolean resizeable = false; + private boolean closeable = true; + private boolean showedTitleBar = false; + + private WindowSizeMode windowSizeMode; + + private int restoredWindowMinX; + private int restoredWindowMinY; + private int restoredWindowWidth; + private int restoredWindowHeight; + + /** + * Constructor + */ + public Window() { + + this.centerOnScreen(); + titleBar = new TitleBar(this); + + initWindowVBox(); + switchToRestored(); + + setDefaultSizeAndPosition(); + + initAreaForUserInteraction(); + setValuesForRestoredWindow(); + if (this.canBeResized()) { + this.resizingGrid.toFront(); + } + } + + private void setDefaultSizeAndPosition() { + setWidth((org.nanoboot.powerframework.simplicity.Screen.getVisualWidth()) / 2); + setHeight((org.nanoboot.powerframework.simplicity.Screen.getVisualHeight()) / 8 * 6); + setX((org.nanoboot.powerframework.simplicity.Screen.getVisualWidth() - this.getWidth()) / 2); + setY((org.nanoboot.powerframework.simplicity.Screen.getVisualHeight() - this.getHeight()) / 2); + } + + private void initWindowVBox() { + this.setOnCloseRequest(new EventHandler() { + @Override + public void handle(final WindowEvent event) { + + event.consume(); + } + }); + this.initStyle(StageStyle.TRANSPARENT); + windowVBox = new VBox(); + windowVBox.setFillWidth(true); + this.setScene(new Scene(windowVBox, 400, 300)); + + this.setFullScreenExitHint(""); + windowVBox.setVgrow(applicationArea, Priority.ALWAYS); + windowVBox.getChildren().addAll(applicationArea); + } + + private void setValuesForRestoredWindow() { + + this.restoredWindowMinX = (int) this.getX(); + this.restoredWindowMinY = (int) this.getY(); + this.restoredWindowWidth = (int) this.getWidth(); + this.restoredWindowHeight = (int) this.getHeight(); + } + + /** + * + * @param path + */ + public void setIcon(String path) { + this.titleBar.setIcon(path); + } + + private void setCanBeMoved(boolean value) { + this.titleBar.setCanBeMoved(value); + } + + /** + * + * @param title + */ + public void setWindowTitle(String title) { + this.titleBar.setWindowTitle(title); + this.setTitle(title); + } + + /** + * + * @return title + */ + public String getWindowTitle() { + return this.titleBar.getWindowTitle(); + } + + private void setMaximizeRestoreButtonRestored() { + this.titleBar.setMaximizeRestoreButtonRestored(); + + } + + private void setMaximizeRestoreButtonMaximized() { + this.titleBar.setMaximizeRestoreButtonMaximized(); + + } + + /** + * only the close button is shown + */ + public void showOnlyTheCloseButton() { + this.titleBar.showOnlyTheCloseButton(); + this.setResizeable(false); + } + + /** + * + * @return boolean value + */ + public boolean isShowedOnlyTheCloseButton() { + return this.titleBar.isShowedOnlyTheCloseButton(); + } + + /** + * show all title buttons + */ + public void showAllTitleButtons() { + this.titleBar.showAllTitleButtons(); + this.setResizeable(true); + } + + /** + * + * @return boolean value + */ + public boolean areShowedAllTitleButtons() { + return this.titleBar.areShowedAllTitleButtons(); + } + + private void setResizeable(boolean value) { + if (this.resizeable != value) { + this.resizeable = value; + if (value) { + resizingGrid = new ResizingGrid(); + resizingGrid.setOnMouseDragged(this::handleResizeWindowAction); + applicationArea.getChildren().add(resizingGrid); + applicationArea.setAlignment(resizingGrid, Pos.BOTTOM_RIGHT); + } else { + this.applicationArea.getChildren().remove(this.resizingGrid); + this.resizingGrid = null; + } + } + + } + + private boolean canBeResized() { + return this.resizeable; + } + + /** + * Window's size and position can be changed. + */ + public void switchToRestored() { + this.setFullScreen(false); + this.windowSizeMode = WindowSizeMode.RESTORED; + setX(this.restoredWindowMinX); + setY(this.restoredWindowMinY); + setWidth(restoredWindowWidth); + setHeight(restoredWindowHeight); + + this.setResizeable(true); + this.setBorder(true); + this.showTitleBar(true); + this.setCanBeMoved(true); + this.setMaximizeRestoreButtonMaximized(); + this.setMaximized(false); + newTaskResizingWindow(); + } + + /** + * Window's size and position can not be changed. + */ + public void switchToMaximized() { + this.setFullScreen(false); + + this.windowSizeMode = WindowSizeMode.MAXIMIZED; + this.setValuesForRestoredWindow(); + this.setResizeable(false); + this.setBorder(false); + this.showTitleBar(true); + + Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); + setX(bounds.getMinX()); + setY(bounds.getMinY()); + setWidth(bounds.getWidth()); + setHeight(bounds.getHeight()); + + this.setCanBeMoved(false); + this.setMaximizeRestoreButtonRestored(); + newTaskResizingWindow(); + } + + /** + ** Window's size and position can not be changed. The size is the biggest + */ + public void switchToFullScreen() { + this.windowSizeMode = WindowSizeMode.FULLSCREEN; + if (this.canBeResized()) { + this.setValuesForRestoredWindow(); + } + this.setResizeable(false); + this.setBorder(false); + this.showTitleBar(false); + this.setFullScreen(true); + Rectangle2D bounds = Screen.getPrimary().getBounds(); + setX(bounds.getMinX()); + setY(bounds.getMinY()); + setWidth(bounds.getWidth()); + setHeight(bounds.getHeight()); + newTaskResizingWindow(); + } + + private void newTaskResizingWindow() { + Thread thread = new Thread(() -> { + try { + sleep(100); + } catch (InterruptedException ex) { + Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex); + Thread.currentThread().interrupt(); + } + for(int i=0;i<=10;i++) + {try { + sleep(50); + } catch (InterruptedException ex) { + Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex); + Thread.currentThread().interrupt(); + } + this.onResizingWindow();} + + }); + thread.setDaemon(true); + thread.start(); + } + + public WindowSizeMode getWindowSizeMode() { + return this.windowSizeMode; + } + + private void setBorder(boolean value) { + if (value) { + windowVBox.setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" + + "-fx-border-width: " + Simplicity.getDpmm() / 3 + ";" + + "-fx-border-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + } else { + windowVBox.setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" + + "-fx-border-width: 0;"); + } + + } + + private void showTitleBar(boolean value) { + if (value != showedTitleBar) { + this.showedTitleBar = value; + if (value) { + windowVBox.getChildren().addAll(titleBar); + titleBar.toBack(); + } else { + this.windowVBox.getChildren().removeAll(this.titleBar); + } + } + } + + /** + * + * @param e + */ + public void handleMovingWindowStarted(MouseEvent e) { + this.dragOffsetXForMoving = e.getScreenX() - this.getX(); + this.dragOffsetYXForMoving = e.getScreenY() - this.getY(); + } + + /** + * + * @param e + */ + public void handleMovingWindowEnded(MouseEvent e) { + this.setX(e.getScreenX() - this.dragOffsetXForMoving); + this.setY(e.getScreenY() - this.dragOffsetYXForMoving); + this.onMovingWindow(); + } + + /** + * + * @param event + */ + public void handleMinimizeButtonAction(MouseEvent event) { + this.setIconified(true); + } + + /** + * + * @param event + */ + public void handleMaximizeRestoreButtonAction(MouseEvent event) { + if (this.windowSizeMode == WindowSizeMode.RESTORED) { + this.switchToMaximized(); + } else if (this.windowSizeMode == WindowSizeMode.MAXIMIZED) { + this.switchToRestored(); + } + } + + /** + * + * @param value + */ + public void setCloseable(boolean value) { + this.closeable = value; + } + + /** + * + * @return + */ + public boolean isCloseable() { + return this.closeable; + } + + /** + * + * @param event + */ + public void handleCloseButtonAction(MouseEvent event) { + if (this.closeable) { + this.onClosingWindow(); + super.close(); + } + } + + protected void onClosingWindow() { + } + + private void handleResizeWindowAction(MouseEvent event) {//NOSONAR + double newX = event.getScreenX() - this.getX() + 13; + double newY = event.getScreenY() - this.getY() + 10; + + if (newX > getMinWidth()) { + this.setWidth(newX); + } else { + this.setWidth(getMinWidth()); + } + + if (newY > getMinHeight()) { + this.setHeight(newY); + } else { + this.setHeight(getMinHeight()); + } + this.onResizingWindow(); + } + + protected void onResizingWindow() { + } + + protected void onMovingWindow() { + } + + protected abstract void initAreaForUserInteraction(); + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java new file mode 100644 index 0000000..b67aaff --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java @@ -0,0 +1,188 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +import org.nanoboot.powerframework.simplicity.EnumColour; +import javafx.scene.paint.Color; + +/** + * Represents colour skin of Window. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class WindowColourSkin { + + /** + * 16 variants of colour for window skin. + * + * colour[0] is used for light colours colour[1] is used for light colours + */ + private static final Color[][] colour = new Color[2][17]; + + /** + * Filling colour variable. + */ + static { + colour[0][1] = Color.rgb(142, 255, 142); + colour[1][1] = Color.rgb(0, 255, 0); + colour[0][2] = Color.rgb(255, 105, 105); + colour[1][2] = Color.rgb(255, 71, 71); + colour[0][3] = Color.rgb(43, 128, 213); + colour[1][3] = Color.rgb(0, 70, 255); + colour[0][4] = Color.rgb(255, 255, 164); + colour[1][4] = Color.rgb(244, 244, 0); + colour[0][5] = Color.rgb(98, 255, 255); + colour[1][5] = Color.rgb(0, 225, 225); + colour[0][6] = Color.rgb(178, 113, 178); + colour[1][6] = Color.rgb(139, 73, 139); + colour[0][7] = Color.rgb(133, 84, 57); + colour[1][7] = Color.rgb(107, 37, 4); + colour[0][8] = Color.rgb(255, 218, 236); + colour[1][8] = Color.rgb(255, 171, 213); + colour[0][9] = Color.rgb(0, 204, 0); + colour[1][9] = Color.rgb(0, 153, 0); + colour[0][10] = Color.rgb(255, 228, 119); + colour[1][10] = Color.rgb(255, 185, 0); + colour[0][11] = Color.rgb(253, 154, 73); + colour[1][11] = Color.rgb(244, 128, 32); + colour[0][12] = Color.rgb(255, 255, 255); + colour[1][12] = Color.rgb(238, 238, 238); + colour[0][13] = Color.rgb(204, 204, 204); + colour[1][13] = Color.rgb(178, 178, 178); + colour[0][14] = Color.rgb(32, 32, 32); + colour[1][14] = Color.rgb(0, 0, 0); + colour[0][15] = Color.rgb(111, 183, 255); + colour[1][15] = Color.rgb(0, 128, 255); + colour[0][16] = Color.rgb(108, 119, 46); + colour[1][16] = Color.rgb(75, 83, 32); + + } + private EnumColour enumColour; + + /** + * + * @param colour + */ + public WindowColourSkin(EnumColour colour) { + this.enumColour = colour; + } + + /** + * + * @param colourVariant + * @return + */ + public Color getColour(ColourVariant colourVariant) { + if (colourVariant == ColourVariant.LIGHT) { + return colour[0][enumColour.ordinal()]; + } else { + return colour[1][enumColour.ordinal()]; + } + } + + /** + * + * @return + */ + public Color getColourForActiveWindowTitleButton() { + return Color.rgb(128, 128, 128); + } + + /** + * + * @return + */ + public Color getColourForInactiveWindowTitleButton() { + return Color.rgb(153, 153, 153); + } + + /** + * + * @return + */ + public Color getColourForActiveWindowTitleCloseButton() { + return Color.rgb(255, 102, 102); + } + + /** + * + * @param lightOrDarkBackground + * @return + */ + public Color getColourForText(ColourVariant lightOrDarkBackground) { + int colourNumber = this.getEnumColour().getNumber(); + if (lightOrDarkBackground == ColourVariant.DARK) { + int[] intArray = {3, 6, 7, 14, 16}; + for (int element : intArray) { + if (colourNumber == element) { + return Color.rgb(255, 255, 255); + } + } + } else { + if (colourNumber == 14) { + return Color.rgb(255, 255, 255); + } + } + + return Color.rgb(0, 0, 0); + } + + /** + * Convert EnumColour Instance to Color Instance. Its RGB values combine + * with commas. + * + * @param lightOrDark + * @return css String representation of colour + */ + public String getRGBStringForCSS(ColourVariant lightOrDark) { + return Integer.toString((int) (getColour(lightOrDark).getRed() * 255)) + + "," + + Integer.toString((int) (getColour(lightOrDark).getGreen() * 255)) + + "," + + Integer.toString((int) (getColour(lightOrDark).getBlue() * 255)); + } + + /** + * + * @param color + * @return + */ + public String getRGBStringForCSS(Color color) { + return Integer.toString((int) (color.getRed() * 255)) + + "," + + Integer.toString((int) (color.getGreen() * 255)) + + "," + + Integer.toString((int) (color.getBlue() * 255)); + } + + /** + * + * @return + */ + public EnumColour getEnumColour() { + return this.enumColour; + } + + @Override + public String toString() { + return this.enumColour.toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java new file mode 100644 index 0000000..de416aa --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window; + +/** + * Window size modes. + * + * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + */ +public enum WindowSizeMode { + + /** + * Window is not fullscreen. Window is not maximized. Window has borders and + * we can move it and change its size. Window has decorations. + */ + RESTORED, + /** + * Window has no borders, we cannot move it. We cannot resize it. Window has + * decorations. + */ + MAXIMIZED, + /** + * Window has no borders, we cannot move it. We cannot resize it. Window has + * no decorations. + */ + FULLSCREEN; +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java new file mode 100644 index 0000000..2e77e6e --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java @@ -0,0 +1,75 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import javafx.geometry.Insets; +import javafx.scene.input.MouseEvent; +import javafx.scene.text.Font; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class Button extends javafx.scene.control.Button { + + private String setStyleStartString + = new StringBuilder("-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(") + .append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)) + .append(");-fx-border-color:rgb(") + .toString(); + private String setStyleEndString = new StringBuilder(");-fx-border-width: ") + .append(Simplicity.getDpmm() / 2) + .append(";") + .toString(); + + /** + * + * @param windowColourSkin + * @param text + */ + public Button(String text) { + super(text); + this.setMaxWidth(Double.MAX_VALUE); + this.setMaxHeight(6 * Simplicity.getDpmm()); + this.setPadding(new Insets(0, 0, 0, 0)); + this.setFont(Font.font(3 * Simplicity.getDpmm())); + this.setStyle(getSetStyleString("186, 186, 186")); + setOnMouseEntered(this::handleMouseEnteredAction); + setOnMouseExited(this::handleMouseExitedAction); + } + + private void handleMouseEnteredAction(MouseEvent event) {//NOSONAR + this.setStyle(getSetStyleString("0,0,0")); + } + + private void handleMouseExitedAction(MouseEvent event) {//NOSONAR + this.setStyle(getSetStyleString("186, 186, 186")); + } + + private String getSetStyleString(String fxBorderColorString) { + return new StringBuilder(setStyleStartString) + .append(fxBorderColorString) + .append(setStyleEndString) + .toString(); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java new file mode 100644 index 0000000..dbf2281 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +/** + * Represents numeric minus plus control. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class NumericMinusPlus { + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java new file mode 100644 index 0000000..2d56594 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import javafx.scene.text.Font; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class PasswordField extends javafx.scene.control.PasswordField { + + /** + * Constructor + */ + public PasswordField() { + this.setFont(Font.font(3 * Simplicity.getDpmm())); + this.setMaxHeight(6 * Simplicity.getDpmm()); + this.setStyle("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java new file mode 100644 index 0000000..0d41386 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java @@ -0,0 +1,46 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import javafx.scene.paint.Color; +import javafx.scene.text.Font; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; + +/** + * Represents radio button. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class RadioButton extends javafx.scene.control.RadioButton { +/** + * Constructor + * + * @param text + */ + public RadioButton(String text) { + super(text); + + setFont(Font.font(3 * Simplicity.getDpmm())); + Color color=Simplicity.getDefaultWindowColourSkin().getColourForText(ColourVariant.LIGHT); + this.setTextFill(color); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java new file mode 100644 index 0000000..b58360b --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class RadioButtonGroup { + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java new file mode 100644 index 0000000..3414631 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java @@ -0,0 +1,133 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.HBox; +import javafx.scene.layout.StackPane; +import javafx.scene.paint.Color; +import javafx.scene.shape.Line; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SCheckBox extends HBox { + + private StackPane checkBoxStackPane = new StackPane(); + private SLabel checkBoxSLabel = new SLabel(); + private boolean selected = false; + private boolean disabled = false; + Line line1 = new Line(0, 0, 3 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm()); + Line line2 = new Line(0, 3 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), 0); + + /** + * Constructor + */ + public SCheckBox() { + this.line1.setStroke(Color.rgb(153, 153, 153)); + this.line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + this.line2.setStroke(Color.rgb(153, 153, 153)); + this.line2.setStrokeWidth(0.5 * Simplicity.getDpmm()); + + this.setAlignment(Pos.CENTER_LEFT); + + this.getChildren().addAll(this.checkBoxStackPane, this.checkBoxSLabel); + setMargin(checkBoxStackPane, new Insets(0, 1 * Simplicity.getDpmm(), 0, 0)); + setOnMouseClicked(this::handleMouseClicked); + this.checkBoxStackPane.setMinSize(6 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm()); + this.checkBoxStackPane.setMaxSize(6 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm()); + this.checkBoxStackPane.setStyle("-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + } + + /** + * + * @param text + */ + public SCheckBox(String text) { + this(); + this.setCheckBoxText(text); + } + + /** + * + * @param text + */ + public void setCheckBoxText(String text) { + this.checkBoxSLabel.setText(text); + } + + /** + * + * @return + */ + public String getCheckBoxText() { + return this.checkBoxSLabel.getText(); + } + + private void handleMouseClicked(MouseEvent event) {//NOSONAR + this.setSelected(!this.isSelected()); + } + + public void setSelected(boolean value) { + this.selected = value; + this.checkBoxStackPane.getChildren().clear(); + if (value) { + this.checkBoxStackPane.getChildren().addAll(this.line1, this.line2); + } + } + + /** + * + * @return + */ + public boolean isSelected() { + return this.selected; + } + + /** + * + * @param value + */ + public void turnDisabled(boolean value) { + this.disabled = value; + if (value) { + this.checkBoxStackPane.setStyle("-fx-background-color: rgb(192,192,192);-fx-border-color:rgb(153,153,153);-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + setOnMouseClicked(null); + } else { + this.checkBoxStackPane.setStyle("-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + setOnMouseClicked(this::handleMouseClicked); + } + } + + /** + * + * @return + */ + public boolean getDisabled() { + return this.disabled; + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java new file mode 100644 index 0000000..e6e970b --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java @@ -0,0 +1,50 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import javafx.scene.control.ComboBox; +import javafx.scene.text.Font; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SComboBox extends ComboBox { + + /** + * Constructor + */ + public SComboBox() { + this.setMaxHeight(6 * Simplicity.getDpmm()); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb("); + stringBuilder.append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); + stringBuilder.append(");-fx-border-width: "); + stringBuilder.append(Simplicity.getDpmm() / 2); + stringBuilder.append(";-fx-font-size: "); + stringBuilder.append(Font.font(3 * Simplicity.getDpmm())); + stringBuilder.append(";"); + this.setStyle(stringBuilder.toString()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java new file mode 100644 index 0000000..edeca13 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import javafx.scene.paint.Color; +import org.nanoboot.powerframework.simplicity.Simplicity; +import javafx.scene.text.Font; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SLabel extends javafx.scene.control.Label { + + /** + * Constructor + * + * @param text + */ + public SLabel(String text) { + this(text, ColourVariant.LIGHT); + } + + /** + * Constructor + * + * @param text + * @param colourVariant + */ + public SLabel(String text, ColourVariant colourVariant) { + super(text); + setFont(Font.font(3 * Simplicity.getDpmm())); + Color color = Simplicity.getDefaultWindowColourSkin().getColourForText(colourVariant); + this.setTextFill(color); + } + + /** + * Constructor + */ + public SLabel() { + setFont(Font.font(3 * Simplicity.getDpmm())); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java new file mode 100644 index 0000000..68b0ab2 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TabPane extends javafx.scene.control.TabPane { + + public TabPane() { + //Not yet implemented. + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java new file mode 100644 index 0000000..77a13f5 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java @@ -0,0 +1,61 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.controls; + +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import javafx.scene.text.Font; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TextField extends javafx.scene.control.TextField { +/** + * Constructor + * + * @param value + */ + public TextField(String value) { + super(value); + setTextField(); + } + + /** + * Constructor + */ + public TextField() { + setTextField(); + } + + private void setTextField() { + this.setFont(Font.font(3 * Simplicity.getDpmm())); + this.setMaxHeight(6 * Simplicity.getDpmm()); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb("); + stringBuilder.append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); + stringBuilder.append(");-fx-border-width: "); + stringBuilder.append(Simplicity.getDpmm() / 2); + stringBuilder.append(";"); + this.setStyle(stringBuilder.toString()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java new file mode 100644 index 0000000..c009794 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java @@ -0,0 +1,68 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.titlebuttons; + +import javafx.geometry.Pos; +import javafx.scene.shape.Line; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.Window; +import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; + +/** + * Represents close button. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class CloseButton extends WindowTitleButton { + + Line line1 = new Line(0, 0, 5 * Simplicity.getDpmm(), 2.5 * Simplicity.getDpmm()); + Line line2 = new Line(0, 2.5 * Simplicity.getDpmm(), 5 * Simplicity.getDpmm(), 0); + + /** + * + * @param windowColourSkin + * @param window + */ + public CloseButton(WindowColourSkin windowColourSkin, Window window) { + super(windowColourSkin); + setOnMouseClicked(window::handleCloseButtonAction); + line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + line2.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + line2.setStrokeWidth(0.5 * Simplicity.getDpmm()); + getChildren().addAll(line1, line2); + setAlignment(line1, Pos.CENTER); + setAlignment(line2, Pos.CENTER); + } + + @Override + public void makeActive() { + line1.setStroke(this.windowColourSkin.getColourForActiveWindowTitleCloseButton()); + line2.setStroke(this.windowColourSkin.getColourForActiveWindowTitleCloseButton()); + } + + @Override + public void makeInactive() { + line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + line2.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java new file mode 100644 index 0000000..6205bcb --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.titlebuttons; + +import javafx.scene.paint.Color; +import javafx.scene.shape.Line; +import org.nanoboot.powerframework.simplicity.Simplicity; + +/** + * Represents a line of a window title button + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class LineInWindowTitleButton extends Line { + + protected Color inactiveLinesColour = Color.rgb(153, 153, 153); + + /** + * Constructor + */ + public LineInWindowTitleButton() { + setStroke(inactiveLinesColour); + setStrokeWidth(0.5 * Simplicity.getDpmm()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java new file mode 100644 index 0000000..1f42a84 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java @@ -0,0 +1,107 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.titlebuttons; + +import javafx.geometry.Pos; +import javafx.scene.paint.Color; +import javafx.scene.shape.Polyline; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.Window; +import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; + +/** + * Represents maximize/restore button. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class MaximizeRestoreButton extends WindowTitleButton { + + private Polyline restorePolyline = new Polyline( + 1.5 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), + 1.5 * Simplicity.getDpmm(), 0, + 5.5 * Simplicity.getDpmm(), 0, + 5.5 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm(), + 4 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm(), + 4 * Simplicity.getDpmm(), 3.0 * Simplicity.getDpmm(), + 0 * Simplicity.getDpmm(), 3.0 * Simplicity.getDpmm(), + 0 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), + 4 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), + 4 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm() + ); + private Polyline maximizePolyline = new Polyline( + 0.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm(), + 5.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm(), + 5.25 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), + 0.25 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), + 0.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm()); + + /** + * + * @param windowColourSkin + * @param window + */ + public MaximizeRestoreButton(WindowColourSkin windowColourSkin, Window window) { + super(windowColourSkin); + setOnMouseClicked(window::handleMaximizeRestoreButtonAction); + restorePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + restorePolyline.setStrokeWidth(0.5 * Simplicity.getDpmm()); + restorePolyline.setFill(Color.TRANSPARENT); + + maximizePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + maximizePolyline.setStrokeWidth(0.5 * Simplicity.getDpmm()); + maximizePolyline.setFill(Color.TRANSPARENT); + + this.setAlignment(Pos.CENTER); + this.setMaximizeRestoreButtonMaximized(); + + } + + /** + * Changes button's look to restored. + */ + public void setMaximizeRestoreButtonRestored() { + getChildren().clear(); + getChildren().add(restorePolyline); + + } + + /** + ** Changes button's look to maximized. + */ + public void setMaximizeRestoreButtonMaximized() { + getChildren().clear(); + getChildren().add(maximizePolyline); + + } + + @Override + public void makeActive() { + restorePolyline.setStroke(this.windowColourSkin.getColourForActiveWindowTitleButton()); + maximizePolyline.setStroke(this.windowColourSkin.getColourForActiveWindowTitleButton()); + + } + + @Override + public void makeInactive() { + restorePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + maximizePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java new file mode 100644 index 0000000..bb64449 --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java @@ -0,0 +1,64 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.titlebuttons; + +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.shape.Line; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.Window; +import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; + +/** + * Represents minimize button. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class MinimizeButton extends WindowTitleButton { + + Line line1 = new Line(1 * Simplicity.getDpmm(), 3.5 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm(), 3.5 * Simplicity.getDpmm()); + + /** + * + * @param windowColourSkin + * @param window + */ + public MinimizeButton(WindowColourSkin windowColourSkin, Window window) { + super(windowColourSkin); + setOnMouseClicked(window::handleMinimizeButtonAction); + line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + getChildren().addAll(line1); + setAlignment(line1, Pos.BOTTOM_CENTER); + this.setPadding(new Insets(Simplicity.getDpmm(), Simplicity.getDpmm(), Simplicity.getDpmm(), Simplicity.getDpmm())); + + } + + @Override + public void makeActive() { + line1.setStroke(this.windowColourSkin.getColourForActiveWindowTitleButton()); + } + + @Override + public void makeInactive() { + line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java new file mode 100644 index 0000000..26e5edb --- /dev/null +++ b/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java @@ -0,0 +1,89 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.simplicity.window.titlebuttons; + +import javafx.scene.input.MouseEvent; +import javafx.scene.layout.StackPane; +import javafx.scene.shape.Line; +import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; + +/** + * Represents window title button. + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public abstract class WindowTitleButton extends StackPane { + + private static final int BUTTONWIDTH = 7; + + protected WindowColourSkin windowColourSkin; + + /** + * + * @param windowColourSkin + */ + public WindowTitleButton(WindowColourSkin windowColourSkin) { + this.windowColourSkin = windowColourSkin; + this.setStyle("-fx-background-color: rgb(" + windowColourSkin.getRGBStringForCSS(ColourVariant.DARK) + ");"); + setMinWidth(BUTTONWIDTH * Simplicity.getDpmm()); + setMaxWidth(BUTTONWIDTH * Simplicity.getDpmm()); + + setOnMouseEntered(this::handleMouseEnteredAction); + setOnMouseExited(this::handleMMouseExitedAction); + } + + /** + * Makes the background of the button active. + */ + public void makeActiveBackground() { + this.setStyle("-fx-background-color: rgb(212, 212, 212);"); + } + + /** + * + * @param line + */ + public void makeLine(Line line) { + line.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); + line.setStrokeWidth(0.5 * Simplicity.getDpmm()); + } + + private void handleMouseEnteredAction(MouseEvent event) {//NOSONAR + makeActive(); + } + + private void handleMMouseExitedAction(MouseEvent event) {//NOSONAR + makeInactive(); + } + + /** + * Makes button to look active. + */ + public abstract void makeActive(); + + /** + * Makes button to look inactive. + */ + public abstract void makeInactive(); + +} diff --git a/src/main/java/org/nanoboot/powerframework/utilities/.gitkeep b/src/main/java/org/nanoboot/powerframework/utilities/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/resources/.gitkeep b/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java new file mode 100644 index 0000000..55cde57 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java @@ -0,0 +1,205 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DictionaryKeyIteratorTest { + + /** + * + */ + public DictionaryKeyIteratorTest() { + } + + /** + * Test of getNextKey method, of class DictionaryKeyIterator. + */ + @Test + public void testGetNextKey() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + StringBuilder stringBuilder = new StringBuilder(); + String key1; + String key2; + String key3; + String value1; + String value2; + String value3; + String expectedString = "JohnJohnycalm"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + dictionary.addValue("personality", "calm"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + key1 = dictionaryKeyIterator.getNextKey(); + key2 = dictionaryKeyIterator.getNextKey(); + key3 = dictionaryKeyIterator.getNextKey(); + + value1 = dictionary.getValue(key1); + value2 = dictionary.getValue(key2); + value3 = dictionary.getValue(key3); + + stringBuilder.append(value1); + stringBuilder.append(value2); + stringBuilder.append(value3); + returnedString = stringBuilder.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of hasNext method, of class DictionaryKeyIterator. + */ + @Test + public void testHasNext() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + boolean expectedValue = true; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + dictionary.addValue("personality", "calm"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + dictionaryKeyIterator.getNextKey(); + dictionaryKeyIterator.getNextKey(); + returnedValue = dictionaryKeyIterator.hasNext(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of hasNext method, of class DictionaryKeyIterator. + */ + @Test + public void testHasNext2() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + boolean expectedValue = false; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + dictionary.addValue("personality", "calm"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + dictionaryKeyIterator.getNextKey(); + dictionaryKeyIterator.getNextKey(); + dictionaryKeyIterator.getNextKey(); + returnedValue = dictionaryKeyIterator.hasNext(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of hasNext method, of class DictionaryKeyIterator. + */ + @Test + public void testHasNext3() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + boolean expectedValue = false; + boolean returnedValue; + //act + dictionary.addValue("name", "John"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + dictionaryKeyIterator.getNextKey(); + returnedValue = dictionaryKeyIterator.hasNext(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of hasNext method, of class DictionaryKeyIterator. + */ + @Test + public void testHasNext4() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + boolean expectedValue = false; + boolean returnedValue; + //act + + dictionaryKeyIterator = dictionary.getKeyIterator(); + + returnedValue = dictionaryKeyIterator.hasNext(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of hasNext method, of class DictionaryKeyIterator. + */ + @Test + public void testHasNext5() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + boolean expectedValue = true; + boolean returnedValue; + //act + dictionary.addValue("name", "John"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + + returnedValue = dictionaryKeyIterator.hasNext(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of reset method, of class DictionaryKeyIterator. + */ + @Test + public void testReset() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + String firstKey; + + String expectedString = "John"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + dictionary.addValue("personality", "calm"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + for (int i = 0; i < 3; i++) { + dictionaryKeyIterator.getNextKey(); + } + dictionaryKeyIterator.reset(); + firstKey = dictionaryKeyIterator.getNextKey(); + returnedString = dictionary.getValue(firstKey); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java new file mode 100644 index 0000000..05df7d1 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java @@ -0,0 +1,137 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DictionaryNodeTest { + + /** + * + */ + public DictionaryNodeTest() { + } + + /** + * Test of getElement method, of class DictionaryNode. + */ + @Test + public void testGetElement() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + String expectedString = "John"; + String returnedString; + //act + returnedString = dictionaryNode.getElement(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of setElement method, of class DictionaryNode. + */ + @Test + public void testSetElement() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + String expectedString = "Jack"; + String returnedString; + //act + dictionaryNode.setElement("Jack"); + returnedString = dictionaryNode.getElement(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getNext method, of class DictionaryNode. + */ + @Test + public void testGetNext() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + DictionaryNode dictionaryNode2 = new DictionaryNode<>("surname", "Black"); + String expectedString = "Black"; + String returnedString; + //act + dictionaryNode.setNext(dictionaryNode2); + DictionaryNode returnedDictionaryNode = dictionaryNode.getNext(); + returnedString = returnedDictionaryNode.getElement(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of setNext method, of class DictionaryNode. + */ + @Test + public void testSetNext() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + DictionaryNode dictionaryNode2 = new DictionaryNode<>("surname", "White"); + String expectedString = "White"; + String returnedString; + //act + dictionaryNode.setNext(dictionaryNode2); + DictionaryNode returnedDictionaryNode = dictionaryNode.getNext(); + returnedString = returnedDictionaryNode.getElement(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getKey method, of class DictionaryNode. + */ + @Test + public void testGetKey() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + String expectedString = "name"; + String returnedString; + //act + returnedString = dictionaryNode.getKey(); + //assert + assertEquals(expectedString, returnedString); + + } + + /** + * Test of setKey method, of class DictionaryNode. + */ + @Test + public void testSetKey() { + //arrange + DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); + String expectedString = "nick"; + String returnedString; + //act + dictionaryNode.setKey("nick"); + returnedString = dictionaryNode.getKey(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java new file mode 100644 index 0000000..9fd3de7 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java @@ -0,0 +1,381 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DictionaryTest { + + /** + * + */ + public DictionaryTest() { + } + + /** + * Test of getCountOfItems method, of class Dictionary. + */ + @Test + public void testGetCountOfItems() { + //arrange + Dictionary dictionary = new Dictionary<>(); + int expectedValue = 0; + int returnedValue; + //act + returnedValue = dictionary.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getCountOfItems method, of class Dictionary. + */ + @Test + public void testGetCountOfItems2() { + //arrange + Dictionary dictionary = new Dictionary<>(); + int expectedValue = 0; + int returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black"); + dictionary.removeValue("name").removeValue("surname"); + returnedValue = dictionary.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getCountOfItems method, of class Dictionary. + */ + @Test + public void testGetCountOfItems3() { + //arrange + Dictionary dictionary = new Dictionary<>(); + int expectedValue = 2; + int returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + returnedValue = dictionary.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getCountOfItems method, of class Dictionary. + */ + @Test + public void testGetCountOfItems4() { + //arrange + Dictionary dictionary = new Dictionary<>(); + int expectedValue = 1; + int returnedValue; + //act + dictionary.addValue("surname", "Black"); + returnedValue = dictionary.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Dictionary. + */ + @Test + public void testIsEmpty() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + returnedValue = dictionary.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Dictionary. + */ + @Test + public void testIsEmpty2() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black"); + dictionary.removeValue("name").removeValue("surname"); + returnedValue = dictionary.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Dictionary. + */ + @Test + public void testIsEmpty3() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + returnedValue = dictionary.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getValue method, of class Dictionary. + */ + @Test + public void testIsEmpty4() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("name"); + returnedValue = dictionary.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class Dictionary. + */ + @Test + public void containsValueWithKey() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + returnedValue = dictionary.containsValueWithKey("surname"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class Dictionary. + */ + @Test + public void containsValueWithKey2() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + returnedValue = dictionary.containsValueWithKey("job"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class Dictionary. + */ + @Test + public void containsValueWithKey3() { + //arrange + Dictionary dictionary = new Dictionary<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + dictionary.addValue("name", "John"); + returnedValue = dictionary.containsValueWithKey("name"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addValue method, of class Dictionary. + */ + @Test + public void testAddValue() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Johny"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + returnedString = dictionary.getValue("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of addValue method, of class Dictionary. + */ + @Test + public void testAddValue2() { + //arrang + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Johny"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("name"); + returnedString = dictionary.getValue("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of addValue method, of class Dictionary. + */ + @Test + public void testAddValue3() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Black"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("nick"); + returnedString = dictionary.getValue("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getValue method, of class Dictionary. + */ + @Test + public void testGetValue() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Black"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("name"); + returnedString = dictionary.getValue("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getValue method, of class Dictionary. + */ + @Test + public void testGetValue2() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Johny"; + String returnedString; + //act + dictionary.addValue("nick", "Johny"); + returnedString = dictionary.getValue("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of updateValue method, of class Dictionary. + */ + @Test + public void testUpdateValue() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Blue"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.updateValue("surname", "Blue"); + returnedString = dictionary.getValue("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of removeValue method, of class Dictionary. + */ + @Test + public void testRemoveValue() { + //arrange + boolean isExceptionThrown = false; + Dictionary dictionary = new Dictionary<>(); + String expectedString = "Black"; + String returnedString; + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + //act + try { + returnedString = dictionary.getValue("surname"); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getKeyIterator method, of class Dictionary. + */ + @Test + public void testGetKeyIterator() { + //arrange + Dictionary dictionary = new Dictionary<>(); + DictionaryKeyIterator dictionaryKeyIterator; + String expectedString = "Johny"; + String returnedString; + String secondKey; + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + dictionary.removeValue("surname"); + dictionaryKeyIterator = dictionary.getKeyIterator(); + //act + dictionaryKeyIterator.getNextKey(); + secondKey = dictionaryKeyIterator.getNextKey(); + returnedString = dictionary.getValue(secondKey); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toString method, of class Dictionary. + */ + @Test + public void testToString() { + //arrange + Dictionary dictionary = new Dictionary<>(); + String expectedString = "name:John\nsurname:Black\nnick:Johny\n"; + String returnedString; + //act + dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); + returnedString = dictionary.toString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java b/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java new file mode 100644 index 0000000..c9ab36c --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java @@ -0,0 +1,292 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class QueueTest { + + /** + * + */ + public QueueTest() { + } + + /** + * Test of getCountOfItems method, of class Queue. + */ + @Test + public void testGetCountOfItems() { + //arrange + Queue queue = new Queue<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + returnedCountOfItems = queue.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Queue. + */ + @Test + public void testGetCountOfItems2() { + //arrange + Queue queue = new Queue<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + queue.enqueue("John"); + queue.dequeue(); + returnedCountOfItems = queue.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Queue. + */ + @Test + public void testGetCountOfItems3() { + //arrange + Queue queue = new Queue<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + queue.enqueue("John"); + queue.dequeue(); + queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.enqueue("Jane"); + queue.dequeue(); + returnedCountOfItems = queue.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Queue. + */ + @Test + public void testGetCountOfItems4() { + //arrange + Queue queue = new Queue<>(); + int expectedCountOfItems = 1; + int returnedCountOfItems; + //act + queue.enqueue("John"); + queue.dequeue(); + queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + + queue.dequeue(); + queue.dequeue(); + queue.enqueue("Jane"); + queue.dequeue(); + returnedCountOfItems = queue.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Queue. + */ + @Test + public void testGetCountOfItems5() { + //arrange + Queue queue = new Queue<>(); + int expectedCountOfItems = 3; + int returnedCountOfItems; + //act + queue.enqueue("John"); + queue.dequeue(); + queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie").enqueue("Susan"); + + queue.dequeue(); + queue.enqueue("Jane"); + queue.dequeue(); + returnedCountOfItems = queue.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of isEmpty method, of class Queue. + */ + @Test + public void testIsEmpty() { + //arrange + Queue queue = new Queue<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + returnedValue = queue.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Queue. + */ + @Test + public void testIsEmpty2() { + //arrange + Queue queue = new Queue<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + + queue.enqueue("Jane"); + queue.dequeue(); + returnedValue = queue.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Queue. + */ + @Test + public void testIsEmpty3() { + //arrange + Queue queue = new Queue<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + + queue.enqueue("Jane"); + queue.dequeue(); + returnedValue = queue.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Queue. + */ + @Test + public void testIsEmpty4() { + //arrange + Queue queue = new Queue<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + + queue.dequeue(); + queue.dequeue(); + + queue.enqueue("Jane"); + queue.dequeue(); + returnedValue = queue.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of enqueue method, of class Queue. + */ + @Test + public void testEnqueue() { + //arrange + Queue queue = new Queue<>(); + String expectedString = "John"; + String returnedString; + //act + queue.enqueue("John"); + returnedString = queue.dequeue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of dequeue method, of class Queue. + */ + @Test + public void testDequeue() { + //arrange + Queue queue = new Queue<>(); + String expectedString = "Alice"; + String returnedString; + //act + queue.enqueue("Alice").enqueue("Jane"); + returnedString = queue.dequeue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of dequeue method, of class Queue. + */ + @Test + public void testDequeue_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + Queue queue = new Queue<>(); + //act + try { + queue.dequeue(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of toString method, of class Queue. + */ + @Test + public void testToString() { + //arrange + Queue queue = new Queue<>(); + String expectedString = "Alice, Jane, "; + String returnedString; + //act + queue.enqueue("Alice").enqueue("Jane"); + returnedString = queue.toString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/StackTest.java b/src/test/java/org/nanoboot/powerframework/collections/StackTest.java new file mode 100644 index 0000000..827cbf6 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/collections/StackTest.java @@ -0,0 +1,340 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class StackTest { + + /** + * + */ + public StackTest() { + } + + /** + * Test of getCountOfItems method, of class Stack. + */ + @Test + public void testGetCountOfItems() { + //arrange + Stack stack = new Stack<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + returnedCountOfItems = stack.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Stack. + */ + @Test + public void testGetCountOfItems2() { + //arrange + Stack stack = new Stack<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + stack.push("John"); + stack.pop(); + returnedCountOfItems = stack.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Stack. + */ + @Test + public void testGetCountOfItems3() { + //arrange + Stack stack = new Stack<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + stack.push("John"); + stack.pop(); + stack.push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + stack.pop(); + stack.push("Jane"); + stack.pop(); + returnedCountOfItems = stack.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Stack. + */ + @Test + public void testGetCountOfItems4() { + //arrange + Stack stack = new Stack<>(); + int expectedCountOfItems = 1; + int returnedCountOfItems; + //act + stack.push("John"); + stack.pop(); + stack.push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + stack.push("Jane"); + stack.pop(); + returnedCountOfItems = stack.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getCountOfItems method, of class Stack. + */ + @Test + public void testGetCountOfItems5() { + //arrange + Stack stack = new Stack<>(); + int expectedCountOfItems = 3; + int returnedCountOfItems; + //act + stack.push("John"); + stack.pop(); + stack.push("Jack").push("Anne").push("Charlie").push("Susan"); + + stack.pop(); + stack.push("Jane"); + stack.pop(); + returnedCountOfItems = stack.getCountOfItems(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of isEmpty method, of class Stack. + */ + @Test + public void testIsEmpty() { + //arrange + Stack stack = new Stack<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + returnedValue = stack.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Stack. + */ + @Test + public void testIsEmpty2() { + //arrange + Stack stack = new Stack<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + stack.pop(); + stack.pop(); + + stack.push("Jane"); + stack.pop(); + returnedValue = stack.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Stack. + */ + @Test + public void testIsEmpty3() { + //arrange + Stack stack = new Stack<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + stack.pop(); + + stack.push("Jane"); + stack.pop(); + returnedValue = stack.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class Stack. + */ + @Test + public void testIsEmpty4() { + //arrange + Stack stack = new Stack<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + + stack.push("Jane"); + stack.pop(); + returnedValue = stack.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of push method, of class Stack. + */ + @Test + public void testPush() { + //arrange + Stack stack = new Stack<>(); + String expectedString = "Jack"; + String returnedString; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie"); + + stack.pop(); + stack.pop(); + + stack.push("Jane"); + stack.pop(); + returnedString = stack.pop(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of pop method, of class Stack. + */ + @Test + public void testPop() { + //arrange + Stack stack = new Stack<>(); + String expectedString = "Dennis"; + String returnedString; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + + stack.push("Jane"); + stack.pop(); + returnedString = stack.pop(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of peek method, of class Stack. + */ + @Test + public void testPeek() { + //arrange + Stack stack = new Stack<>(); + String expectedString = "Dennis"; + String returnedString; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + + stack.push("Jane"); + stack.pop(); + returnedString = stack.peek(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of peek method, of class Stack. + */ + @Test + public void testPeek2() { + //arrange + Stack stack = new Stack<>(); + int expectedValue = 6; + int returnedValue; + //act + stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + + stack.push("Jane"); + stack.pop(); + returnedValue = stack.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of pop method, of class Stack. + */ + @Test + public void testPop2() { + + //arrange + boolean isExceptionThrown = false; + Stack stack = new Stack<>(); + //act + try { + stack.pop(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of toString method, of class Stack. + */ + @Test + public void testToString() { + //arrange + Stack stack = new Stack<>(); + String expectedString = "Jane, Alice, "; + String returnedString; + //act + stack.push("Alice").push("Jane"); + returnedString = stack.toString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java b/src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java new file mode 100644 index 0000000..2864e48 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java @@ -0,0 +1,228 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import java.io.File; +import org.nanoboot.powerframework.json.JsonObject; + +import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; +import org.junit.AfterClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.BeforeClass; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DatabaseConnectionTest { + + private static final File directory; + private static final String directoryName; + + static { + PseudoRandomGenerator pseudoRandomGenerator = PseudoRandomGenerator.getInstance(); + int randomNumber = pseudoRandomGenerator.getInt(0, 999999); + directoryName = "./temp" + randomNumber + "/"; + directory = new File(directoryName); + } + + static public boolean deleteDirectory(File path) { + if (path.exists()) { + File[] files = path.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDirectory(files[i]); + } else { + files[i].delete(); + } + } + } + return (path.delete()); + } + + public DatabaseConnectionTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + directory.mkdir(); + } + + private String getNextDatabaseName() { + return Integer.toString(PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + } + + /** + * Test of getDatabaseName method, of class DatabaseConnection. + */ + @Test + public void testGetDatabaseName() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + String expectedString = databaseName; + String returnedString; + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + //act + returnedString = databaseConnection.getDatabaseName(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of execute method, of class DatabaseConnection. + */ + @Test + public void testExecute_String() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + databaseConnection.execute("create table customers(id integer,name text,surname text,yearofbirth integer)"); + //act + databaseConnection.execute("insert into customers values(1,'John','Green',1954);"); + //assert + assertFalse(databaseConnection.isTableEmpty("customers")); + } + + /** + * Test of execute method, of class DatabaseConnection. + */ + @Test + public void testExecute_SqlCommandQueue() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); + sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); + sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); + sqlCommandQueue.add("insert into customers values(3,'Peter','Orange',1990);"); + + //act + databaseConnection.executeMoreCommands(sqlCommandQueue); + //assert + assertFalse(databaseConnection.isTableEmpty("customers")); + } + + /** + * Test of executeAndReturn method, of class DatabaseConnection. + */ + @Test + public void testExecuteAndReturn() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); + sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); + sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); + sqlCommandQueue.add("insert into customers values(3,'Peter','Orange',1990);"); + String query = "select * from customers"; + databaseConnection.executeMoreCommands(sqlCommandQueue); + + String expectedString = "{\"query\":\"select * from customers\",\"columns\":[\"id\",\"name\",\"surname\",\"yearofbirth\"],\"rows\":[[\"1\",\"John\",\"Green\",\"1954\"],[\"2\",\"Anne\",\"Blue\",\"1985\"],[\"3\",\"Peter\",\"Orange\",\"1990\"]]}"; + String returnedString; + ResultOfSqlQuery resultOfSqlQuery; + //act + resultOfSqlQuery = databaseConnection.executeAndReturn(query); + returnedString = resultOfSqlQuery.toJsonObject().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getRow method, of class DatabaseConnection. + */ + @Test + public void testGetRow() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); + sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); + sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); + sqlCommandQueue.add("insert into customers values(3,'Peter','Orange',1990);"); + + databaseConnection.executeMoreCommands(sqlCommandQueue); + JsonObject row; + String expectedString = "{\"id\":\"2\",\"name\":\"Anne\",\"surname\":\"Blue\",\"yearofbirth\":\"1985\"}"; + String returnedString; + //act + row = databaseConnection.getRow("customers", 2); + returnedString = row.toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * + * Test of isTableEmpty method, of class DatabaseConnection. + */ + @Test + public void testIsTableEmpty() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + boolean returnedValue; + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); + databaseConnection.executeMoreCommands(sqlCommandQueue); + //act + returnedValue = databaseConnection.isTableEmpty("customers"); + //assert + assertTrue(returnedValue); + } + + /** + * + * Test of isTableEmpty method, of class DatabaseConnection. + */ + @Test + public void testIsTableEmpty2() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + boolean returnedValue; + Database.createDatabase(databaseName); + DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); + sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); + sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); + sqlCommandQueue.add("insert into customers values(3,'Peter','Orange',1990);"); + databaseConnection.executeMoreCommands(sqlCommandQueue); + //act + returnedValue = databaseConnection.isTableEmpty("customers"); + //assert + assertFalse(returnedValue); + } + + @AfterClass + public static void tearDownClass() { + deleteDirectory(directory); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java b/src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java new file mode 100644 index 0000000..3fef910 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java @@ -0,0 +1,211 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import java.io.File; +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; +import org.junit.AfterClass; +import org.junit.Test; +import static org.junit.Assert.*; +import org.junit.BeforeClass; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DatabaseTest { + + private static final File directory; + private static final String directoryName; + + static { + PseudoRandomGenerator pseudoRandomGenerator = PseudoRandomGenerator.getInstance(); + int randomNumber = pseudoRandomGenerator.getInt(0, 999999); + directoryName = "./temp" + randomNumber + "/"; + directory = new File(directoryName); + } + + static public boolean deleteDirectory(File path) { + if (path.exists()) { + File[] files = path.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + deleteDirectory(files[i]); + } else { + files[i].delete(); + } + } + } + return (path.delete()); + } + + public DatabaseTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + directory.mkdir(); + } + + private String getNextDatabaseName() { + return Integer.toString(PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + } + + /** + * Test of createDatabase method, of class Database. + */ + @Test + public void testCreateDatabase() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + //act + Database.createDatabase(databaseName); + //assert + assertTrue(new File(databaseName + ".sqlite").exists()); + } + + /** + * Test of createDatabase method, of class Database. + */ + @Test + public void testCreateDatabase2() { + //arrange + boolean isExceptionThrown = false; + String databaseName = directoryName + getNextDatabaseName(); + //act + Database.createDatabase(databaseName); + try { + Database.createDatabase(databaseName); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of dropDatabase method, of class Database. + */ + @Test + public void testDropDatabase() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + Database.createDatabase(databaseName); + //act + Database.dropDatabase(databaseName); + //assert + assertFalse(Database.existsDatabase(databaseName)); + } + + /** + * Test of dropDatabase method, of class Database. + */ + @Test + public void testDropDatabase2() { + //arrange + boolean isExceptionThrown = false; + String databaseName = directoryName + getNextDatabaseName(); + //act + try { + Database.dropDatabase(databaseName); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of existsDatabaseWithThisName method, of class Database. + */ + @Test + public void testExistsDatabaseWithThisName() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + //act + Database.createDatabase(databaseName); + //assert + assertTrue(Database.existsDatabase(databaseName)); + } + + /** + * Test of existsDatabaseWithThisName method, of class Database. + */ + @Test + public void testExistsDatabaseWithThisName2() { + //arrange + String databaseName = directoryName + getNextDatabaseName(); + //act + //assert + assertFalse(Database.existsDatabase(databaseName)); + } + + /** + * Test of createDatabaseConnection method, of class Database. + */ + @Test + public void testCreateDatabaseConnection() { + //arrange + boolean isExceptionThrown = false; + String databaseName = directoryName + getNextDatabaseName(); + //act + Database.createDatabase(databaseName); + try { + Database.createDatabaseConnection(databaseName); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of createDatabaseConnection method, of class Database. + */ + @Test + public void testCreateDatabaseConnection2() { + //arrange + boolean isExceptionThrown = false; + String databaseName = directoryName + getNextDatabaseName(); + //act + try { + Database.createDatabaseConnection(databaseName); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + @AfterClass + public static void tearDownClass() { + deleteDirectory(directory); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java b/src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java new file mode 100644 index 0000000..2be8cf6 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java @@ -0,0 +1,315 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import org.nanoboot.powerframework.json.JsonArray; +import org.nanoboot.powerframework.json.JsonObject; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class ResultOfSqlQueryTest { + + private static final String jsonObjectAsString; + + static { + JsonObject jsonObject = new JsonObject(); + + String command = "select * from customers"; + JsonArray columns = new JsonArray(); + columns.addString("id").addString("name").addString("surname").addString("yearofbirth"); + + JsonArray rows = new JsonArray(); + JsonArray row1 = new JsonArray(); + row1.addString("1").addString("John").addString("Green").addString("1954"); + + JsonArray row2 = new JsonArray(); + row2.addString("2").addString("Anne").addString("Blue").addString("1985"); + + JsonArray row3 = new JsonArray(); + row3.addString("3").addString("Peter").addString("Orange").addString("1990"); + + rows.addArray(row1).addArray(row2).addArray(row3); + + jsonObject.addString("query", command); + jsonObject.addArray("columns", columns); + jsonObject.addArray("rows", rows); + + jsonObjectAsString = jsonObject.toMinimalString(); + } + + public ResultOfSqlQueryTest() { + } + + /** + * + */ + @Test + public void testJsonObjectAsString() { + //arrange + String expectedString = "{\"query\":\"select * from customers\",\"columns\":[\"id\",\"name\",\"surname\",\"yearofbirth\"],\"rows\":[[\"1\",\"John\",\"Green\",\"1954\"],[\"2\",\"Anne\",\"Blue\",\"1985\"],[\"3\",\"Peter\",\"Orange\",\"1990\"]]}"; + String returnedString; + //act + returnedString = jsonObjectAsString; + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getColumnNames method, of class ResultOfSqlQuery. + */ + @Test + public void testGetColumnNames() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "[\"id\",\"name\",\"surname\",\"yearofbirth\"]"; + String returnedString; + //act + returnedString = resultOfSqlQuery.getColumnNames().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getRows method, of class ResultOfSqlQuery. + */ + @Test + public void testGetRows() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "[[\"1\",\"John\",\"Green\",\"1954\"],[\"2\",\"Anne\",\"Blue\",\"1985\"],[\"3\",\"Peter\",\"Orange\",\"1990\"]]"; + String returnedString; + //act + returnedString = resultOfSqlQuery.getRows().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getCountOfRows method, of class ResultOfSqlQuery. + */ + @Test + public void testGetCountOfRows() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + int expectedValue = 3; + int returnedValue; + //act + returnedValue = resultOfSqlQuery.getCountOfRows(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class ResultOfSqlQuery. + */ + @Test + public void testIsEmpty() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + boolean returnedValue; + //act + returnedValue = resultOfSqlQuery.isEmpty(); + //assert + assertFalse(returnedValue); + } + + /** + * Test of resetPosition method, of class ResultOfSqlQuery. + */ + @Test + public void testResetPosition() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "[\"1\",\"John\",\"Green\",\"1954\"]"; + String returnedString; + //act + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.resetPositionBeforeFirstRow(); + resultOfSqlQuery.moveToTheNextRow(); + returnedString = resultOfSqlQuery.getRow().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of hasNextRow method, of class ResultOfSqlQuery. + */ + @Test + public void testHasNextRow() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + boolean returnedValue; + //act + returnedValue = resultOfSqlQuery.hasNextRow(); + //assert + assertTrue(returnedValue); + } + + /** + * Test of hasNextRow method, of class ResultOfSqlQuery. + */ + @Test + public void testHasNextRow2() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + resultOfSqlQuery.moveToTheNextRow(); + boolean returnedValue; + //act + returnedValue = resultOfSqlQuery.hasNextRow(); + //assert + assertTrue(returnedValue); + } + + /** + * Test of hasNextRow method, of class ResultOfSqlQuery. + */ + @Test + public void testHasNextRow3() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + boolean returnedValue; + //act + returnedValue = resultOfSqlQuery.hasNextRow(); + //assert + assertFalse(returnedValue); + } + + /** + * Test of moveToTheNextRow method, of class ResultOfSqlQuery. + */ + @Test + public void testMoveToTheNextRow() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "[\"2\",\"Anne\",\"Blue\",\"1985\"]"; + String returnedString; + //act + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + returnedString = resultOfSqlQuery.getRow().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getInt method, of class ResultOfSqlQuery. + */ + @Test + public void testGetInt() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + int expectedValue = 1985; + int returnedValue; + //act + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + returnedValue = resultOfSqlQuery.getInt("yearofbirth"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getDouble method, of class ResultOfSqlQuery. + */ + @Test + public void testGetDouble() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + double expectedValue = 1985d; + double returnedValue; + //act + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + returnedValue = resultOfSqlQuery.getDouble("yearofbirth"); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of getString method, of class ResultOfSqlQuery. + */ + @Test + public void testGetString() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "Anne"; + String returnedString; + //act + resultOfSqlQuery.moveToTheNextRow(); + resultOfSqlQuery.moveToTheNextRow(); + returnedString = resultOfSqlQuery.getString("name"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getQuery method, of class ResultOfSqlQuery. + */ + @Test + public void testGetQuery() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = "select * from customers"; + String returnedString; + //act + returnedString = resultOfSqlQuery.getQuery(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toJsonObject method, of class ResultOfSqlQuery. + */ + @Test + public void testToJsonObject() { + //arrange + JsonObject jsonObject = new JsonObject(jsonObjectAsString); + ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + String expectedString = jsonObjectAsString; + String returnedString; + //act + returnedString = resultOfSqlQuery.toJsonObject().toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java b/src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java new file mode 100644 index 0000000..025c0b0 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java @@ -0,0 +1,119 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.database; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SqlCommandQueueTest { + + public SqlCommandQueueTest() { + } + + /** + * Test of add method, of class SqlCommandQueue. + */ + @Test + public void testAdd() { + //arrange + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + String expectedString = "insert into customers values ('Jack','Black')"; + String returnedString; + //act + sqlCommandQueue.add("insert into customers values ('Jack','Black')"); + sqlCommandQueue.add("insert into customers values ('Susan','White')"); + returnedString = sqlCommandQueue.loadNextCommand(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of loadNextCommand method, of class SqlCommandQueue. + */ + @Test + public void testLoadNextCommand() { + //arrange + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + String expectedString = "insert into customers values ('Susan','White')"; + String returnedString; + //act + sqlCommandQueue.add("insert into customers values ('Jack','Black')"); + sqlCommandQueue.add("insert into customers values ('Susan','White')"); + sqlCommandQueue.loadNextCommand(); + returnedString = sqlCommandQueue.loadNextCommand(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of isThereANextCommand method, of class SqlCommandQueue. + */ + @Test + public void testIsThereANextCommand() { + //arrange + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + //act + sqlCommandQueue.add("insert into customers values ('Jack','Black')"); + sqlCommandQueue.add("insert into customers values ('Susan','White')"); + sqlCommandQueue.loadNextCommand(); + //assert + assertTrue(sqlCommandQueue.isThereANextCommand()); + } + + /** + * Test of isThereANextCommand method, of class SqlCommandQueue. + */ + @Test + public void testIsThereANextCommand2() { + //arrange + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + //act + sqlCommandQueue.add("insert into customers values ('Jack','Black')"); + sqlCommandQueue.add("insert into customers values ('Susan','White')"); + sqlCommandQueue.loadNextCommand(); + sqlCommandQueue.loadNextCommand(); + //assert + assertFalse(sqlCommandQueue.isThereANextCommand()); + } + + /** + * Test of toString method, of class SqlCommandQueue. + */ + @Test + public void testToString() { + //arrange + SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + String expectedString = "insert into customers values ('Jack','Black'), insert into customers values ('Susan','White'), "; + String returnedString; + //act + sqlCommandQueue.add("insert into customers values ('Jack','Black')"); + sqlCommandQueue.add("insert into customers values ('Susan','White')"); + returnedString = sqlCommandQueue.toString(); + //assert + assertEquals(expectedString, returnedString); + + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java new file mode 100644 index 0000000..6d0c018 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java @@ -0,0 +1,342 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DateTimeTest { + + private class DateTimeImpl extends DateTime { + + public DateTimeImpl(LocalDate localDate, LocalTime localTime) { + super(localDate, localTime); + } + + public DateTimeImpl(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + super(year, month, day, hour24Format, minute, second, millisecond); + } + + public DateTimeImpl(DateTime dateTime) { + super(dateTime); + } + + public DateTimeImpl(String dateTimeInString) { + super(dateTimeInString); + } + + } + + /** + * + */ + public DateTimeTest() { + } + + /** + * Test of constructor of class DateTime. (LocalDate localDate, LocalTime + * localTime) + */ + @Test + public void testDateTime_2args_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(new LocalDate(1994, 5, 6), new LocalTime(21, 45, 6, 32)); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (LocalDate localDate, LocalTime + * localTime) + */ + @Test + public void testDateTime_2args_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(new LocalDate(1994, 15, 6), new LocalTime(21, 45, 6, 32)); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (int year, int month, int day, int + * hour24Format, int minute, int second, int millisecond) + */ + @Test + public void testDateTime_7args_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (int year, int month, int day, int + * hour24Format, int minute, int second, int millisecond) + */ + @Test + public void testDateTime_7args_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(1994, 15, 6, 21, 45, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (DateTime dateTime) + */ + @Test + public void testDateTime_1argsFromAnotherObject_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32)); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (DateTime dateTime) + */ + @Test + public void testDateTime_1argsFromAnotherObject_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl(new DateTimeImpl(1994, 15, 6, 21, 45, 6, 32)); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (String dateTimeInString) + */ + @Test + public void testDateTime_1argsFromString_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl("1994-05-06 21:45:06:032"); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class DateTime. (String dateTimeInString) + */ + @Test + public void testDateTime_1argsFromString_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + DateTimeImpl dateTimeImpl = new DateTimeImpl("1994-15-06 21:45:06:032"); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getYear method, of class LocalDate. + */ + @Test + public void testGetYear() { + //arrange + int expectedYear = 1994; + int returnedYear; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedYear = dateTimeImpl.getYear(); + //assert + assertEquals(expectedYear, returnedYear); + } + + /** + * Test of getYear method, of class LocalDate. + */ + @Test + public void testGetMonth() { + //arrange + int expectedMonth = 5; + int returnedMonth; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedMonth = dateTimeImpl.getMonth(); + //assert + assertEquals(expectedMonth, returnedMonth); + } + + /** + * Test of getDay method, of class LocalDate. + */ + @Test + public void testGetDay() { + //arrange + int expectedDay = 6; + int returnedDay; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedDay = dateTimeImpl.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of getHour method, of class DateTime. + */ + @Test + public void testGetHour() { + //arrange + int expectedHour = 21; + int returnedHour; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedHour = dateTimeImpl.getHour(); + //assert + assertEquals(expectedHour, returnedHour); + } + + /** + * Test of getMinute method, of class DateTime. + */ + @Test + public void testGetMinute() { + //arrange + int expectedMinute = 45; + int returnedMinute; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedMinute = dateTimeImpl.getMinute(); + //assert + assertEquals(expectedMinute, returnedMinute); + } + + /** + * Test of getSecond method, of class DateTime. + */ + @Test + public void testGetSecond() { + //arrange + int expectedSecond = 6; + int returnedSecond; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedSecond = dateTimeImpl.getSecond(); + //assert + assertEquals(expectedSecond, returnedSecond); + } + + /** + * Test of getMillisecond method, of class DateTime. + */ + @Test + public void testGetMillisecond() { + //arrange + int expectedMillisecond = 32; + int returnedMillisecond; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + returnedMillisecond = dateTimeImpl.getMillisecond(); + //assert + assertEquals(expectedMillisecond, returnedMillisecond); + } + + /** + * Test of toString method, of class LocalDate. + */ + @Test + public void testToString() { //arrange + String expectedResult = "1994-05-06 21:45:06:032"; + String result; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + result = dateTimeImpl.toString(); + //assert + assertEquals(expectedResult, result); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java b/src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java new file mode 100644 index 0000000..69ab5a5 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java @@ -0,0 +1,218 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DateUnitsValidatorTest { + + /** + * + */ + public DateUnitsValidatorTest() { + } + + /** + * Test of isMonthValid method, of class DateUnitsValidator. + */ + @Test + public void testIsMonthValid_MonthIs3_ThereShouldBeReturnedTrue() { + //arrange + int month = 3; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isMonthValid(month); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isMonthValid method, of class DateUnitsValidator. + */ + @Test + public void testIsMonthValid_MonthIs0_ThereShouldBeReturnedFalse() { + //arrange + int month = 0; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isMonthValid(month); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isMonthValid method, of class DateUnitsValidator. + */ + @Test + public void testIsMonthValid_MonthIs13_ThereShouldBeReturnedFalse() { + //arrange + int month = 13; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isMonthValid(month); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isDayValid method, of class DateUnitsValidator. + */ + @Test + public void testIsDayValid_DayIs3_ThereShouldBeReturnedTrue() { + //arrange + int day = 3; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isDayValid(day); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isDayValid method, of class DateUnitsValidator. + */ + @Test + public void testIsDayValid_DayIs0_ThereShouldBeReturnedFalse() { + //arrange + int day = 0; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isDayValid(day); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isDayValid method, of class DateUnitsValidator. + */ + @Test + public void testIsDayValid_DayIs32_ThereShouldBeReturnedFalse() { + //arrange + int day = 32; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.isDayValid(day); + //assert + assertFalse(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs1992AndMonthIs3AndDayIs3_ThereShouldBeReturnedTrue() { + //arrange + int year = 1992; + int month = 3; + int day = 3; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertTrue(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs1992AndMonthIs6AndDayIs31_ThereShouldBeReturnedFalse() { + //arrange + int year = 1992; + int month = 6; + int day = 31; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertFalse(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs01992AndMonthIs2AndDayIs28_ThereShouldBeReturnedTrue() { + //arrange + int year = 1992; + int month = 2; + int day = 28; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertTrue(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs1993AndMonthIs2AndDayIs28_ThereShouldBeReturnedTrue() { + //arrange + int year = 1993; + int month = 2; + int day = 28; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertTrue(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs01993AndMonthIs2AndDayIs29_ThereShouldBeReturnedFalse() { + //arrange + int year = 1993; + int month = 2; + int day = 29; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertFalse(returnedValue); + } + + /** + * Test of hasDateValidCombination method, of class DateUnitsValidator. + */ + @Test + public void testHasDateValidCombination_YearIs01992AndMonthIs2AndDayIs29_ThereShouldBeReturnedTrue() { + //arrange + int year = 1992; + int month = 2; + int day = 29; + boolean returnedValue; + //act + returnedValue = DateUnitsValidator.hasDateValidCombination(year, month, day); + //assert + assertTrue(returnedValue); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java b/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java new file mode 100644 index 0000000..c5e73c9 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java @@ -0,0 +1,878 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class DurationTest { + + /** + * + */ + public DurationTest() { + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_5Args_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + Duration duration = new Duration(23, 5, 3, 43, 97); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_5Args_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + Duration duration = new Duration(23, 5, 3, 143, 97); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_5Args_ThereShouldBeReturnedIsPositive() { + //arrange + boolean expectedValue = true; + boolean returnedValue; + Duration duration = new Duration(23, 5, 3, 43, 97); + //act + returnedValue = duration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_6Args_ThereShouldBeReturnedIsPositive() { + //arrange + boolean expectedValue = true; + boolean returnedValue; + Duration duration = new Duration(true, 23, 5, 3, 43, 97); + //act + returnedValue = duration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_6Args_ThereShouldBeReturnedIsNotPositive() { + //arrange + boolean expectedValue = false; + boolean returnedValue; + Duration duration = new Duration(false, 23, 5, 3, 43, 97); + //act + returnedValue = duration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_StringArg() { + //arrange + String argString = "+00023:05:03:43:097"; + String expectedString = "+23:5:3:43:97"; + String returnedString; + + Duration duration = new Duration(argString); + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of constructor, of class Duration. + */ + @Test + public void TestDuration_StringArg_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + String argString = "+23:5:60:43:97"; + Duration duration = new Duration(argString); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of between method, of class Duration. + */ + @Test + public void testBetween1_UniversalDateTime_UniversalDateTime() { + //arrange + UniversalDateTime startUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); + UniversalDateTime endUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); + String expectedString = "+21077:4:54:51:300"; + String returnedString; + //act + returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of between method, of class Duration. + */ + @Test + public void testBetween2_UniversalDateTime_UniversalDateTime() { + //arrange + UniversalDateTime startUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); + UniversalDateTime endUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); + String expectedString = "-21077:4:54:51:300"; + String returnedString; + //act + returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of between method, of class Duration. + */ + @Test + public void testBetween1_ZonedDateTime_ZonedDateTime() { + //arrange + LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); + ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); + ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); + String expectedString = "-0:9:0:0:0"; + String returnedString; + //act + returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of between method, of class Duration. + */ + @Test + public void testBetween2_ZonedDateTime_ZonedDateTime() { + //arrange + LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); + ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); + ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); + String expectedString = "+0:9:0:0:0"; + String returnedString; + //act + returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of ofDays method, of class Duration. + */ + @Test + public void testOfDays() { + //arrange + int days = 13; + + Duration duration = Duration.ofDays(days); + String expectedString = "+13:0:0:0:0"; + String returnedString; + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of ofHours method, of class Duration. + */ + @Test + public void testOfHours() { + //arrange + int hours = 17; + + Duration duration = Duration.ofHours(hours); + String expectedString = "+0:17:0:0:0"; + String returnedString; + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of ofMinutes method, of class Duration. + */ + @Test + public void testOfMinutes() { + //arrange + int minutes = 42; + + Duration duration = Duration.ofMinutes(minutes); + String expectedString = "+0:0:42:0:0"; + String returnedString; + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of ofSeconds method, of class Duration. + */ + @Test + public void testOfSeconds() { + //arrange + int seconds = 9; + + Duration duration = Duration.ofSeconds(seconds); + String expectedString = "+0:0:0:9:0"; + String returnedString; + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of ofMilliseconds method, of class Duration. + */ + @Test + public void testOfMilliseconds() { + //arrange + int milliseconds = 4; + + Duration duration = Duration.ofMilliseconds(milliseconds); + String expectedString = "+0:0:0:0:4"; + String returnedString; + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of fromUniversalDateTimePlusDurationCreateNewUniversalDateTime + * method, of class Duration. + */ + @Test + public void testFromUniversalDateTimePlusDurationCreateNewUniversalDateTime() { + //arrange + UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); + Duration duration = Duration.ofHours(7); + String expectedString = "2007-04-21 16:17:58:954"; + String returnedString; + //act + returnedString = Duration.fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime + * method, of class Duration. + */ + @Test + public void testFromUniversalDateTimeMinusDurationCreateNewUniversalDateTime() { + //arrange + UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); + Duration duration = Duration.ofHours(7); + String expectedString = "2007-04-21 02:17:58:954"; + String returnedString; + //act + returnedString = Duration.fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of fromZonedDateTimePlusDurationCreateNewZonedDateTime method, of + * class Duration. + */ + @Test + public void testFromZonedDateTimePlusDurationCreateNewZonedDateTime() { + //arrange + LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); + TimeZone timeZone = new TimeZone("Australia/Sydney"); + ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); + Duration duration = Duration.ofHours(7); + String expectedString = "2007-04-21 16:17:58:954"; + String returnedString; + //act + returnedString = Duration.fromZonedDateTimePlusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of fromZonedDateTimeMinusDurationCreateNewZonedDateTime method, of + * class Duration. + */ + @Test + public void testFromZonedDateTimeMinusDurationCreateNewZonedDateTime() { + //arrange + LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); + TimeZone timeZone = new TimeZone("Australia/Sydney"); + ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); + Duration duration = Duration.ofHours(7); + String expectedString = "2007-04-21 02:17:58:954"; + String returnedString; + //act + returnedString = Duration.fromZonedDateTimeMinusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getDays method, of class Duration. + */ + @Test + public void testGetDays() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + long expectedDays = 23; + long returnedDays; + //act + returnedDays = duration.getDays(); + //assert + assertEquals(expectedDays, returnedDays); + } + + /** + * Test of getHours method, of class Duration. + */ + @Test + public void testGetHours() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + int expectedHours = 5; + int returnedHours; + //act + returnedHours = duration.getHours(); + //assert + assertEquals(expectedHours, returnedHours); + } + + /** + * Test of getMinutes method, of class Duration. + */ + @Test + public void testGetMinutes() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + int expectedMinutes = 3; + int returnedMinutes; + //act + returnedMinutes = duration.getMinutes(); + //assert + assertEquals(expectedMinutes, returnedMinutes); + } + + /** + * Test of getSeconds method, of class Duration. + */ + @Test + public void testGetSeconds() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + int expectedSeconds = 43; + int returnedSeconds; + //act + returnedSeconds = duration.getSeconds(); + //assert + assertEquals(expectedSeconds, returnedSeconds); + } + + /** + * Test of getMilliseconds method, of class Duration. + */ + @Test + public void testGetMilliseconds() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + int expectedMilliseconds = 97; + int returnedMilliseconds; + //act + returnedMilliseconds = duration.getMilliseconds(); + //assert + assertEquals(expectedMilliseconds, returnedMilliseconds); + } + + /** + * Test of isPositive method, of class Duration. + */ + @Test + public void testIsPositive() { + //arrange + Duration duration = new Duration(false, 23, 5, 3, 43, 97); + boolean expectedValue = false; + boolean returnedValue; + //act + returnedValue = duration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of negated method, of class Duration. + */ + @Test + public void testNegated() { + //arrange + Duration duration = new Duration(23, 5, 3, 43, 97); + Duration negatedDuration; + + boolean expectedValue = false; + boolean returnedValue; + //act + negatedDuration = duration.negated(); + returnedValue = negatedDuration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of abs method, of class Duration. + */ + @Test + public void testAbs() { + //arrange + Duration duration = new Duration(false, 23, 5, 3, 43, 97); + Duration absDuration; + + boolean expectedValue = true; + boolean returnedValue; + //act + absDuration = duration.abs(); + returnedValue = absDuration.isPositive(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of plusDuration method, of class Duration. + */ + @Test + public void testPlusDuration() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + Duration durationToAdd = new Duration(0, 5, 4, 2, 7); + Duration returnedDuration; + String expectedString = "+12:5:4:2:7"; + String returnedString; + + //act + returnedDuration = duration.plusDuration(durationToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of plusDays method, of class Duration. + */ + @Test + public void testPlusDays() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + long daysToAdd = 1; + Duration returnedDuration; + String expectedString = "+13:0:0:0:0"; + String returnedString; + + //act + returnedDuration = duration.plusDays(daysToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of plusHours method, of class Duration. + */ + @Test + public void testPlusHours() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + int hoursToAdd = 1; + Duration returnedDuration; + String expectedString = "+12:1:0:0:0"; + String returnedString; + + //act + returnedDuration = duration.plusHours(hoursToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of plusMinutes method, of class Duration. + */ + @Test + public void testPlusMinutes() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + int minutesToAdd = 1; + Duration returnedDuration; + String expectedString = "+12:0:1:0:0"; + String returnedString; + + //act + returnedDuration = duration.plusMinutes(minutesToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of plusSeconds method, of class Duration. + */ + @Test + public void testPlusSeconds() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + int secondsToAdd = 1; + Duration returnedDuration; + String expectedString = "+12:0:0:1:0"; + String returnedString; + + //act + returnedDuration = duration.plusSeconds(secondsToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of plusMilliseconds method, of class Duration. + */ + @Test + public void testPlusMilliseconds() { + //arrange + Duration duration = new Duration(12, 0, 0, 0, 0); + int millisecondsToAdd = 1; + Duration returnedDuration; + String expectedString = "+12:0:0:0:1"; + String returnedString; + + //act + returnedDuration = duration.plusMilliseconds(millisecondsToAdd); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusDuration method, of class Duration. + */ + @Test + public void testMinusDuration() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + Duration durationToSubtract = new Duration(0, 5, 4, 2, 7); + Duration returnedDuration; + String expectedString = "+12:0:0:0:0"; + String returnedString; + + //act + returnedDuration = duration.minusDuration(durationToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusDays method, of class Duration. + */ + @Test + public void testMinusDays() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + long daysToSubtract = 1; + Duration returnedDuration; + String expectedString = "+11:5:4:2:7"; + String returnedString; + + //act + returnedDuration = duration.minusDays(daysToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusHours method, of class Duration. + */ + @Test + public void testMinusHours() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + int hoursToSubtract = 1; + Duration returnedDuration; + String expectedString = "+12:4:4:2:7"; + String returnedString; + + //act + returnedDuration = duration.minusHours(hoursToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusMinutes method, of class Duration. + */ + @Test + public void testMinusMinutes() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + int minutesToSubtract = 1; + Duration returnedDuration; + String expectedString = "+12:5:3:2:7"; + String returnedString; + + //act + returnedDuration = duration.minusMinutes(minutesToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusSeconds method, of class Duration. + */ + @Test + public void testMinusSeconds() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + int secondsToSubtract = 1; + Duration returnedDuration; + String expectedString = "+12:5:4:1:7"; + String returnedString; + + //act + returnedDuration = duration.minusSeconds(secondsToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of minusMilliseconds method, of class Duration. + */ + @Test + public void testMinusMilliseconds() { + //arrange + Duration duration = new Duration(12, 5, 4, 2, 7); + int millisecondsToSubtract = 1; + Duration returnedDuration; + String expectedString = "+12:5:4:2:6"; + String returnedString; + + //act + returnedDuration = duration.minusMilliseconds(millisecondsToSubtract); + returnedString = returnedDuration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toTotalDays method, of class Duration. + */ + @Test + public void testToTotalDays() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedValue = 14; + long returnedValue; + //act + returnedValue = (long) Math.floor(duration.toTotalDays()); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toTotalHours method, of class Duration. + */ + @Test + public void testToTotalHours() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedValue = 345; + long returnedValue; + //act + returnedValue = (long) Math.floor(duration.toTotalHours()); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toTotalMinutes method, of class Duration. + */ + @Test + public void testToTotalMinutes() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedValue = 20717; + long returnedValue; + //act + returnedValue = (long) Math.floor(duration.toTotalMinutes()); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toTotalSeconds method, of class Duration. + */ + @Test + public void testToTotalSeconds() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedValue = 1243073; + long returnedValue; + //act + returnedValue = (long) Math.floor(duration.toTotalSeconds()); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toTotalMilliseconds method, of class Duration. + */ + @Test + public void testToTotalMilliseconds() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedValue = 1243073834; + long returnedValue; + //act + returnedValue = (long) Math.floor(duration.toTotalMilliseconds()); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toJavaDuration method, of class Duration. + */ + @Test + public void testToJavaDuration() { + //arrange + Duration duration = new Duration(14, 9, 17, 53, 834); + long expectedTotalSeconds = (long) Math.floor(duration.toTotalSeconds()); + long returnedSeconds; + java.time.Duration javaDuration; + //act + javaDuration = duration.toJavaDuration(); + returnedSeconds = javaDuration.getSeconds(); + //assert + assertEquals(expectedTotalSeconds, returnedSeconds); + } + + /** + * Test of toString method, of class Duration. + */ + @Test + public void testToString1_ConstructorWithLongArgUsed() { + //arrange + String expectedString = "+23:5:3:43:97"; + String returnedString; + long countOfTotalMilliseconds = 2005423097; + + Duration duration = new Duration(countOfTotalMilliseconds); + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toString method, of class Duration. + */ + @Test + public void testToString2_ConstructorWithLongArgUsed() { + //arrange + String expectedString = "-23:5:3:43:97"; + String returnedString; + long countOfTotalMilliseconds = -2005423097; + + Duration duration = new Duration(countOfTotalMilliseconds); + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toString method, of class Duration. + */ + @Test + public void testToString3_ConstructorWithLongArgUsed() { + //arrange + String expectedString = "+0:0:0:0:0"; + String returnedString; + long countOfTotalMilliseconds = 0; + + Duration duration = new Duration(countOfTotalMilliseconds); + //act + returnedString = duration.toString(); + //assert + assertEquals(expectedString, returnedString); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java b/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java new file mode 100644 index 0000000..4aa9f7d --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java @@ -0,0 +1,435 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class LocalDateTest { + + /** + * + */ + public LocalDateTest() { + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 5, 6); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsZero_MonthIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 0, 6); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFifty_MonthIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 50, 6); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_DayIsZero_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 5, 0); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_DayIsThirtyTwo_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 5, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsSeptember_DayIsThirtyOne_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1994, 9, 31); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsThirtyOne_YearIsNotLeap_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 31); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsThirty_YearIsNotLeap_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1993, 2, 30); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentyNine_YearIsNotLeap_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1993, 2, 29); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentyEight_YearIsNotLeap_DayIsNotOutOfRange_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1993, 2, 28); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentySeven_YearIsNotLeap_DayIsNotOutOfRange_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1993, 2, 27); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsThirtyOne_YearIsLeap_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 31); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsThirty_YearIsLeap_DayIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 30); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentyNine_YearIsLeap_DayIsNotOutOfRange_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 29); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentyEight_YearIsLeap_DayIsNotOutOfRange_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 28); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalDate . + */ + @Test + public void testLocalDate_MonthIsFebruary_DayIsTwentySeven_YearIsLeap_DayIsNotOutOfRange_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalDate localDate = new LocalDate(1992, 2, 27); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of isYearLeap method, of class LocalDate. + */ + @Test + public void testIsYearLeap_YearIs1992_ThereShouldBeReturnedTrue() { + //arrange + int year = 1992; + boolean returnedValue; + //act + returnedValue = LocalDate.isYearLeap(year); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isYearLeap method, of class LocalDate. + */ + @Test + public void testIsYearLeap_YearIs1994_ThereShouldBeReturnedFalse() { + //arrange + int year = 1995; + boolean returnedValue; + //act + returnedValue = LocalDate.isYearLeap(year); + //assert + assertFalse(returnedValue); + } + + /** + * Test of getYear method, of class LocalDate. + */ + @Test + public void testGetYear() { + //arrange + int expectedYear = 1994; + int returnedYear; + LocalDate localDate; + //act + localDate = new LocalDate(1994, 5, 6); + returnedYear = localDate.getYear(); + //assert + assertEquals(expectedYear, returnedYear); + } + + /** + * Test of getMonth method, of class LocalDate. + */ + @Test + public void testGetMonth() { + //arrange + int expectedMonth = 5; + int returnedMonth; + LocalDate localDate; + //act + localDate = new LocalDate(1994, 5, 6); + returnedMonth = localDate.getMonth(); + //assert + assertEquals(expectedMonth, returnedMonth); + } + + /** + * Test of getDay method, of class LocalDate. + */ + @Test + public void testGetDay() { + //arrange + int expectedDay = 6; + int returnedDay; + LocalDate localDate; + //act + localDate = new LocalDate(1994, 5, 6); + returnedDay = localDate.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of toString method, of class LocalDate. + */ + @Test + public void testToString() { //arrange + String expectedResult = "1994-05-06"; + String result; + LocalDate localDate; + //act + localDate = new LocalDate(1994, 5, 6); + result = localDate.toString(); + //assert + assertEquals(expectedResult, result); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java new file mode 100644 index 0000000..3f1bd80 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java @@ -0,0 +1,166 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class LocalDateTimeTest { + + /** + * + */ + public LocalDateTimeTest() { + } + + /** + * Test of constructor of class LocalDateTime. (String dateTimeInString) + */ + @Test + public void testLocalDateTime_1argString_day6MustBeReturned() { + //arrange + LocalDateTime localDateTime; + int expectedDay = 6; + int returnedDay; + //act + localDateTime = new LocalDateTime("1994-05-06 21:45:06:032"); + returnedDay = localDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class LocalDateTime. (int year, int month, int + * day, int hour24Format, int minute, int second, int millisecond) + */ + @Test + public void testLocalDateTime_7args_day6MustBeReturned() { + //arrange + LocalDateTime localDateTime; + int expectedDay = 6; + int returnedDay; + //act + localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); + returnedDay = localDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class LocalDateTime. (UniversalDateTime + * universalDateTime) + */ + @Test + public void testLocalDateTime_1argUniversalDateTime_day6MustBeReturned() { + //arrange + LocalDateTime localDateTime; + UniversalDateTime universalDateTime; + int expectedDay = 6; + int returnedDay; + //act + universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); + localDateTime = new LocalDateTime(universalDateTime); + returnedDay = localDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class LocalDateTime. (ZonedDateTime zonedDateTime) + */ + @Test + public void testLocalDateTime_1argZonedDateTime_day6MustBeReturned() { + //arrange + LocalDateTime localDateTime; + TimeZone timeZone; + ZonedDateTime zonedDateTime; + int expectedDay = 6; + int returnedDay; + //act + timeZone = new TimeZone("Australia/Sydney"); + zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); + localDateTime = new LocalDateTime(zonedDateTime); + returnedDay = localDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of toUniversalDateTime method, of class LocalDateTime. + */ + @Test + public void testToUniversalDateTime() { + //arrange + LocalDateTime localDateTime; + UniversalDateTime universalDateTime; + int expectedDay = 6; + int returnedDay; + //act + localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); + universalDateTime = localDateTime.toUniversalDateTime(); + returnedDay = universalDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of toZonedDateTime method, of class LocalDateTime. + */ + @Test + public void testToZonedDateTime() { + //arrange + LocalDateTime localDateTime; + TimeZone timeZone; + ZonedDateTime zonedDateTime; + int expectedDay = 6; + int returnedDay; + //act + timeZone = new TimeZone("Australia/Sydney"); + localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); + zonedDateTime = localDateTime.toZonedDateTime(timeZone); + returnedDay = zonedDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of toJavaLocalDateTime method, of class LocalDateTime. + */ + @Test + public void testToJavaLocalDateTime() { + //arrange + LocalDateTime localDateTime; + java.time.LocalDateTime javaLocalDateTime; + int expectedDay = 6; + int returnedDay; + //act + localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); + javaLocalDateTime = localDateTime.toJavaLocalDateTime(); + returnedDay = javaLocalDateTime.getDayOfMonth(); + //assert + assertEquals(expectedDay, returnedDay); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java new file mode 100644 index 0000000..a201269 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java @@ -0,0 +1,290 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class LocalTimeTest { + + /** + * + */ + public LocalTimeTest() { + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 45, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_HourIsMinusOne_HourIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(-1, 45, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_HourIsTwentyFour_HourIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(24, 45, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_MinuteIsMinusOne_MinuteIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, -1, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_MinuteIsSixty_MinuteIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 60, 6, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_SecondIsMinusOne_SecondIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 45, -1, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_SecondIsSixty_SecondIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 45, 60, 32); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_MillisecondIsMinusOne_MillisecondIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 45, 6, -1); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of constructor of class LocalTime. + */ + @Test + public void testDateTime_MillisecondIsOneThousand_MillisecondIsOutOfRange_ThereShouldBeThrownPowerRuntimeException() { + //arrange + boolean isExceptionThrown = false; + //act + try { + LocalTime localTime = new LocalTime(21, 45, 6, 1000); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getHour method, of class LocalTime. + */ + @Test + public void testGetHour() { + //arrange + int expectedHour = 9; + int returnedHour; + LocalTime localTime; + //act + localTime = new LocalTime(9, 23, 14, 354); + returnedHour = localTime.getHour(); + //assert + assertEquals(expectedHour, returnedHour); + } + + /** + * Test of getMinute method, of class LocalTime. + */ + @Test + public void testGetMinute() { + //arrange + int expectedMinute = 23; + int returnedMinute; + LocalTime localTime; + //act + localTime = new LocalTime(9, 23, 14, 354); + returnedMinute = localTime.getMinute(); + //assert + assertEquals(expectedMinute, returnedMinute); + } + + /** + * Test of getSecond method, of class LocalTime. + */ + @Test + public void testGetSecond() { + //arrange + int expectedSecond = 14; + int returnedSecond; + LocalTime localTime; + //act + localTime = new LocalTime(9, 23, 14, 354); + returnedSecond = localTime.getSecond(); + //assert + assertEquals(expectedSecond, returnedSecond); + } + + /** + * Test of getMillisecond method, of class LocalTime. + */ + @Test + public void testGetMillisecond() { + //arrange + int expectedMillisecond = 354; + int returnedMillisecond; + LocalTime localTime; + //act + localTime = new LocalTime(9, 23, 14, 354); + returnedMillisecond = localTime.getMillisecond(); + //assert + assertEquals(expectedMillisecond, returnedMillisecond); + } + + /** + * Test of toString method, of class DateTime. + */ + @Test + public void testToString() { + //arrange + String expectedResult = "09:23:14:354"; + String result; + LocalTime localTime; + //act + localTime = new LocalTime(9, 23, 14, 354); + result = localTime.toString(); + //assert + assertEquals(expectedResult, result); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java b/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java new file mode 100644 index 0000000..9a525ed --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java @@ -0,0 +1,288 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TimeUnitsValidatorTest { + + /** + * + */ + public TimeUnitsValidatorTest() { + } + + /** + * Test of isHourValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsHourValid_HourIs13_ThereShouldBeReturnedTrue() { + //arrange + int hour = 13; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isHourValid(hour); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isHourValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsHourValid_HourIsMinus1_ThereShouldBeReturneFalse() { + //arrange + int hour = -1; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isHourValid(hour); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isHourValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsHourValid_HourIs24_ThereShouldBeReturneFalse() { + //arrange + int hour = 24; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isHourValid(hour); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isMinuteValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMinuteValid_MinuteIs34__ThereShouldBeReturnedTrue() { + //arrange + int minute = 34; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMinuteValid(minute); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isMinuteValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMinuteValid_MinuteIsMinus1_ThereShouldBeReturneFalse() { + //arrange + int minute = -1; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMinuteValid(minute); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isMinuteValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMinuteValid_MinuteIs60_ThereShouldBeReturneFalse() { + //arrange + int minute = 60; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMinuteValid(minute); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isSecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsSecondValid_SecondIs46__ThereShouldBeReturnedTrue() { + //arrange + int second = 46; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isSecondValid(second); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isSecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsSecondValid_SecondIsMinus1__ThereShouldBeReturneFalse() { + //arrange + int second = -1; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isSecondValid(second); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isSecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsSecondValid_SecondIs60__ThereShouldBeReturneFalse() { + //arrange + int second = 60; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isSecondValid(second); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isMillisecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMillisecondValid_MillisecondIs843__ThereShouldBeReturnedTrue() { + //arrange + int millisecond = 843; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isMillisecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMillisecondValid_MillisecondIsMinus1_ThereShouldBeReturneFalse() { + //arrange + int millisecond = -1; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); + //assert + assertFalse(returnedValue); + } + + /** + * Test of isMillisecondValid method, of class TimeUnitsValidator. + */ + @Test + public void testIsMillisecondValid_MillisecondIs1000_ThereShouldBeReturneFalse() { + //arrange + int millisecond = 1000; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); + //assert + assertFalse(returnedValue); + } + + /** + * Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. + */ + @Test + public void testAreAllTimeUnitsValid_ThereShouldBeReturneTrue() { + //arrange + int hour = 2; + int minute = 34; + int second = 23; + int millisecond = 428; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); + //assert + assertTrue(returnedValue); + } + + /** + * Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. + */ + @Test + public void testAreAllTimeUnitsValid_ThereShouldBeReturneFalse() { + //arrange + int hour = 112; + int minute = 134; + int second = 123; + int millisecond = 1428; + boolean returnedValue; + //act + returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); + //assert + assertFalse(returnedValue); + } + + /** + * Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException + * method, of class TimeUnitsValidator. + */ + @Test + public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownNoPowerRuntimeException() { + //arrange + int hour = 12; + int minute = 34; + int second = 23; + int millisecond = 428; + boolean isExceptionThrown = false; + //act + try { + TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException + * method, of class TimeUnitsValidator. + */ + @Test + public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownPowerRuntimeException() { + //arrange + int hour = 112; + int minute = 134; + int second = 123; + int millisecond = 1428; + boolean isExceptionThrown = false; + //act + try { + TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java b/src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java new file mode 100644 index 0000000..95d3743 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java @@ -0,0 +1,129 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import java.util.List; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class TimeZoneTest { + + /** + * + */ + public TimeZoneTest() { + } + + /** + * Test of getListOfTimeZoneIDs method, of class TimeZone. + */ + @Test + public void testGetListOfTimeZoneIDs_mustContain() { + //arrange + List listOfTimeZoneIDs; + boolean expectedValue = true; + boolean result; + //act + listOfTimeZoneIDs = TimeZone.getListOfTimeZoneIDs(); + result = listOfTimeZoneIDs.contains("Australia/Sydney"); + //assert + assertEquals(expectedValue, result); + } + + /** + * Test of getListOfTimeZoneIDs method, of class TimeZone. + */ + @Test + public void testGetListOfTimeZoneIDs_mustNotContain() { + //arrange + List listOfTimeZoneIDs; + boolean expectedValue = false; + boolean result; + //act + listOfTimeZoneIDs = TimeZone.getListOfTimeZoneIDs(); + result = listOfTimeZoneIDs.contains("Amflkfd/Adfkjldfk"); + //assert + assertEquals(expectedValue, result); + } + + /** + * Test of isTimeZoneIDValid method, of class TimeZone. + */ + @Test + public void testIsTimeZoneIDValid_mustReturnTrue() { + //arrange + boolean expectedValue = true; + boolean result; + //act + result = TimeZone.isTimeZoneIDValid("Australia/Sydney"); + //assert + assertEquals(expectedValue, result); + } + + /** + * Test of isTimeZoneIDValid method, of class TimeZone. + */ + @Test + public void testIsTimeZoneIDValid_mustReturnFalse() { + //arrange + boolean expectedValue = false; + boolean result; + //act + result = TimeZone.isTimeZoneIDValid("Jehjujfdue/Eklfglsdi"); + //assert + assertEquals(expectedValue, result); + } + + /** + * Test of toString method, of class TimeZone. + */ + @Test + public void testToString() { + //arrange + String expectedValue = "Australia/Sydney"; + String result; + TimeZone timeZone = new TimeZone("Australia/Sydney"); + //act + result = timeZone.toString(); + //assert + assertEquals(expectedValue, result); + } + + /** + * Test of getTimeZoneID method, of class TimeZone. + */ + @Test + public void testGetTimeZoneID() { + //arrange + String expectedValue = "Australia/Sydney"; + String result; + TimeZone timeZone = new TimeZone("Australia/Sydney"); + //act + result = timeZone.getTimeZoneID(); + //assert + assertEquals(expectedValue, result); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java new file mode 100644 index 0000000..9b55a3b --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java @@ -0,0 +1,148 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class UniversalDateTimeTest { + + /** + * + */ + public UniversalDateTimeTest() { + } + + /** + * Test of constructor of class UniversalDateTime. (String dateTimeInString) + */ + @Test + public void testUniversalDateTime_1argString_day6MustBeReturned() { + //arrange + UniversalDateTime universalDateTime; + int expectedDay = 6; + int returnedDay; + //act + universalDateTime = new UniversalDateTime("1994-05-06 21:45:06:032"); + returnedDay = universalDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class UniversalDateTime. (int year, int month, int + * day, int hour24Format, int minute, int second, int millisecond) + */ + @Test + public void testUniversalDateTime_7args_day6MustBeReturned() { + //arrange + UniversalDateTime universalDateTime; + int expectedDay = 6; + int returnedDay; + //act + universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); + returnedDay = universalDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class UniversalDateTime. (ZonedDateTime + * zonedDateTime) + */ + @Test + public void testUniversalDateTime_1argZonedDateTime_day6MustBeReturned() { + //arrange + UniversalDateTime universalDateTime; + TimeZone timeZone; + ZonedDateTime zonedDateTime; + int expectedDay = 5; + int returnedDay; + //act + timeZone = new TimeZone("Australia/Sydney"); + zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); + universalDateTime = new UniversalDateTime(zonedDateTime); + returnedDay = universalDateTime.getMonth(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of constructor of class UniversalDateTime. (LocalDateTime + * localDateTime) + */ + @Test + public void testUniversalDateTime_1argLocalDateTime_day6MustBeReturned() { + //arrange + UniversalDateTime universalDateTime; + LocalDateTime localDateTime; + int expectedDay = 6; + int returnedDay; + //act + localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); + universalDateTime = new UniversalDateTime(localDateTime); + + returnedDay = localDateTime.getDay(); + //assert + assertEquals(expectedDay, returnedDay); + } + + /** + * Test of toZonedDateTime method, of class LocalDateTime. + */ + @Test + public void testToZonedDateTime() { + //arrange + UniversalDateTime universalDateTime; + ZonedDateTime zonedDateTime; + int expectedMonth = 5; + int returnedMonth; + //act + universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); + zonedDateTime = universalDateTime.toZonedDateTime(); + returnedMonth = zonedDateTime.getMonth(); + //assert + assertEquals(expectedMonth, returnedMonth); + } + + /** + * Test of testToLocalDateTime method, of class LocalDateTime. + */ + @Test + public void testToLocalDateTime() { + //arrange + UniversalDateTime universalDateTime; + LocalDateTime localDateTime; + + int expectedMonth = 5; + int returnedMonth; + //act + universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); + localDateTime = universalDateTime.toLocalDateTime(); + returnedMonth = universalDateTime.getMonth(); + //assert + assertEquals(expectedMonth, returnedMonth); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java new file mode 100644 index 0000000..f60789a --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java @@ -0,0 +1,157 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.datetime; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class ZonedDateTimeTest { + + /** + * + */ + public ZonedDateTimeTest() { + } + + /** + * Test of convertDateTimeFromOneTimeZoneToAnother method, of class + * ZonedDateTime. + */ + @Test + public void testConvertDateTimeFromOneTimeZoneToAnother() { + //arrange + TimeZone oldTimeZone = new TimeZone("Australia/West"); + ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); + String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); + + String expectedStringValue = "1995-11-05 13:05:04:064"; + String returnedStringValue; + TimeZone newTimeZone = new TimeZone("Australia/Sydney"); + //act + returnedStringValue = ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother(stringRepresentationOfOldZonedDateTime, oldTimeZone, newTimeZone); + //assert + assertEquals(expectedStringValue, returnedStringValue); + } + + /** + * Test of getTimeZone method, of class ZonedDateTime. + */ + @Test + public void testGetTimeZone() { + //arrange + String timeZoneID = "Australia/West"; + TimeZone timeZone = new TimeZone(timeZoneID); + ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), timeZone); + TimeZone returnedTimeZone; + String returnedZoneID; + //act + returnedTimeZone = zonedDateTime.getTimeZone(); + returnedZoneID = returnedTimeZone.getTimeZoneID(); + //assert + assertEquals(timeZoneID, returnedZoneID); + + } + + /** + * Test of toUniversalDateTime method, of class ZonedDateTime. + */ + @Test + public void testToUniversalDateTime() { + //arrange + TimeZone oldTimeZone = new TimeZone("Australia/West"); + ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); + String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); + + String expectedStringValue = "1995-08-05 02:05:04:064"; + String returnedStringValue; + //act + UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); + returnedStringValue = universalDateTime.toString(); + //assert + assertEquals(expectedStringValue, returnedStringValue); + } + + /** + * Test of toLocalDateTime method, of class ZonedDateTime. + */ + @Test + public void testToLocalDateTime() { + //arrange + TimeZone oldTimeZone = new TimeZone("Australia/West"); + ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); + String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); + + String expectedStringValue = "1995-08-05 10:05:04:064"; + String returnedStringValue; + //act + LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); + returnedStringValue = localDateTime.toString(); + //assert + assertEquals(expectedStringValue, returnedStringValue); + } + + /** + * Test of toZonedDateTime method, of class ZonedDateTime. + */ + @Test + public void testToZonedDateTime() { + //arrange + TimeZone oldTimeZone = new TimeZone("Australia/West"); + ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); + String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); + + TimeZone newTimeZone = new TimeZone("Australia/Sydney"); + ZonedDateTime newZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 13, 5, 4, 64), oldTimeZone); + + String expectedStringValue = "1995-11-05 13:05:04:064"; + String returnedStringValue; + //act + String stringRepresentationOfNewZonedDateTime = newZonedDateTime.toString(); + returnedStringValue = stringRepresentationOfNewZonedDateTime; + //assert + assertEquals(expectedStringValue, returnedStringValue); + } + + /** + * Test of toJavaZonedDateTime method, of class ZonedDateTime. + */ + @Test + public void testToJavaZonedDateTime() { + //arrange + TimeZone timeZone = new TimeZone("Australia/West"); + ZonedDateTime zonedDateTime; + zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); + java.time.ZonedDateTime javaZonedDateTime; + int expectedDay = 6; + int returnedDay; + //act + + javaZonedDateTime = zonedDateTime.toJavaZonedDateTime(); + returnedDay = javaZonedDateTime.getDayOfMonth(); + //assert + assertEquals(expectedDay, returnedDay); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java b/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java new file mode 100644 index 0000000..f20522f --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java @@ -0,0 +1,796 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class JsonArrayTest { + + /** + * + */ + public JsonArrayTest() { + } + + /** + * Test of constructor, of class JsonArray. + */ + @Test + public void testJsonArray() { + //arrange + String expectedString = "[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492]"; + String returnedString; + + JsonArray property; + //act + property = new JsonArray(expectedString); + returnedString = property.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of getCountOfItems method, of class JsonArray. + */ + @Test + public void testGetCountOfItems() { + + //arrange + int expectedValue = 4; + int returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.add("John"); + jsonArray.addString("Black"); + jsonArray.addString("Johny"); + jsonArray.addString("calm"); + //act + + returnedValue = jsonArray.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class JsonArray. + */ + @Test + public void testIsEmpty() { + //arrange + boolean expectedValue = true; + boolean returnedValue; + JsonArray jsonArray = new JsonArray(); + //act + returnedValue = jsonArray.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class JsonArray. + */ + @Test + public void testIsEmpty2() { + //arrange + boolean expectedValue = false; + boolean returnedValue; + JsonArray jsonArray = new JsonArray(); + jsonArray.add("John"); + jsonArray.addString("Black"); + jsonArray.addString("Johny"); + jsonArray.addString("calm"); + for (int i = 1; i <= 3; i++) { + jsonArray.removeJsonValue(0); + } + //act + returnedValue = jsonArray.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonArray. + */ + @Test + public void testAdd() { + + //arrange + JsonValueType expectedValue = JsonValueType.NULL; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.add(null); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addNull method, of class JsonArray. + */ + @Test + public void testAddNull() { + //arrange + JsonValueType expectedValue = JsonValueType.NULL; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addObject method, of class JsonArray. + */ + @Test + public void testAddObject() { + //arrange + JsonValueType expectedValue = JsonValueType.OBJECT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addObject(new JsonObject()); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addArray method, of class JsonArray. + */ + @Test + public void testAddArray() { + //arrange + JsonValueType expectedValue = JsonValueType.ARRAY; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addArray(new JsonArray()); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addBoolean method, of class JsonArray. + */ + @Test + public void testAddBoolean() { + //arrange + JsonValueType expectedValue = JsonValueType.BOOLEAN; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addBoolean(true); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addString method, of class JsonArray. + */ + @Test + public void testAddString() { + //arrange + JsonValueType expectedValue = JsonValueType.STRING; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addString("String"); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addChar method, of class JsonArray. + */ + @Test + public void testAddChar() { + //arrange + JsonValueType expectedValue = JsonValueType.CHAR; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addChar('S'); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addInt method, of class JsonArray. + */ + @Test + public void testAddInt() { + //arrange + JsonValueType expectedValue = JsonValueType.INT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addInt(10); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addLong method, of class JsonArray. + */ + @Test + public void testAddLong() { + //arrange + JsonValueType expectedValue = JsonValueType.LONG; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addLong(10l); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addFloat method, of class JsonArray. + */ + @Test + public void testAddFloat() { + //arrange + JsonValueType expectedValue = JsonValueType.FLOAT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addFloat(10.4f); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addDouble method, of class JsonArray. + */ + @Test + public void testAddDouble() { + //arrange + JsonValueType expectedValue = JsonValueType.DOUBLE; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addDouble(10.4d); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonArray. + */ + @Test + public void testGetJsonValueType() { + //arrange + JsonValueType expectedValue = JsonValueType.DOUBLE; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addDouble(10.4d); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getObject method, of class JsonArray. + */ + @Test + public void testGetObject() { + //arrange + String expectedValue = "object"; + String returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addObject(new JsonObject().addString("key", "object")); + //act + returnedValue = jsonArray.getObject(0).getString("key"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getArray method, of class JsonArray. + */ + @Test + public void testGetArray() { + //arrange + String expectedValue = "array"; + String returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addArray(new JsonArray().addString("array")); + //act + returnedValue = jsonArray.getArray(0).getString(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getBoolean method, of class JsonArray. + */ + @Test + public void testGetBoolean() { + //arrange + boolean expectedValue = true; + boolean returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addBoolean(true); + //act + returnedValue = jsonArray.getBoolean(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getString method, of class JsonArray. + */ + @Test + public void testGetString() { + //arrange + String expectedValue = "String"; + String returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addString("String"); + //act + returnedValue = jsonArray.getString(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getChar method, of class JsonArray. + */ + @Test + public void testGetChar() { + //arrange + char expectedValue = 'S'; + char returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addChar('S'); + //act + returnedValue = jsonArray.getChar(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getInt method, of class JsonArray. + */ + @Test + public void testGetInt() { + //arrange + int expectedValue = 10; + int returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addInt(10); + //act + returnedValue = jsonArray.getInt(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getLong method, of class JsonArray. + */ + @Test + public void testGetLong() { + //arrange + long expectedValue = 10l; + long returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addLong(10l); + //act + returnedValue = jsonArray.getLong(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getFloat method, of class JsonArray. + */ + @Test + public void testGetFloat() { + //arrange + float expectedValue = 10.4f; + float returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addFloat(10.4f); + //act + returnedValue = jsonArray.getFloat(0); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of getDouble method, of class JsonArray. + */ + @Test + public void testGetDouble() { + //arrange + double expectedValue = 10.4d; + double returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addDouble(10.4d); + //act + returnedValue = jsonArray.getDouble(0); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of updateNull method, of class JsonArray. + */ + @Test + public void testUpdateNull() { + //arrange + JsonValueType expectedValue = JsonValueType.NULL; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addDouble(10.4d); + jsonArray.updateNull(0); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateObject method, of class JsonArray. + */ + @Test + public void testUpdateObject() { + //arrange + JsonValueType expectedValue = JsonValueType.OBJECT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateObject(0, new JsonObject()); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateArray method, of class JsonArray. + */ + @Test + public void testUpdateArray() { + //arrange + JsonValueType expectedValue = JsonValueType.ARRAY; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateArray(0, new JsonArray()); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateBoolean method, of class JsonArray. + */ + @Test + public void testUpdateBoolean() { + //arrange + JsonValueType expectedValue = JsonValueType.BOOLEAN; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateBoolean(0, true); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateString method, of class JsonArray. + */ + @Test + public void testUpdateString() { + //arrange + JsonValueType expectedValue = JsonValueType.STRING; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateString(0, "String"); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateChar method, of class JsonArray. + */ + @Test + public void testUpdateChar() { + //arrange + JsonValueType expectedValue = JsonValueType.CHAR; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateChar(0, 'S'); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateInt method, of class JsonArray. + */ + @Test + public void testUpdateInt() { + //arrange + JsonValueType expectedValue = JsonValueType.INT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateInt(0, 10); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateLong method, of class JsonArray. + */ + @Test + public void testUpdateLong() { + //arrange + JsonValueType expectedValue = JsonValueType.LONG; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateLong(0, 10l); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateFloat method, of class JsonArray. + */ + @Test + public void testUpdateFloat() { + //arrange + JsonValueType expectedValue = JsonValueType.FLOAT; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateFloat(0, 10.4f); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateDouble method, of class JsonArray. + */ + @Test + public void testUpdateDouble() { + //arrange + JsonValueType expectedValue = JsonValueType.DOUBLE; + JsonValueType returnedValue; + + JsonArray jsonArray = new JsonArray(); + jsonArray.addNull(); + jsonArray.updateDouble(0, 10.4d); + //act + returnedValue = jsonArray.getJsonValueType(0); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of removeJsonValue method, of class JsonArray. + */ + @Test + public void testRemoveJsonValue() { + //arrange + boolean isExceptionThrown = false; + JsonArray jsonArray = new JsonArray(); + jsonArray.addChar('g'); + //act + jsonArray.removeJsonValue(0); + try { + jsonArray.getChar(0); + } catch (Exception e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonValue method, of class JsonArray. + */ + @Test + public void testGetJsonValue() { + //arrange + int expectedValue = 4; + int returnedValue; + JsonValue jsonValue; + JsonArray jsonArray = new JsonArray(); + jsonArray.addInt(4);//act + jsonValue = jsonArray.getJsonValue(0); + returnedValue = jsonValue.getJsonInt().getInt(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of toMinimalString method, of class JsonArray. + */ + @Test + public void testToMinimalString() { + //arrange + String expectedString = "[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492]"; + String returnedString; + + JsonArray propertyOfJohnBlack = new JsonArray(); + propertyOfJohnBlack.addNull(); + + JsonObject computerOfJohnBlack = new JsonObject(); + computerOfJohnBlack.addString("type", "computer"); + computerOfJohnBlack.addString("cpu", "corei7"); + computerOfJohnBlack.addString("ram", "16GB"); + + propertyOfJohnBlack.addObject(computerOfJohnBlack); + + JsonArray memoryCards = new JsonArray(); + memoryCards.addString("8GB memory card"); + memoryCards.addString("16GB memory card"); + memoryCards.addString("32GB memory card"); + memoryCards.addString("128GB memory card"); + + propertyOfJohnBlack.addArray(memoryCards); + + propertyOfJohnBlack.addBoolean(true); + propertyOfJohnBlack.addString("car"); + propertyOfJohnBlack.addChar('y'); + propertyOfJohnBlack.addInt(42); + propertyOfJohnBlack.addLong(9987987998798l); + propertyOfJohnBlack.addFloat(4.56f); + propertyOfJohnBlack.addDouble(1.646659262492d); + + //act + returnedString = propertyOfJohnBlack.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of toPrettyString method, of class JsonArray. + */ + @Test + public void testToPrettyString() { + //arrange + String expectedString = "[\n null,\n {\n \"type\":\"computer\",\n \"cpu\":\"corei7\",\n \"ram\":\"16GB\"\n },\n [\n \"8GB memory card\",\n \"16GB memory card\",\n \"32GB memory card\",\n \"128GB memory card\"\n ],\n true,\n \"car\",\n \"y\",\n 42,\n 9987987998798,\n 4.56,\n 1.646659262492\n]"; + String returnedString; + + JsonArray propertyOfJohnBlack = new JsonArray(); + propertyOfJohnBlack.addNull(); + + JsonObject computerOfJohnBlack = new JsonObject(); + computerOfJohnBlack.addString("type", "computer"); + computerOfJohnBlack.addString("cpu", "corei7"); + computerOfJohnBlack.addString("ram", "16GB"); + + propertyOfJohnBlack.addObject(computerOfJohnBlack); + + JsonArray memoryCards = new JsonArray(); + memoryCards.addString("8GB memory card"); + memoryCards.addString("16GB memory card"); + memoryCards.addString("32GB memory card"); + memoryCards.addString("128GB memory card"); + + propertyOfJohnBlack.addArray(memoryCards); + + propertyOfJohnBlack.addBoolean(true); + propertyOfJohnBlack.addString("car"); + propertyOfJohnBlack.addChar('y'); + propertyOfJohnBlack.addInt(42); + propertyOfJohnBlack.addLong(9987987998798l); + propertyOfJohnBlack.addFloat(4.56f); + propertyOfJohnBlack.addDouble(1.646659262492d); + + //act + returnedString = propertyOfJohnBlack.toPrettyString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of getCopy method, of class JsonArray. + */ + @Test + public void testGetCopy() { + + String expectedString = "[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492]"; + String returnedString; + + JsonArray property = new JsonArray(expectedString); + JsonArray propertyCopy; + + //act + propertyCopy = property.getCopy(); + returnedString = propertyCopy.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java b/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java new file mode 100644 index 0000000..bff39e7 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java @@ -0,0 +1,1214 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.collections.DictionaryKeyIterator; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class JsonObjectTest { + + /** + * + */ + public JsonObjectTest() { + } + + /** + * Test of constructor, of class JsonObject. + */ + @Test + public void testJsonObject() { + //arrange + String expectedString = "{\"date of death\":null,\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"},\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"},\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492],\"is rich\":true,\"name\":\"John\",\"surname\":\"Black\",\"date of birth\":\"1975-09-23\",\"favorit letter\":\"W\",\"year of birth\":1975,\"favorit very long number\":8798799845647987,\"height\":173.5466,\"height- high precision\":173.54666549879545}"; + String returnedString; + + JsonObject personJohnBlack; + + //act + personJohnBlack = new JsonObject(expectedString); + returnedString = personJohnBlack.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of getCountOfItems method, of class JsonObject. + */ + @Test + public void testGetCountOfItems() { + //arrange + JsonObject jsonObject = new JsonObject(); + int expectedValue = 4; + int returnedValue; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + returnedValue = jsonObject.getCountOfItems(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class JsonObject. + */ + @Test + public void testIsEmpty() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + returnedValue = jsonObject.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class JsonObject. + */ + @Test + public void testIsEmpty2() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = false; + boolean returnedValue; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + returnedValue = jsonObject.isEmpty(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class JsonObject. + */ + @Test + public void testContainsValueWithKey() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + returnedValue = jsonObject.containsValueWithKey("nick"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class JsonObject. + */ + @Test + public void testContainsValueWithKey2() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = false; + boolean returnedValue; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + returnedValue = jsonObject.containsValueWithKey("nationality"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsValueWithKey method, of class JsonObject. + */ + @Test + public void testContainsValueWithKey3() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addString("personality", "calm"); + returnedValue = jsonObject.containsValueWithKey("personality"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsNull() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.NULL; + JsonValueType returnedValue; + //act + jsonObject.add("nothing", null); + returnedValue = jsonObject.getJsonValueType("nothing"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsJsonObject() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.OBJECT; + JsonValueType returnedValue; + //act + jsonObject.add("object", new JsonObject()); + returnedValue = jsonObject.getJsonValueType("object"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsJsonArray() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.ARRAY; + JsonValueType returnedValue; + //act + jsonObject.add("array", new JsonArray()); + returnedValue = jsonObject.getJsonValueType("array"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsBoolean() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.BOOLEAN; + JsonValueType returnedValue; + //act + jsonObject.add("boolean", true); + returnedValue = jsonObject.getJsonValueType("boolean"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsString() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.STRING; + JsonValueType returnedValue; + //act + jsonObject.add("String", "some text"); + returnedValue = jsonObject.getJsonValueType("String"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsChar() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.CHAR; + JsonValueType returnedValue; + //act + jsonObject.add("char", 'a'); + returnedValue = jsonObject.getJsonValueType("char"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsInt() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.INT; + JsonValueType returnedValue; + //act + jsonObject.add("int", 2); + returnedValue = jsonObject.getJsonValueType("int"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsLong() {//arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.LONG; + JsonValueType returnedValue; + //act + jsonObject.add("long", 2l); + returnedValue = jsonObject.getJsonValueType("long"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsFloat() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.FLOAT; + JsonValueType returnedValue; + //act + jsonObject.add("float", 2.5f); + returnedValue = jsonObject.getJsonValueType("float"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class JsonObject. + */ + @Test + public void testAdd_ObjectIsDouble() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.DOUBLE; + JsonValueType returnedValue; + //act + jsonObject.add("double", 2.5d); + returnedValue = jsonObject.getJsonValueType("double"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addNull method, of class JsonObject. + */ + @Test + public void testAddNull() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addNull("nothing"); + returnedValue = jsonObject.containsValueWithKey("nothing"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addObject method, of class JsonObject. + */ + @Test + public void testAddObject() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addObject("object", new JsonObject()); + returnedValue = jsonObject.containsValueWithKey("object"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addArray method, of class JsonObject. + */ + @Test + public void testAddArray() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addArray("array", new JsonArray()); + returnedValue = jsonObject.containsValueWithKey("array"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addBoolean method, of class JsonObject. + */ + @Test + public void testAddBoolean() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addBoolean("boolean", true); + returnedValue = jsonObject.containsValueWithKey("boolean"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addString method, of class JsonObject. + */ + @Test + public void testAddString() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addString("String", "some text"); + returnedValue = jsonObject.containsValueWithKey("String"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addChar method, of class JsonObject. + */ + @Test + public void testAddChar() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addChar("char", 'a'); + returnedValue = jsonObject.containsValueWithKey("char"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addInt method, of class JsonObject. + */ + @Test + public void testAddInt() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addInt("int", 2); + returnedValue = jsonObject.containsValueWithKey("int"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addLong method, of class JsonObject. + */ + @Test + public void testAddLong() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addLong("long", 2l); + returnedValue = jsonObject.containsValueWithKey("long"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addFloat method, of class JsonObject. + */ + @Test + public void testAddFloat() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addFloat("float", 2.5f); + returnedValue = jsonObject.containsValueWithKey("float"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of addDouble method, of class JsonObject. + */ + @Test + public void testAddDouble() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + returnedValue = jsonObject.containsValueWithKey("double"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Null() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.NULL; + JsonValueType returnedValue; + //act + jsonObject.addNull("nothing"); + returnedValue = jsonObject.getJsonValueType("nothing"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Object() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.OBJECT; + JsonValueType returnedValue; + //act + jsonObject.addObject("object", new JsonObject()); + returnedValue = jsonObject.getJsonValueType("object"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Array() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.ARRAY; + JsonValueType returnedValue; + //act + jsonObject.addArray("array", new JsonArray()); + returnedValue = jsonObject.getJsonValueType("array"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Boolean() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.BOOLEAN; + JsonValueType returnedValue; + //act + jsonObject.addBoolean("boolean", true); + returnedValue = jsonObject.getJsonValueType("boolean"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_String() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.STRING; + JsonValueType returnedValue; + //act + jsonObject.addString("String", "some text"); + returnedValue = jsonObject.getJsonValueType("String"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Char() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.CHAR; + JsonValueType returnedValue; + //act + jsonObject.addChar("char", 'a'); + returnedValue = jsonObject.getJsonValueType("char"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Int() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.INT; + JsonValueType returnedValue; + //act + jsonObject.addInt("int", 2); + returnedValue = jsonObject.getJsonValueType("int"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Long() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.LONG; + JsonValueType returnedValue; + //act + jsonObject.addLong("long", 2l); + returnedValue = jsonObject.getJsonValueType("long"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Float() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.FLOAT; + JsonValueType returnedValue; + //act + jsonObject.addFloat("float", 2.5f); + returnedValue = jsonObject.getJsonValueType("float"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonValueType method, of class JsonObject. + */ + @Test + public void testGetJsonValueType_Double() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType expectedValue = JsonValueType.DOUBLE; + JsonValueType returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + returnedValue = jsonObject.getJsonValueType("double"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of get method, of class JsonObject. + */ + @Test + public void testGet() { + //arrange + JsonObject jsonObject = new JsonObject(); + int expectedValue = 2; + int returnedValue; + //act + jsonObject.addInt("int", 2); + returnedValue = (int) jsonObject.get("int"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getObject method, of class JsonObject. + */ + @Test + public void testGetObject() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonObject jsonObjectToReturn = new JsonObject(); + String expectedString = "object"; + String returnedString; + //act + jsonObjectToReturn.addString("name", "object"); + jsonObject.addObject("object to return", jsonObjectToReturn); + returnedString = jsonObject.getObject("object to return").getString("name"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getArray method, of class JsonObject. + */ + @Test + public void testGetArray() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonArray jsonArrayToReturn = new JsonArray(); + String expectedString = "array"; + String returnedString; + //act + jsonArrayToReturn.addString("array"); + jsonObject.addArray("array to return", jsonArrayToReturn); + returnedString = jsonObject.getArray("array to return").getString(0); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getBoolean method, of class JsonObject. + */ + @Test + public void testGetBoolean() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addBoolean("boolean", true); + returnedValue = jsonObject.getBoolean("boolean"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getString method, of class JsonObject. + */ + @Test + public void testGetString() { + //arrange + JsonObject jsonObject = new JsonObject(); + String expectedString = "some text"; + String returnedString; + //act + jsonObject.addString("String", "some text"); + returnedString = jsonObject.getString("String"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getChar method, of class JsonObject. + */ + @Test + public void testGetChar() { + //arrange + JsonObject jsonObject = new JsonObject(); + char expectedValue = 'a'; + char returnedValue; + //act + jsonObject.addChar("char", 'a'); + returnedValue = jsonObject.getChar("char"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getInt method, of class JsonObject. + */ + @Test + public void testGetInt() { + //arrange + JsonObject jsonObject = new JsonObject(); + int expectedValue = 2; + int returnedValue; + //act + jsonObject.addInt("int", 2); + returnedValue = jsonObject.getInt("int"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getLong method, of class JsonObject. + */ + @Test + public void testGetLong() { + //arrange + JsonObject jsonObject = new JsonObject(); + long expectedValue = 2l; + long returnedValue; + //act + jsonObject.addLong("long", 2l); + returnedValue = jsonObject.getLong("long"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getFloat method, of class JsonObject. + */ + @Test + public void testGetFloat() { + //arrange + JsonObject jsonObject = new JsonObject(); + float expectedValue = 2.5f; + float returnedValue; + //act + jsonObject.addFloat("float", 2.5f); + returnedValue = jsonObject.getFloat("float"); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of getDouble method, of class JsonObject. + */ + @Test + public void testGetDouble() { + //arrange + JsonObject jsonObject = new JsonObject(); + double expectedValue = 2.5d; + double returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + returnedValue = jsonObject.getDouble("double"); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of update method, of class JsonObject. + */ + @Test + public void testUpdate() { + //arrange + JsonObject jsonObject = new JsonObject(); + double expectedValue = 2.8d; + double returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.update("double", 2.8d); + returnedValue = jsonObject.getDouble("double"); + //assert + assertEquals(expectedValue, returnedValue, 0); + } + + /** + * Test of updateNull method, of class JsonObject. + */ + @Test + public void testUpdateNull() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateNull("double"); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.NULL; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateObject method, of class JsonObject. + */ + @Test + public void testUpdateObject() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateObject("double", new JsonObject()); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.OBJECT; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateArray method, of class JsonObject. + */ + @Test + public void testUpdateArray() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateArray("double", new JsonArray()); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.ARRAY; + //assert + assertEquals(expectedValue, returnedValue); + + } + + /** + * Test of updateString method, of class JsonObject. + */ + @Test + public void testUpdateString() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateString("double", "some text"); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.STRING; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateBoolean method, of class JsonObject. + */ + @Test + public void testUpdateBoolean() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addString("Is Bob rich?", "no"); + jsonObject.updateBoolean("Is Bob rich?", true); + returnedValue = jsonObject.getJsonValueType("Is Bob rich?") == JsonValueType.BOOLEAN; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateChar method, of class JsonObject. + */ + @Test + public void testUpdateChar() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateChar("double", 'a'); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.CHAR; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateInt method, of class JsonObject. + */ + @Test + public void testUpdateInt() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateInt("double", 2); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.INT; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateLong method, of class JsonObject. + */ + @Test + public void testUpdateLong() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateLong("double", 2l); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.LONG; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateFloat method, of class JsonObject. + */ + @Test + public void testUpdateFloat() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addDouble("double", 2.5d); + jsonObject.updateFloat("double", 2.5f); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.FLOAT; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of updateDouble method, of class JsonObject. + */ + @Test + public void testUpdateDouble() { + //arrange + JsonObject jsonObject = new JsonObject(); + boolean expectedValue = true; + boolean returnedValue; + //act + jsonObject.addFloat("double", 2.5f); + jsonObject.updateDouble("double", 2.5d); + returnedValue = jsonObject.getJsonValueType("double") == JsonValueType.DOUBLE; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of removeJsonValue method, of class JsonObject. + */ + @Test + public void testRemoveJsonValue() { + //arrange + boolean isExceptionThrown = false; + JsonObject jsonObject = new JsonObject(); + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + jsonObject.removeJsonValue("nick"); + try { + jsonObject.getString("nick"); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of toMinimalString method, of class JsonObject. + */ + @Test + public void testToMinimalString() { + //arrange + String expectedString = "{\"date of death\":null,\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"},\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"},\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492],\"is rich\":true,\"name\":\"John\",\"surname\":\"Black\",\"date of birth\":\"1975-09-23\",\"favorit letter\":\"W\",\"year of birth\":1975,\"favorit very long number\":8798799845647987,\"height\":173.5466,\"height- high precision\":173.54666549879545}"; + String returnedString; + + JsonObject personJohnBlack = new JsonObject(); + JsonArray propertyOfJohnBlack = new JsonArray(); + propertyOfJohnBlack.addNull(); + + JsonObject computerOfJohnBlack = new JsonObject(); + computerOfJohnBlack.addString("type", "computer"); + computerOfJohnBlack.addString("cpu", "corei7"); + computerOfJohnBlack.addString("ram", "16GB"); + + propertyOfJohnBlack.addObject(computerOfJohnBlack); + + JsonArray memoryCards = new JsonArray(); + memoryCards.addString("8GB memory card"); + memoryCards.addString("16GB memory card"); + memoryCards.addString("32GB memory card"); + memoryCards.addString("128GB memory card"); + + propertyOfJohnBlack.addArray(memoryCards); + + propertyOfJohnBlack.addBoolean(true); + propertyOfJohnBlack.addString("car"); + propertyOfJohnBlack.addChar('y'); + propertyOfJohnBlack.addInt(42); + propertyOfJohnBlack.addLong(9987987998798l); + propertyOfJohnBlack.addFloat(4.56f); + propertyOfJohnBlack.addDouble(1.646659262492d); + + JsonObject personPeterBlack = new JsonObject(); + personPeterBlack.addString("name", "Peter"); + personPeterBlack.addString("surname", "Black"); + + JsonObject personSueBlack = new JsonObject(); + personSueBlack.addString("name", "Sue"); + personSueBlack.addString("surname", "Black"); + + personJohnBlack.addNull("date of death"); + personJohnBlack.addObject("father", personPeterBlack); + personJohnBlack.addObject("mother", personSueBlack); + personJohnBlack.addArray("property", propertyOfJohnBlack); + personJohnBlack.addBoolean("is rich", true); + personJohnBlack.addString("name", "John"); + personJohnBlack.addString("surname", "Black"); + personJohnBlack.addString("date of birth", "1975-09-23"); + personJohnBlack.addChar("favorit letter", 'W'); + personJohnBlack.addInt("year of birth", 1975); + personJohnBlack.addLong("favorit very long number", 8798799845647987l); + personJohnBlack.addFloat("height", 173.5466f); + personJohnBlack.addDouble("height- high precision", 173.54666549879544659d); + //act + returnedString = personJohnBlack.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of toPrettyString method, of class JsonObject. + */ + @Test + public void testToPrettyString() { + //arrange + String expectedString = "{\n \"date of death\":null,\n \"father\":{\n \"name\":\"Peter\",\n \"surname\":\"Black\"\n },\n \"mother\":{\n \"name\":\"Sue\",\n \"surname\":\"Black\"\n },\n \"property\":[\n null,\n {\n \"type\":\"computer\",\n \"cpu\":\"corei7\",\n \"ram\":\"16GB\"\n },\n [\n \"8GB memory card\",\n \"16GB memory card\",\n \"32GB memory card\",\n \"128GB memory card\"\n ],\n true,\n \"car\",\n \"y\",\n 42,\n 9987987998798,\n 4.56,\n 1.646659262492\n ],\n \"is rich\":true,\n \"name\":\"John\",\n \"surname\":\"Black\",\n \"date of birth\":\"1975-09-23\",\n \"favorit letter\":\"W\",\n \"year of birth\":1975,\n \"favorit very long number\":8798799845647987,\n \"height\":173.5466,\n \"height- high precision\":173.54666549879545\n}"; + String returnedString; + + JsonObject personJohnBlack = new JsonObject(); + JsonArray propertyOfJohnBlack = new JsonArray(); + propertyOfJohnBlack.addNull(); + + JsonObject computerOfJohnBlack = new JsonObject(); + computerOfJohnBlack.addString("type", "computer"); + computerOfJohnBlack.addString("cpu", "corei7"); + computerOfJohnBlack.addString("ram", "16GB"); + + propertyOfJohnBlack.addObject(computerOfJohnBlack); + + JsonArray memoryCards = new JsonArray(); + memoryCards.addString("8GB memory card"); + memoryCards.addString("16GB memory card"); + memoryCards.addString("32GB memory card"); + memoryCards.addString("128GB memory card"); + + propertyOfJohnBlack.addArray(memoryCards); + + propertyOfJohnBlack.addBoolean(true); + propertyOfJohnBlack.addString("car"); + propertyOfJohnBlack.addChar('y'); + propertyOfJohnBlack.addInt(42); + propertyOfJohnBlack.addLong(9987987998798l); + propertyOfJohnBlack.addFloat(4.56f); + propertyOfJohnBlack.addDouble(1.646659262492d); + + JsonObject personPeterBlack = new JsonObject(); + personPeterBlack.addString("name", "Peter"); + personPeterBlack.addString("surname", "Black"); + + JsonObject personSueBlack = new JsonObject(); + personSueBlack.addString("name", "Sue"); + personSueBlack.addString("surname", "Black"); + + personJohnBlack.addNull("date of death"); + personJohnBlack.addObject("father", personPeterBlack); + personJohnBlack.addObject("mother", personSueBlack); + personJohnBlack.addArray("property", propertyOfJohnBlack); + personJohnBlack.addBoolean("is rich", true); + personJohnBlack.addString("name", "John"); + personJohnBlack.addString("surname", "Black"); + personJohnBlack.addString("date of birth", "1975-09-23"); + personJohnBlack.addChar("favorit letter", 'W'); + personJohnBlack.addInt("year of birth", 1975); + personJohnBlack.addLong("favorit very long number", 8798799845647987l); + personJohnBlack.addFloat("height", 173.5466f); + personJohnBlack.addDouble("height- high precision", 173.54666549879544659d); + //act + returnedString = personJohnBlack.toPrettyString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of getCopy method, of class JsonObject. + */ + @Test + public void testGetCopy() { + //arrange + String expectedString = "{\"date of death\":null,\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"},\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"},\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492],\"is rich\":true,\"name\":\"John\",\"surname\":\"Black\",\"date of birth\":\"1975-09-23\",\"favorit letter\":\"W\",\"year of birth\":1975,\"favorit very long number\":8798799845647987,\"height\":173.5466,\"height- high precision\":173.54666549879545}"; + String returnedString; + + JsonObject personJohnBlack = new JsonObject(expectedString); + JsonObject personJohnBlackCopy; + + //act + personJohnBlackCopy = personJohnBlack.getCopy(); + returnedString = personJohnBlackCopy.toMinimalString(); + //assert + boolean result = expectedString.equals(returnedString); + assertEquals(expectedString, returnedString); + } + + /** + * Test of getKeyIterator method, of class JsonObject. + */ + @Test + public void testGetKeyIterator() { + //arrange + JsonObject jsonObject = new JsonObject(); + DictionaryKeyIterator dictionaryKeyIterator; + String expectedString = "name"; + String returnedString; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + dictionaryKeyIterator = jsonObject.getKeyIterator(); + dictionaryKeyIterator.getNextKey(); + dictionaryKeyIterator.getNextKey(); + returnedString = dictionaryKeyIterator.getNextKey();; + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getJsonValue method, of class JsonObject. + */ + @Test + public void testGetJsonValue() { + //arrange + JsonObject jsonObject = new JsonObject(); + DictionaryKeyIterator dictionaryKeyIterator; + String expectedString = "John"; + String returnedString; + //act + jsonObject.addString("personality", "calm"); + jsonObject.addString("nick", "Johny"); + jsonObject.addString("name", "John"); + jsonObject.addInt("age", 43); + + returnedString = jsonObject.getJsonValue("name").getJsonString().getString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java b/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java new file mode 100644 index 0000000..cd4a4bf --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java @@ -0,0 +1,432 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.PowerRuntimeException; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class JsonValueTest { + + /** + * + */ + public JsonValueTest() { + } + + /** + * Test of getJsonValueType method, of class JsonValue. + */ + @Test + public void testGetJsonValueType() { + //arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.STRING; + JsonString jsonString; + //act + jsonString = new JsonString("hello"); + jsonValue = new JsonValue(jsonString); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isNull method, of class JsonValue. + */ + @Test + public void testIsNull() { + //arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.NULL; + //act + jsonValue = new JsonValue(); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isObject method, of class JsonValue. + */ + @Test + public void testIsObject() { + //arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.OBJECT; + JsonObject jsonObject; + //act + jsonObject = new JsonObject(); + jsonValue = new JsonValue(jsonObject); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isArray method, of class JsonValue. + */ + @Test + public void testIsArray() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.ARRAY; + JsonArray jsonArray; + //act + jsonArray = new JsonArray(); + jsonValue = new JsonValue(jsonArray); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isBoolean method, of class JsonValue. + */ + @Test + public void testIsBoolean() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.BOOLEAN; + JsonBoolean jsonBoolean; + //act + jsonBoolean = new JsonBoolean(true); + jsonValue = new JsonValue(jsonBoolean); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isString method, of class JsonValue. + */ + @Test + public void testIsString() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.STRING; + JsonString jsonString; + //act + jsonString = new JsonString("hello"); + jsonValue = new JsonValue(jsonString); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isChar method, of class JsonValue. + */ + @Test + public void testIsChar() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.CHAR; + JsonChar jsonChar; + //act + jsonChar = new JsonChar('h'); + jsonValue = new JsonValue(jsonChar); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isInt method, of class JsonValue. + */ + @Test + public void testIsInt() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.INT; + JsonInt jsonInt; + //act + jsonInt = new JsonInt(549); + jsonValue = new JsonValue(jsonInt); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isLong method, of class JsonValue. + */ + @Test + public void testIsLong() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.LONG; + JsonLong jsonLong; + //act + jsonLong = new JsonLong(4l); + jsonValue = new JsonValue(jsonLong); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isFloat method, of class JsonValue. + */ + @Test + public void testIsFloat() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.FLOAT; + JsonFloat jsonFloat; + //act + jsonFloat = new JsonFloat(8.6f); + jsonValue = new JsonValue(jsonFloat); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isDouble method, of class JsonValue. + */ + @Test + public void testIsDouble() { +//arrange + JsonValue jsonValue; + JsonValueType expectedValue; + JsonValueType returnedValue = JsonValueType.DOUBLE; + JsonDouble jsonDouble; + //act + jsonDouble = new JsonDouble(8.6d); + jsonValue = new JsonValue(jsonDouble); + expectedValue = jsonValue.getJsonValueType(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getJsonObject method, of class JsonValue. + */ + @Test + public void testGetJsonObject() { + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonObject(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonArray method, of class JsonValue. + */ + @Test + public void testGetJsonArray() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonArray(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonBoolean method, of class JsonValue. + */ + @Test + public void testGetJsonBoolean() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonBoolean(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonString method, of class JsonValue. + */ + @Test + public void testGetJsonString() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonString(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (isExceptionThrown) { + fail("There should be thrown no PowerRuntimeException"); + } + } + + /** + * Test of getJsonChar method, of class JsonValue. + */ + @Test + public void testGetJsonChar() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonChar(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonInt method, of class JsonValue. + */ + @Test + public void testGetJsonInt() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonInt(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonLong method, of class JsonValue. + */ + @Test + public void testGetJsonLong() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonLong(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonFloat method, of class JsonValue. + */ + @Test + public void testGetJsonFloat() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonFloat(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + + /** + * Test of getJsonDouble method, of class JsonValue. + */ + @Test + public void testGetJsonDouble() { + + //arrange + boolean isExceptionThrown = false; + JsonString jsonString = new JsonString("hello"); + JsonValue jsonValue = new JsonValue(jsonString); + //act + try { + jsonValue.getJsonDouble(); + } catch (PowerRuntimeException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown PowerRuntimeException"); + } + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java b/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java new file mode 100644 index 0000000..51daf65 --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java @@ -0,0 +1,125 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.pseudorandom; + +import org.nanoboot.powerframework.datetime.DateTime; +import org.nanoboot.powerframework.datetime.LocalDateTime; +import org.nanoboot.powerframework.datetime.UniversalDateTime; +import org.nanoboot.powerframework.json.JsonArray; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class PseudoRandomGeneratorTest { + + public PseudoRandomGeneratorTest() { + } + + /** + * Test of getLong method, of class PseudoRandomGenerator. + */ + @Test + public void testGetLong() { + //arrange + PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); + + long expectedValue = 420726198994l; + long returnedValue; + //act + for (int i = 1; i <= 4; i++) { + pseudoRandomGenerator.getLong(0, 499999999999l); + } + returnedValue = pseudoRandomGenerator.getLong(0, 499999999999l); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getInt method, of class PseudoRandomGenerator. + */ + @Test + public void testGetInt() { + //arrange + PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); + + int expectedValue = 198994; + int returnedValue; + //act + for (int i = 1; i <= 4; i++) { + pseudoRandomGenerator.getInt(0, 499999); + } + returnedValue = pseudoRandomGenerator.getInt(0, 499999); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getBoolean method, of class PseudoRandomGenerator. + */ + @Test + public void testGetBoolean() { + //arrange + PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); + JsonArray jsonArray = new JsonArray(); + String expectedString = "[true,false,false,true,false,false,false,false,true,true,false,true,false,false,true,true,true,true,true,false,true,true,false,true,true,false,false,true,true,false,false,false,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true,false,false,false]"; + String returnedString; + //act + for (int i = 1; i <= 50; i++) { + jsonArray.addBoolean(pseudoRandomGenerator.getBoolean()); + } + returnedString = jsonArray.toMinimalString(); + //assert + assertEquals(expectedString, returnedString); + } + + @Test + public void testTheSame100thOrderHasTheSame() { + //arrange + int magicNumber = PseudoRandomGenerator.getInstance().getInt(0, 1000000); + DateTime dateTime = UniversalDateTime.getRandomUniversalDateTime(); + PseudoRandomGenerator pseudoRandomGenerator; + pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, dateTime); + for (int i = 1; i < 100; i++) { + pseudoRandomGenerator.getInt(0, 1000000); + } + int expectedValue = pseudoRandomGenerator.getInt(0, 1000000); + int returnedValue; + + pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, dateTime); + for (int i = 1; i < 100; i++) { + if (PseudoRandomGenerator.getInstance().getBoolean()) { + pseudoRandomGenerator.getBoolean(); + } else if (PseudoRandomGenerator.getInstance().getBoolean()) { + pseudoRandomGenerator.getInt(0, PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + } else { + pseudoRandomGenerator.getLong(0, PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + } + } + //act + returnedValue = pseudoRandomGenerator.getInt(0, 1000000); + //assert + assertEquals(expectedValue, returnedValue); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java b/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java new file mode 100644 index 0000000..7c2eb5c --- /dev/null +++ b/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java @@ -0,0 +1,71 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// 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; +// version 2.1 of the License only. +// +// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.pseudorandom; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author Robert Vokac e-mail: robertvokac@nanoboot.org + */ +public class SeedTest { + + public SeedTest() { + } + + /** + * Test of getNextNumber method, of class Seed. + */ + @Test + public void testGetNextNumber() { + //arrange + Seed seed = new Seed(5); + long expectedValue = 1679444804; + long returnedValue; + //act + for (int i = 1; i <= 37; i++) { + seed.getNextNumber(); + } + returnedValue = seed.getNextNumber(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of jump method, of class Seed. + */ + @Test + public void testJump() { + //arrange + Seed seed = new Seed(5); + long expectedValue = 1679444804; + long returnedValue; + //act + for (int i = 1; i <= 37; i++) { + seed.jump(); + } + returnedValue = seed.getNextNumber(); + //assert + assertEquals(expectedValue, returnedValue); + } + +}