Released: power-framework 1.0.0

This commit is contained in:
Robert Vokac 2023-03-18 11:13:51 +01:00
parent 936a0b9f9e
commit 273e1a8647
No known key found for this signature in database
GPG Key ID: 693D30BEE3329055
108 changed files with 17511 additions and 0 deletions

16
CREDITS Normal file
View File

@ -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

502
LICENSE Executable file
View File

@ -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.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

7
README.md Normal file
View File

@ -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)

73
pom.xml Normal file
View File

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.nanoboot.powerframework</groupId>
<artifactId>power-framework</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Power Framework</name>
<description>A library with many possibilities</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<checkstyle.skip>true</checkstyle.skip><!-- TODO: make false-->
<javase.version>8</javase.version>
</properties>
<dependencies>
<!-- Other dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.39.3.0</version>
</dependency>
<!-- <dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>19</version>
</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${javase.version}</source>
<target>${javase.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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);
}
}

View File

@ -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 <T>
*/
public class Dictionary<T> {
private int countOfItems = 0;
private DictionaryNode<T> currentNode = null;
private DictionaryNode<T> stopNode = null;
private DictionaryNode<T> firstNode = null;
private DictionaryNode<T> lastNode = null;
private DictionaryNode<T> tempNode = null;
private DictionaryNode<T> 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<T> addValue(String key, T value) {
DictionaryNode<T> 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<T> 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();
}
}

View File

@ -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;
}
}

View File

@ -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<T> {
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;
}
}

View File

@ -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 <T> object
*/
public class Queue<T> {
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<T> 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();
}
}

View File

@ -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 <T> object
*/
public class Stack<T> implements Iterable<T> {
private int total = 0;
private Node first;
@Override
public Iterator<T> iterator() {
return new StackIterator();
}
private class Node {
private T element;
private Node next;
}
private class StackIterator implements Iterator<T> {
@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<T> 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();
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<Integer> 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();
}
}

View File

@ -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<String> 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();
}
}

View File

@ -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();
}
}

View File

@ -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<Integer> 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));
}
}

View File

@ -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
*
* <br><br>Example<br>
* <br>
* Duration duration=new Duration(6,19,46,12,754);<br>
* long days=duration.getDays();<br>
* <br>
* days is 6
*/
public long getDays() {
return days;
}
/**
*
* @return count of hours
*
* <br><br>Example<br>
* <br>
* Duration duration=new Duration(6,19,46,12,754);<br>
* long hours=duration.getHours();<br>
* <br>
* hours is 19
*/
public int getHours() {
return hours;
}
/**
*
* @return count of minutes
*
* <br><br>Example<br>
* <br>
* Duration duration=new Duration(6,19,46,12,754);<br>
* long minutes=duration.getMinutes();<br>
* <br>
* minutes is 46
*/
public int getMinutes() {
return minutes;
}
/**
*
* @return count of seconds
*
* <br><br>Example<br>
* <br>
* Duration duration=new Duration(6,19,46,12,754);<br>
* long seconds=duration.getSeconds();<br>
* <br>
* seconds is 12
*/
public int getSeconds() {
return seconds;
}
/**
*
* @return count of milliseconds
*
* <br><br>Example<br>
* <br>
* Duration duration=new Duration(6,19,46,12,754);<br>
* long milliseconds=duration.Milliseconds();<br>
* <br>
* 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();
}
}

View File

@ -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.<br />
* This will throw PowerRuntimeException:
* {@code new LocalDateTime(2015,2,29)}<br />
* This will throw PowerRuntimeException:
* {@code new LocalDateTime(2013,6,31)}<br />
* This will not throw PowerRuntimeException:
* {@code new LocalDateTime(2013,6,30)}<br />
*/
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();
}
}

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -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;
}
}

View File

@ -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.");
}
}
}

View File

@ -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<String> 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<String> 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();
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,4 @@
/**
* This package contains date and time utilities.
*/
package org.nanoboot.powerframework.datetime;

View File

@ -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<JsonValue> 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);
}
}

View File

@ -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<Integer> 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);
}
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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<JsonValue> 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);
}
}

View File

@ -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<Integer> 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;
}
}

View File

@ -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();
}
}

View File

@ -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<Integer> getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(String collectionsOfValuesOfTheJsonArrayString) {
int nesting = 0;
ArrayList<Integer> 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 == ']');
}
}

View File

@ -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()));
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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.");
}
}
}

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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;

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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
* <p>
* ordinal number of enum colour</p>
* <p>
* Converts EnumColour to int.</p>
*/
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);
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}

View File

@ -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);
}
}

View File

@ -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() {
}
}

View File

@ -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);
}
}

View File

@ -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<RowConstraints>();
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<ColumnConstraints>();
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;
}
}

View File

@ -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;
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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<WindowEvent>() {
@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();
}

View File

@ -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();
}
}

View File

@ -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;
}

View File

@ -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();
}
}

View File

@ -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 {
}

View File

@ -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 + ";");
}
}

View File

@ -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);
}
}

View File

@ -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 {
}

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -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()));
}
}

View File

@ -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.
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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();
}

View File

View File

@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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);
}
}

View File

@ -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<String> 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<String> 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<String> dictionaryNode = new DictionaryNode<>("name", "John");
DictionaryNode<String> dictionaryNode2 = new DictionaryNode<>("surname", "Black");
String expectedString = "Black";
String returnedString;
//act
dictionaryNode.setNext(dictionaryNode2);
DictionaryNode<String> returnedDictionaryNode = dictionaryNode.getNext();
returnedString = returnedDictionaryNode.getElement();
//assert
assertEquals(expectedString, returnedString);
}
/**
* Test of setNext method, of class DictionaryNode.
*/
@Test
public void testSetNext() {
//arrange
DictionaryNode<String> dictionaryNode = new DictionaryNode<>("name", "John");
DictionaryNode<String> dictionaryNode2 = new DictionaryNode<>("surname", "White");
String expectedString = "White";
String returnedString;
//act
dictionaryNode.setNext(dictionaryNode2);
DictionaryNode<String> returnedDictionaryNode = dictionaryNode.getNext();
returnedString = returnedDictionaryNode.getElement();
//assert
assertEquals(expectedString, returnedString);
}
/**
* Test of getKey method, of class DictionaryNode.
*/
@Test
public void testGetKey() {
//arrange
DictionaryNode<String> 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<String> dictionaryNode = new DictionaryNode<>("name", "John");
String expectedString = "nick";
String returnedString;
//act
dictionaryNode.setKey("nick");
returnedString = dictionaryNode.getKey();
//assert
assertEquals(expectedString, returnedString);
}
}

View File

@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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);
}
}

View File

@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> queue = new Queue<>();
String expectedString = "Alice, Jane, ";
String returnedString;
//act
queue.enqueue("Alice").enqueue("Jane");
returnedString = queue.toString();
//assert
assertEquals(expectedString, returnedString);
}
}

View File

@ -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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> 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<String> stack = new Stack<>();
String expectedString = "Jane, Alice, ";
String returnedString;
//act
stack.push("Alice").push("Jane");
returnedString = stack.toString();
//assert
assertEquals(expectedString, returnedString);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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");
}
}
}

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