Compare commits

...

19 Commits

Author SHA1 Message Date
3ef40e52af
Improvements 2024-12-27 19:02:46 +01:00
bcb9956c6e
Changes 2024-12-27 18:34:07 +01:00
5c58cecb61
Migrated to GPL v3 and robertvokac.com 2024-10-13 12:31:00 +02:00
50eb74906e
Working on documentation - wip 2 2024-05-21 21:08:51 +02:00
a9ae731309
Working on documentation - wip 1 2024-05-21 20:48:30 +02:00
8b4beeccb5
Text bib was replaced by bitbackup 2024-05-08 18:32:35 +02:00
ddae394534
Fixed several small issues 2024-05-01 18:56:58 +02:00
845c5ebe49
Renamed to Bit Backup II 2024-05-01 12:29:05 +02:00
af0c107d6a
Renamed to Bit Backup 2024-05-01 11:31:00 +02:00
Robert Vokac
ef26009a09
Updated README.md 2023-11-05 11:35:03 +01:00
Robert Vokac
5280c45f04
Added Jenkins support 2023-09-28 19:29:20 +02:00
Robert Vokac
72e5214000
README.md was improved 2023-09-28 19:22:47 +02:00
Robert Vokac
8ffd191bdd
Adding new features - work in progress #3 2023-08-08 18:54:25 +02:00
Robert Vokac
e7f57aeea8
Adding new features - work in progress #2 2023-08-08 18:24:48 +02:00
Robert Vokac
43cce8a510
Adding new features - work in progress #1 2023-08-08 18:04:04 +02:00
Robert Vokac
e90f9ed36c
Remaining time is now using method toHumanString() of class Duration 2023-08-05 17:37:02 +02:00
Robert Vokac
46eaeb824e
Big refactoring 2023-08-05 17:15:34 +02:00
Robert Vokac
edba08f896
Implemented first working version 2023-07-30 18:48:14 +02:00
Robert Vokac
c6c996339c
README.md was improved 2023-07-30 12:15:51 +02:00
64 changed files with 4535 additions and 265 deletions

4
.gitignore vendored
View File

@ -10,3 +10,7 @@
#*.class
/target/
/nbproject/
*nbactions.xml
.bitbackup.sqlite3**

View File

@ -1,5 +1,5 @@
This file partially lists people, that have contributed to
the "Bit Inspector" project. They are sorted by name.
the "Bit Backup" 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).
@ -9,8 +9,8 @@
----------
N: Robert Vokac
E: robertvokac@nanoboot.org
W: https://nanoboot.org
P: 4096R/E3329055 322B D109 0AA8 C324 EA9C 72F5 693D 30BE E332 9055
E: robertvokac@robertvokac.com
W: https://robertvokac.com
P: 4096R/C459E1E4 255C 69CC 1D09 CA54 EF0C C9DF FB9C E8E2 0AAD A55F
D: Founder
S: Czech Republic

114
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,114 @@
pipeline
/*
Bit Backup
Requirements:
Maven is Installed
Java 21 is installed - variable JAVA_21_HOME is set
*/
{
agent any
environment {
AAA = 'aaa'
}
stages
{
stage('Build')
{
steps {
echo "*** Building ${env.JOB_NAME} ***"
sh '''
#!/bin/bash
echo JOB_NAME=$JOB_NAME
if [ -z "$JAVA_21_HOME" ]
then
echo "KO : Variable JAVA_21_HOME is empty. You fix this issue by adding this variable to configuration of Jenkins."
exit 1
else
echo "OK : Variable JAVA_21_HOME is NOT empty"
fi
export JAVA_HOME=$JAVA_21_HOME
case $BRANCH_NAME in
master | deploy_prod)
mvn clean install
;;
develop | jenkins | deploy_test)
echo Branch $BRANCH_NAME is supported. Continuing.
version=`mvn help:evaluate -Dexpression=project.version -q -DforceStdout`
echo version=$version
case "$version" in
*"SNAPSHOT"*) echo echo version is OK ;;
* ) echo echo "You cannot build releases on Jenkins, only snapshots!"&&exit 1 ;;
esac
mvn clean deploy
;;
*)
echo Branch $BRANCH_NAME is not supported. A failure happened. Exiting.
exit 1
;;
esac
echo "Build of $JOB_NAME was successful"
'''
}
}
stage('Deploy')
{
steps {
echo "*** Deploying ${env.JOB_NAME} ***"
sh '''
#!/bin/bash
echo "Nothing to do"
exit
case $BRANCH_NAME in
master | deploy_prod)
echo Branch $BRANCH_NAME is supported. Continuing.
TOMCAT_HOME=$TOMCAT10_HOME
systemdService=tomcat10
;;
develop | jenkins | deploy_test)
echo Branch $BRANCH_NAME is supported. Continuing.
TOMCAT_HOME=$TOMCAT10_TEST_HOME
systemdService=tomcat10test
;;
*)
echo Branch $BRANCH_NAME is not supported. A failure happened. Exiting.
exit 1
;;
esac
'''
}
}
}
post {
always {
script {
env.color = "${currentBuild.currentResult == 'SUCCESS' ? 'green' : 'red'}"
}
echo 'Sending e-mail.'
sh "printenv | sort"
emailext body: "<b style=\"color:$COLOR\">${currentBuild.currentResult}</b> - ${env.JOB_NAME} (#${env.BUILD_NUMBER})<br> <ul style=\"margin-top:2px;padding-top:2px;padding-left:30px;\"><li>More info at: <a href=\"${env.BUILD_URL}\">${env.BUILD_URL}</a></li></ul>",
recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
subject: "Jenkins Build - ${currentBuild.currentResult} - $JOB_NAME (#$BUILD_NUMBER)"
}
}
}

833
LICENSE
View File

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

183
README.md
View File

@ -1,21 +1,180 @@
# bit-inspector
# bit-backup
Detects bit rotten files in the given directory to keep your files forever.
You can find more information in docs directory.
It is inspired by:
### Feature 2 : Backup of files
* https://github.com/ambv/bitrot
* https://github.com/laktak/chkbit-py
## How it works
You go to a directory.
You run the command bin:
* All files in this directory are inspected, new files are added to the database.
* If the file last modification date in database and on the disk is the same, but the content checksum is different, then a bit rot is detected.
## How to setup your environment on Linux
#### File .bitbackup/bitbackuplog
Contains index number of last bitbackup index.
#### file .bitbackup/description
#### File .bitbackup/config
```
pack-file.files-until-size.mb=100
pack-file.max-size.mb=1000
```
## Commands
bitbackup {command} [{arg1} {arg2} {argn}]
Example:
```
bitbackup clone path=/home/johndoe/mydir url={local path or s3 bucket or FTP server or website url}
```
Arguments
alias bir='java -jar /rv/data/desktop/code/code.nanoboot.org/nanoboot/bit-inspector/target/bir-inspector-0.0.0-SNAPSHOT-jar-with-dependencies.jar'
path={path to directory}
* default:. (current working directory)
### bitrot
Checks for bitrots in current directory
### clone : Cloning a remote repo
```
bitbackup clone {url} [[--bare]] [[revision number|tag]]
```
#### Local
```
bitbackup clone {path to another local Bit Backup repository - path to directory}
```
#### S3
```
bitbackup clone s3://http[s]://{endpoint url}/{bucket name}
```
Then you will be asked for access key and secret key.
#### FTP/FTPS/SFTP
```
bitbackup clone {protocol}://[{user}:{password}]@{host url}:{port}/{directory}
```
#### HTTP/HTTPS
```
bitbackup clone http[s]://[{user}:{password}]@{host url}:{port}/{directory}
```
#### Bit Backup server (via Rest api)
```
bitbackup clone bitbackup:://[{user}:{password}]@{host url}:{port}/[path to repository/]{repository name}
```
### init
Init commands creates new directory .bitbackup with its structure
```
bitbackup init [[--bare]]
```
* Creating a new empty Bit Backup repository
* Creating a Bit Backup repository using an existing directory
### help
### version
### config
### restore
### reset
### tag
### revert
### blame
```
bitbackup blame {file} {remote}
```
### clean
### gc
```
bitbackup gc abc
```
### fsck
### check
### bundle
### remote add {remote name}
```
bitbackup remote add {remote name}
```
```
bitbackup remote add abc protocol://user:pw|{}@host:port/directory[::password=encryption_password|{}::duplicate_count=1::exclude=::include=::]
bitbackup remote add wedos_disk_100gb_backup user:pw@host:port/directory::password=123::duplicate_count=2
bitbackup remote add abc user:pw|{}@host:port/directory::password=encryption_password|{}::duplicate_count={1, 0 is default}::compression_level={0-9,5 is default}
```
{} placeholders means, that user will be asked in console (to avoid the password to be in console history)
### remote remove {remote name}
```
bitbackup remote remove abc
```
### bitbackup commit
```
bitbackup commit [-m "{message}"]
```
### bitbackup mirror {remote name}
```
bitbackup mirror abc def ghi [-m message -t TAG]
bitbackup mirror @all
```
### bitbackup fetch
### bitbackup pull
### bitbackup log
### bitbackup diff
### bitbackup prune
```
bitbackup prune origin --since 2021-10-04
bitbackup prune abc --since "2 months ago" | 10 … does not delete anything, only marks objects to be deleted
```
### verify
```
bitbackup verify abc
```
### repack
## Todo
Table FILE add new columns linux_rights, owner, group

1
build.sh Executable file
View File

@ -0,0 +1 @@
mvn clean install

12
docs/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
#files to ignore
*.metadata/**
*.recommenders/**
*target/**
*build/**
*.idea/**
*.iml
#*.class
/target/
*generated/*

170
docs/LICENSE Normal file
View File

@ -0,0 +1,170 @@
Creative Commons Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors.
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public.
Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. Additional offer from the Licensor Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@ -0,0 +1,26 @@
= Bit Backup - Documentation
////
weight=100
////
////
+++
title = "Development"
date = "2024-05-21"
menu = "main"
+++
////
== How to build
Requirements:
* Java 21
* Maven
----
git clone https://code.nanoboot.org/nanoboot/bit-backup
cd bit-backup
mvn clean install
----

View File

@ -0,0 +1 @@
/rv/data/desktop/code/code.nanoboot.org/nanoboot/bit-backup/docs/content/Introduction/index.adoc

View File

@ -0,0 +1,26 @@
= Bit Backup - Documentation
////
weight=1000
////
////
+++
title = "Installation"
date = "2024-05-21"
menu = "main"
+++
////
== Requirements
* Java 21
== Environment setup on Linux
Add to your .bashrc:
alias bitbackup='java -jar {path to bit-backup jar with dependencies file}/bit-backup-0.0.0-SNAPSHOT-jar-with-dependencies.jar'

View File

@ -0,0 +1,87 @@
= Bit Backup - Documentation
////
weight=200
////
////
+++
title = "Internals"
date = "2024-05-21"
menu = "main"
+++
////
== Structure of "Bit Backup" repository
=== Directory {REPODIR}/objects
SHA-256 hash is used (or an alternative hash, if supported)
objects/{??}/{?????...}
=== Directory {REPODIR}/pack
pack/pack-{sha-512}.pack
{sha-256}::::{length in bytes}::::{sha-256}::::{length in bytes}::::{sha-512}::::{length in bytes}::::{sha-512}::::{length in bytes}::::{sha-512}::::{length in bytes}::::::::{bytes -base}{bytes-incremental}{bytes-incremental}{bytes-incremental}{bytes-incremental}{bytes-incremental}
binary diffs
=== File(s) {REPODIR}/bitbackupindex.{datetime}
==== Content
|===
| Attribute | Example | Description
| PATH | /home/robertvokac |
| FILE_NAME | doc.txt |
| TYPE | - | DIR d, REGULAR -, LINK l
| LINK_TARGET | a/b/text.txt | The target is in the content of binary object
| UID | 2 |
| GID | 2 |
| OWNER | robertvokac |
| GROUP | robertvokac |
| UNIX_PERMISSIONS | rwxrw-r-- |
| ACL | aaa |
| LAST_MOD_TIME | 20220110151617999 |
| LAST_CHANGE_TIME | 20220110151617999 |
| LAST_ACCESS_TIME | 20220110151617999 |
| SIZE | 263 |
| HASH_ALGORITHM | SHA-256 |
| HASH_SUM | {} |
| ATTRS | aaa |
|===
bitbackupinfo
----
Permission Symbolic Representation Octal Representation
read r 4
write w 2
execute x 1
no permission - 0
----
----
Creates local .bitbackupindex
Downloads remote .bitbackupindex if does not exist, empty file will be returned.
Compares these indexes, uploads new blobs to object addressed system (SHA-512) packaged to 7z archives (compression=ultra + other settings)
The most reliable way would be to make md5 hashes of all the local files you care about and store it in a file. So the file will contain a list of filenames and their md5 hashes. Store that file on your ftp server. When you want to update the files on your ftp server, download the file containing the list, compare that against all your local files, and upload the files that have changed (or are new). That way you don't have to worry about archive bits, modified date, or looking at file sizes, the use of which can never be 100% reliable.
Using file sizes isn't reliable for the obvious reason - a file could change but have the same size. I'm not a fan of using the archive bit or modified date because either of those could be confused if you backup or restore your local directory with another backup program.
----
=== File(s) {REPODIR}/bitbackupindexinfo.{datetime}
----
DATE=20231105
TIME=102950
VERSION=1
MESSAGE=
TAG=
----

View File

@ -0,0 +1,95 @@
= Bit Backup - Documentation
////
weight=1000
////
////
+++
title = "General"
date = "2024-05-21"
menu = "main"
+++
////
== Features
* Backing up directory to another location like: local, FTP(S), SFTP, HTTP(S), S3, Bit Backup server and others
* Optionally you can set a password to protect your files (if a not trusted external location like FTP or S3 is used)
* Files are handled in a "Bit Backup repository"
== What is not supported
* Conflict resolution is not supported. (If you wish something not yet supported to be added, please, let's start a discussion here or at forum.nanoboot.org)
* "Bit Backup" is not intended to be used by many read/write users.
* Several people changing one Bit Backup repository must be avoided.
* "Bit Backup" is not intended to be used by many read users and only one read/write user.
* One Bit Backup repository can be used by more users, but only one user can change it.
* Branches are not supported
== File .bitbackupignore
You can create file .bitbackupignore containing the names of the files/directories you wish to ignore (don't backup or analyse)
* .bitbackupignore is similar to Git file .gitignore
* each line should contain exactly one name
* lines starting with # are skipped
* you may use Unix shell-style wildcards
== "Bit Backup" Repository
"Bit Backup" repository is a directory with a defined structure, where "Bit Backup" stores backups of directories.
* Your files are versioned. You can travel in history and return to an older version of the whole repo or only a changed/deleted directory or file.
You can:
* clone a remote Bit Backup repository
* or use an existing local Bit Backup repository
* or create a new empty Bit Backup repository
* or create a new Bit Backup repository using an existing directory
* or save your local repository to a remote repository.
== Directory(ies) to be backed up
These are 1 or more directories, you want to backup
== File bitbackupindex
Created and managed automatically by bit-backup.
This is a text file with a defined structure.
In fact, it is a CSV file, where the columns are separated by the tab character.
Each row represent one file of directory
Each column represents one of file properties
== File bitbackupindex.sha256
Created and managed automatically by bit-backup.
This file contains the calculated sha256 hash of file bitbackupindex
== File bitbackupindexold
Created and managed automatically by bit-backup.
This is the previous file bitbackupindex.
== File bitbackupindexold.sha256
Created and managed automatically by bit-backup.
This file contains the calculated sha256 hash of file bitbackupindexold
== File .bitbackup
File .bitbackup is an optional file. You can save remotes and the credentials here to avoid typing it.
Content:
----
remotes=remote1,remote2,remote3
----

View File

@ -0,0 +1,26 @@
= Bit Backup - Documentation
////
weight=900
////
////
+++
title = "bitbackup analyse"
date = "2024-05-21"
menu = "main"
+++
////
== Description
WARNING: This command does not involve "Bit Backup" repository. Instead it is intended for additional control of integrity of files.
This command is intended for creation list of files and directories in the given root directory together with all their file attributes.
* If the file bitbackupindex exists at the start, then:
** file bitbackupindexold (if exists) is deleted
** file bitbackupindex is renamed to bitbackupindexold
* The output of analyse command (list of files and directories) is stored to file bitbackupindex.
== Examples

View File

@ -0,0 +1,33 @@
= Bit Backup - Documentation
////
weight=900
////
////
+++
title = "bitbackup inspect"
date = "2024-05-21"
menu = "main"
+++
////
== Description
WARNING: This command does not involve "Bit Backup" repository. Instead it is intended for additional control of integrity of files.
This command is intended for Bit Rot Detection (to keep your files forever).
* Current hash sum of files is tracked in file bitbackupindex.
* Previous hash sum of files is tracked in file bitbackupindexold.
* Files bitbackupindex and bitbackupindexold are compared.
* If the current and previous last modification date of a file are the same, but the calculated checksum is different, then a bit rot was detected.
Found bit rots can be probably repaired, but only in case, you used commands like init and create
Inspired by:
* https://github.com/ambv/bitrot
* https://github.com/laktak/chkbit-py
== Examples

View File

@ -0,0 +1,13 @@
= Bit Backup - Documentation
////
weight=1000
////
////
+++
title = "Usage"
date = "2024-05-21"
menu = "main"
+++
////

14
docs/content/index.adoc Normal file
View File

@ -0,0 +1,14 @@
= Bit Backup - Documentation
////
+++
title = "About"
date = "2024-05-21"
menu = "main"
+++
////
"Bit Backup" is a backup tool used to manage files.
Inspired by Borg Backup, but is slightly different.

9
docs/dog.conf Normal file
View File

@ -0,0 +1,9 @@
title = Bit Backup - Documentation
editURL = https://code.nanoboot.org/nanoboot/bit-backup/edit/develop/docs/content/
description = Bit Backup - Documentation
author = Robert Vokac
showVisitedLinks = true
disableBreadcrumb = false
disableNextPrev = false
titleSeparator=|
frontPageName=Introduction

7
docs/templates/footer.html vendored Normal file
View File

@ -0,0 +1,7 @@
<style>
.footer2 a {color:#5dade2;}
</style>
<div class="footer2">
Copyright © 2016-2023 The Nanoboot Authors. Made with <a href="https://code.nanoboot.org/nanoboot/dog">Dog</a>.
<div>

31
docs/templates/header.html vendored Normal file
View File

@ -0,0 +1,31 @@
<style>
#nanoboot_banner {
font-size:2em;
font-weight: 500;
padding-top: 6px !important;
padding-bottom: 9px !important;
text-align:left;
padding-left:60px;
background: #7cd3ff;
background: linear-gradient(180deg, rgba(124, 211, 255,0.4) 10%, white 60%);
}
#nanoboot_banner a {
text-decoration:none;
text-transform: uppercase;
color:#4169E1 !important;
font-weight: 600;
display:inline-block;
}
</style>
<div id="nanoboot_banner"><a href="https://docs.nanoboot.org" style="text-transform:none;"><span style="color:blue;">Documentation</span></a> | <a href="https://www.nanoboot.org" target="_parent">Nanoboot</a> Project</div>

15
links.txt Normal file
View File

@ -0,0 +1,15 @@
https://github.com/puniverse/javafs
https://davidvlijmincx.com/posts/writing_a_simple_filesystem_using_fuse_and_java_17/
https://stackoverflow.com/questions/30532167/support-write-operation-in-fuse-filesystem-using-fuse-j
https://winfsp.dev/
bitbackup - maybe use sha-256 instead of sha-512
https://www.sanfoundry.com/java-program-implement-rolling-hash/
https://github.com/lemire/rollinghashjava

250
pom.xml Normal file
View File

@ -0,0 +1,250 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
bit-backup: Tool detecting bit rots in files.
Copyright (C) 2016-2022 the original author or authors.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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>
<parent>
<groupId>com.robertvokac.essential</groupId>
<artifactId>robertvokac-parent</artifactId>
<version>0.1.1-SNAPSHOT</version>
</parent>
<groupId>com.robertvokac.tools</groupId>
<artifactId>bit-backup</artifactId>
<version>0.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Bit Backup</name>
<description>Tool detecting bit rots in files.</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<checkstyle.skip>true</checkstyle.skip><!-- TODO: make false-->
<power.version>2.0.1-SNAPSHOT</power.version>
<db-migration-core.version>0.1.1-SNAPSHOT</db-migration-core.version>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<!--<compilerArgs>
-|-enable-preview
</compilerArgs>-->
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
<source>${javase.version}</source>
<target>${javase.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<archive>
<manifest>
<mainClass>com.robertvokac.bitbackup.core.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<skip>${checkstyle.skip}</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${build-helper-maven-plugin.version}</version>
<executions>
<execution>
<id>add-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>add-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/resources/db_migrations/sqlite/bitbackup</directory>
<targetPath>db_migrations/sqlite/bitbackup</targetPath>
<includes>
<include>*.sql</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Power dependencies -->
<dependency>
<groupId>com.robertvokac.powerframework</groupId>
<artifactId>power-time</artifactId>
<version>${power.version}</version>
</dependency>
<dependency>
<groupId>com.robertvokac.powerframework</groupId>
<artifactId>power-random</artifactId>
<version>${power.version}</version>
</dependency>
<dependency>
<groupId>com.robertvokac.powerframework</groupId>
<artifactId>power-collections</artifactId>
<version>${power.version}</version>
</dependency>
<!-- Other dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.robertvokac.tools.dbmigration</groupId>
<artifactId>db-migration-core</artifactId>
<version>${db-migration-core.version}</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite-jdbc.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>dev.mccue</groupId>
<artifactId>guava-io</artifactId>
<version>0.0.3</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>robertvokac-releases-repository</id>
<name>robertvokac-releases-repository</name>
<url>https://maven.robertvokac.com/releases</url>
</repository>
<repository>
<id>robertvokac-snapshots-repository</id>
<name>robertvokac-snapshots-repository</name>
<url>https://maven.robertvokac.com/snapshots</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>robertvokac-releases-repository</id>
<name>robertvokac-releases-repository</name>
<url>https://maven.robertvokac.com/releases</url>
</pluginRepository>
<pluginRepository>
<id>robertvokac-snapshots-repository</id>
<name>robertvokac-snapshots-repository</name>
<url>https://maven.robertvokac.com/snapshots</url>
</pluginRepository>
</pluginRepositories>
</project>

3
setmodtime.sh Executable file
View File

@ -0,0 +1,3 @@
set_last_mod_time_the_same_as_this_file="$1"
set_last_mod_time_for_this_file="$2"
touch -r "$set_last_mod_time_the_same_as_this_file" "$set_last_mod_time_for_this_file"

View File

@ -0,0 +1,127 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.commands;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import com.robertvokac.bitbackup.core.Utils;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class BitBackupIgnoreRegex implements Predicate<String> {
private final List<String> patterns = new ArrayList<>();
public BitBackupIgnoreRegex(File bitBackupIgnoreFile) {
patterns.add(convertUnixRegexToJavaRegex("*.birreport.csv"));
patterns.add(convertUnixRegexToJavaRegex("*.bibreport.csv"));
patterns.add(convertUnixRegexToJavaRegex("*.bitbackupreport.csv"));
this.addBitBackupIgnoreFile(bitBackupIgnoreFile);
}
public final void addBitBackupIgnoreFile(File bitBackupIgnoreFile) {
addBitBackupIgnoreFile(bitBackupIgnoreFile, null);
}
public final void addBitBackupIgnoreFile(File bitBackupIgnoreFile, File workingDir) {
String[] lines = bitBackupIgnoreFile.exists() ? Utils.readTextFromFile(bitBackupIgnoreFile).split("\\R") : new String[]{};
String addPrefix = workingDir == null ? "" : bitBackupIgnoreFile.getParentFile().getAbsolutePath().replace(workingDir.getAbsolutePath() + "/", "");
for (String l : lines) {
if (l.isBlank() || l.trim().startsWith("#")) {
//nothing to do
continue;
}
if(addPrefix == null) {
patterns.add(convertUnixRegexToJavaRegex(l));
} else {
patterns.add(convertUnixRegexToJavaRegex(addPrefix + l));
patterns.forEach(e->System.out.println("$$$" + e));
}
}
}
@Override
public boolean test(String text) {
if (patterns.isEmpty()) {
//nothing to do
return false;
}
boolean ignore = false;
for (String p : patterns) {
boolean b = Pattern.matches(p, text);
if (b) {
ignore = true;
} else {
}
}
// if (ignore) {
// System.out.println("ignoring file: " + text);
// } else {
// System.out.println("accepting file: " + text);
// }
return ignore;
}
public static String convertUnixRegexToJavaRegex(String wildcard) {
StringBuffer s = new StringBuffer(wildcard.length());
s.append('^');
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch (c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
// escape special regexp-characters
case '(':
case ')':
case '[':
case ']':
case '$':
case '^':
case '.':
case '{':
case '}':
case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append('$');
return (s.toString());
}
}

View File

@ -0,0 +1,489 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.commands;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.robertvokac.bitbackup.core.BitBackupContext;
import com.robertvokac.bitbackup.core.Command;
import com.robertvokac.bitbackup.core.BitBackupArgs;
import com.robertvokac.bitbackup.core.BitBackupException;
import com.robertvokac.bitbackup.core.BitBackupFiles;
import com.robertvokac.bitbackup.core.ListSet;
import com.robertvokac.bitbackup.core.Utils;
import com.robertvokac.bitbackup.entity.FsFile;
import com.robertvokac.bitbackup.entity.SystemItem;
import com.robertvokac.bitbackup.files.FileEntry;
import com.robertvokac.bitbackup.persistence.api.FileRepository;
import com.robertvokac.bitbackup.persistence.impl.sqlite.SqliteDatabaseMigration;
import com.robertvokac.dbmigration.core.main.MigrationResult;
import com.robertvokac.powerframework.time.duration.Duration;
import com.robertvokac.powerframework.time.moment.LocalDateTime;
import com.robertvokac.powerframework.time.utils.ProgressTracker;
import com.robertvokac.powerframework.time.utils.TimeUnit;
/**
*
* @author r
*/
public class CheckCommand implements Command {
private static final Logger LOG = LogManager.getLogger(CheckCommand.class);
public static final String NAME = "check";
public CheckCommand() {
}
@Override
public String getName() {
return NAME;
}
enum CheckCommandPart {
CHECK_OLD_DB_CHECKSUM(1),
MIGRATE_DB_SCHEMA_IF_NEEDED(2),
UPDATE_VERSION(3),
FOUND_FILES_IN_FILESYSTEM(4),
FOUND_FILES_IN_DB(5),
ADD_NEW_FILES_TO_DB(6),
REMOVE_DELETED_FILES_FROM_DB(7),
COMPARE_CONTENT_AND_LAST_MODTIME(8),
CREATE_REPORT_CSV_IF_NEEDED(9),
CHECK_NEW_DB_CHECKSUM(10);
private int number;
CheckCommandPart(int number) {
this.number = number;
}
public String toText() {
return "Part " + number + ": ";
}
}
static int iStatic = 0;
@Override
public String run(BitBackupArgs bitBackupArgs) {
BitBackupFiles bitBackupFiles = new BitBackupFiles(bitBackupArgs);
BitBackupContext bitBackupContext = new BitBackupContext(bitBackupFiles.getWorkingDirAbsolutePath());
//
//part 1:
part1CheckDbHasExpectedHashSum(bitBackupFiles);
//part 2:
boolean part2Result = part2MigrateDbSchemaIfNeeded(bitBackupFiles);
if (!part2Result) {
return "part 2 failed";
}
//part 3:
part3UpdateVersionInDbIfNeeded(bitBackupContext, bitBackupFiles);
ListSet<File> filesInFileSystem;
try {
filesInFileSystem = part4FoundFilesInFileSystem(bitBackupFiles, bitBackupArgs);
} catch (IOException ex) {
return "Part 4 failed: " + ex.getMessage();
}
ListSet<FsFile> filesInDb = part5FoundFilesInDb(bitBackupContext.getFileRepository(), bitBackupArgs);
LocalDateTime now = part6AddNewFilesToDb(filesInFileSystem, bitBackupFiles, filesInDb, bitBackupContext);
List<FsFile> filesToBeRemovedFromDb = part7RemoveDeletedFilesFromDb(filesInDb, filesInFileSystem, bitBackupContext);
List<FsFile> filesWithBitRot = part8CompareContentAndLastModificationDate(filesInDb, filesToBeRemovedFromDb, bitBackupContext, now);
part9CreateReportCsvIfNeeded(bitBackupArgs, bitBackupFiles, filesWithBitRot);
part10CalculateCurrentHashSumOfDbFile(bitBackupFiles);
LOG.info("==========");
LOG.info("Summary");
if (filesWithBitRot.isEmpty()) {
LOG.info("Summary: OK : No files with bit rot were found.");
} else {
LOG.error("Summary: KO : Some files {} with bit rot were found.", filesWithBitRot.size());
filesWithBitRot.stream().forEach(f
-> LOG.error("Bit rot detected: \"" + f.getAbsolutePath() + "\"" + " expected_sha512=" + f.getHashSumValue() + " returned_sha512=" + Utils.calculateSHA512Hash(new File("./" + f.getAbsolutePath())))
);
}
System.out.println("foundFiles=" + foundFiles);
System.out.println("foundDirs=" + foundDirs);
return filesWithBitRot.isEmpty() ? "" : filesWithBitRot.stream().map(FsFile::getAbsolutePath).collect(Collectors.joining("\n"));
}
/**
* Checks, if SQLite DB file has the expected SHA-512 hash sum
*
* @param bitBackupSQLite3File
* @param bitBackupSQLite3FileSha512
* @throws BitBackupException - if this check fails.
*/
private void part1CheckDbHasExpectedHashSum(BitBackupFiles bitBackupFiles) throws BitBackupException {
LOG.info("** Part {}: Checking DB, if has expected check sum.", CheckCommandPart.CHECK_OLD_DB_CHECKSUM.number);
final File bitBackupSQLite3FileSha512 = bitBackupFiles.getBitBackupSQLite3FileSha512();
final boolean dbExists = bitBackupFiles.getBitBackupSQLite3File().exists();
final boolean checkSumExists = bitBackupFiles.getBitBackupSQLite3FileSha512().exists();
if (dbExists && checkSumExists) {
String expectedHash = Utils.readTextFromFile(bitBackupSQLite3FileSha512);
String returnedHash = Utils.calculateSHA512Hash(bitBackupFiles.getBitBackupSQLite3File());
if (!returnedHash.equals(expectedHash)) {
String msg
= "Part {}: KO. "
+ "Unexpected hash "
+ returnedHash
+ ". Expected SHA-512 hash sum was: "
+ expectedHash
+ " for file "
+ bitBackupFiles.getBitBackupSQLite3File().getAbsolutePath();
LOG.error(msg, CheckCommandPart.CHECK_OLD_DB_CHECKSUM.number);
LOG.info("Exiting because of the previous error.");
throw new BitBackupException(msg);
}
} else {
LOG.info("Part {}: OK. Nothing to do: {}",
CheckCommandPart.CHECK_OLD_DB_CHECKSUM.number,
!dbExists ? "DB does not yet exist." : "Check sum file does not exist.");
}
}
private boolean part2MigrateDbSchemaIfNeeded(BitBackupFiles bitBackupFiles) {
LOG.info("** Part {}: Migrating schema, if needed.", CheckCommandPart.MIGRATE_DB_SCHEMA_IF_NEEDED.number);
try {
MigrationResult migrationResult = SqliteDatabaseMigration.getInstance().migrate(bitBackupFiles.getWorkingDirAbsolutePath());
if (migrationResult == MigrationResult.SUCCESS) {
LOG.info("Part {}: OK. Success.", CheckCommandPart.MIGRATE_DB_SCHEMA_IF_NEEDED.number);
return true;
} else {
LOG.error("Part {}: KO. Failed.", CheckCommandPart.MIGRATE_DB_SCHEMA_IF_NEEDED.number);
throw new RuntimeException("Part " + CheckCommandPart.MIGRATE_DB_SCHEMA_IF_NEEDED.number + ": KO. Failed.");
}
} catch (RuntimeException e) {
LOG.error("Part {}: KO. {}", CheckCommandPart.MIGRATE_DB_SCHEMA_IF_NEEDED.number, e.getMessage());
return false;
}
}
private void part3UpdateVersionInDbIfNeeded(BitBackupContext bitBackupContext, BitBackupFiles bitBackupFiles) {
LOG.info("** Part {}: Updating version, if needed.", CheckCommandPart.UPDATE_VERSION.number);
String bitBackupVersion = bitBackupContext.getSystemItemRepository().read(BIBVERSION).getValue();
System.out.println("Before: bib.version=" + bitBackupVersion);
if (bitBackupVersion == null) {
bitBackupContext.getSystemItemRepository().create(new SystemItem("bib.version", "0.0.0-SNAPSHOT"));
}
System.out.println("Updating version in DB.");
bitBackupVersion = bitBackupContext.getSystemItemRepository().read("bib.version").getValue();
System.out.println("After: bib.version=" + bitBackupVersion);
LOG.info("Part {}: OK.", CheckCommandPart.UPDATE_VERSION.number);
}
public static final String BIBVERSION = "bib.version";
private ListSet<File> part4FoundFilesInFileSystem(BitBackupFiles bitBackupFiles, BitBackupArgs bitBackupArgs) throws IOException {
LOG.info("** Part {}: Loading files in filesystem", CheckCommandPart.FOUND_FILES_IN_FILESYSTEM.number);
String workingDir = bitBackupFiles.getWorkingDirAbsolutePath();
List<File> filesAlreadyFound = new ArrayList<>();
List<File> filesInDirList = foundFilesInCurrentDir(bitBackupFiles.getWorkingDir(), filesAlreadyFound, bitBackupFiles, bitBackupArgs, workingDir);
if(bitBackupArgs.isBitBackupIndexEnabled()) {
Utils.writeTextToFile(bitbackupindexSB.toString(), bitBackupFiles.getBitbackupindex());
}
ListSet<File> listSet = new ListSet<>(filesInDirList, f -> loadPathButOnlyTheNeededPart(bitBackupFiles.getWorkingDir(), f));
LOG.info("Part {}: Found {} files.", CheckCommandPart.FOUND_FILES_IN_FILESYSTEM.number, listSet.size());
return listSet;
}
private String loadPathButOnlyTheNeededPart(File currentDir, File file) {
return file.getAbsolutePath().substring(currentDir.getAbsolutePath().length() + 1);
}
private final StringBuilder bitbackupindexSB = new StringBuilder();
static int iii = 0;
private int foundFiles;
private int foundDirs;
private List<File> foundFilesInCurrentDir(File currentDir, List<File> filesAlreadyFound, BitBackupFiles bitBackupFiles, BitBackupArgs bitBackupArgs, String workingDir) throws IOException {
for (File f : currentDir.listFiles()) {
boolean isBitBackupIgnore = f.getName().equals(bitBackupFiles.getBitBackupIgnore().getName());
if (isBitBackupIgnore && !f.getAbsolutePath().equals(bitBackupFiles.getBitBackupIgnore().getAbsolutePath())) {
bitBackupFiles.getBitBackupIgnoreRegex().addBitBackupIgnoreFile(f, bitBackupFiles.getWorkingDir());
}
if (f.isDirectory()) {
++foundDirs;
if (bitBackupArgs.isBitBackupIndexEnabled()) {
bitbackupindexSB.append(new FileEntry(f).toCsvLine()).append("\n");
}
foundFilesInCurrentDir(f, filesAlreadyFound, bitBackupFiles, bitBackupArgs, workingDir);
} else {
++foundFiles;
if (f.getAbsolutePath().equals(bitBackupFiles.getBitBackupSQLite3File().getAbsolutePath())) {
continue;
}
if (f.getAbsolutePath().equals(bitBackupFiles.getBitBackupSQLite3FileSha512().getAbsolutePath())) {
continue;
}
++iii;
//System.out.println("Testing file: " + iii + "#" + " " + loadPathButOnlyTheNeededPart(currentDirRoot, f));
if (bitBackupFiles.getBitBackupIgnoreRegex().test(loadPathButOnlyTheNeededPart(bitBackupFiles.getWorkingDir(), f))) {
continue;
}
if (bitBackupArgs.isBitBackupIndexEnabled()) {
bitbackupindexSB.append(new FileEntry(f).toCsvLine()).append("\n");
}
filesAlreadyFound.add(f);
if (bitBackupArgs.isVerboseLoggingEnabled() || iStatic % 100 == 0) {
LOG.info("Found file in file system: #" + (++iStatic) + " " + f.getAbsolutePath().substring(workingDir.length() + 1));
}
}
}
return filesAlreadyFound;
}
private ListSet<FsFile> part5FoundFilesInDb(FileRepository fileRepository, BitBackupArgs bitBackupArgs) {
LOG.info("** Part {}: Loading files in DB", CheckCommandPart.FOUND_FILES_IN_DB.number);
List<FsFile> filesInDb = fileRepository.list();
ListSet<FsFile> listSet = new ListSet<>(filesInDb, f -> f.getAbsolutePath());
LOG.info("Part {}: Found {} files.", CheckCommandPart.FOUND_FILES_IN_DB.number, listSet.size());
iStatic = 0;
if (bitBackupArgs.isVerboseLoggingEnabled()) {
filesInDb.stream().forEach((f -> System.out.println("#" + (++iStatic) + " " + f.toString())));
}
return listSet;
}
private LocalDateTime part6AddNewFilesToDb(ListSet<File> filesInFileSystem, BitBackupFiles bitBackupFiles, ListSet<FsFile> filesInDb, BitBackupContext bitBackupContext) {
LOG.info("** Part {}: Adding new files to DB", CheckCommandPart.ADD_NEW_FILES_TO_DB.number);
Date lastChecked = new Date();
com.robertvokac.powerframework.time.moment.LocalDateTime now = com.robertvokac.powerframework.time.moment.LocalDateTime.convertJavaUtilDateToPowerLocalDateTime(lastChecked);
int processedCount0 = 0;
List<FsFile> filesMissingInDb = new ArrayList<>();
for (File fileInDir : filesInFileSystem.getList()) {
processedCount0 = processedCount0 + 1;
if (processedCount0 % 100 == 0) {
double progress = ((double) processedCount0) / filesInFileSystem.getList().size() * 100;
LOG.info("Part {}: Add - Progress: {}/{} {} %",
CheckCommandPart.ADD_NEW_FILES_TO_DB.number,
processedCount0,
filesInFileSystem.getList().size(),
String.format("%,.2f", progress));
}
String absolutePathOfFileInDir = loadPathButOnlyTheNeededPart(bitBackupFiles.getWorkingDir(), fileInDir);
if (!filesInDb.doesSetContains(absolutePathOfFileInDir)) {
Date lastModified = new Date(fileInDir.lastModified());
com.robertvokac.powerframework.time.moment.LocalDateTime ldt = com.robertvokac.powerframework.time.moment.LocalDateTime.convertJavaUtilDateToPowerLocalDateTime(lastModified);
FsFile fsFile = new FsFile(
UUID.randomUUID().toString(),
fileInDir.getName(),
absolutePathOfFileInDir,
ldt.toString(),
now.toString(),
Utils.calculateSHA512Hash(fileInDir),
"SHA-512",
fileInDir.length(),
"OK"
);
filesMissingInDb.add(fsFile);
}
}
LOG.info("Adding new files: {}", filesMissingInDb.size());
bitBackupContext.getFileRepository().create(filesMissingInDb);
return now;
}
private List<FsFile> part7RemoveDeletedFilesFromDb(ListSet<FsFile> filesInDb, ListSet<File> filesInFileSystem, BitBackupContext bitBackupContext) {
LOG.info("** Part {}: Removing deleted files from DB", CheckCommandPart.REMOVE_DELETED_FILES_FROM_DB.number);
List<FsFile> filesToBeRemovedFromDb = new ArrayList<>();
int processedCount = 0;
for (FsFile fileInDb : filesInDb.getList()) {
processedCount = processedCount + 1;
if (processedCount % 100 == 0) {
double progress = ((double) processedCount) / filesInDb.getList().size() * 100;
LOG.info(
"Part {}: Remove - Progress: {}/{} {}%",
CheckCommandPart.REMOVE_DELETED_FILES_FROM_DB.number,
processedCount,
filesInDb.getList().size(),
String.format("%,.2f", progress)
);
}
String absolutePathOfFileInDb = fileInDb.getAbsolutePath();
if (!filesInFileSystem.doesSetContains(absolutePathOfFileInDb)) {
filesToBeRemovedFromDb.add(fileInDb);
}
}
LOG.info("Part {}: Removing files: {}",
CheckCommandPart.REMOVE_DELETED_FILES_FROM_DB.number,
filesToBeRemovedFromDb.size());
for (FsFile f : filesToBeRemovedFromDb) {
bitBackupContext.getFileRepository().remove(f);
}
return filesToBeRemovedFromDb;
}
private List<FsFile> part8CompareContentAndLastModificationDate(
ListSet<FsFile> filesInDb, List<FsFile> filesToBeRemovedFromDb, BitBackupContext bitBackupContext, LocalDateTime now) {
LOG.info("** Part {}: Comparing Content and last modification date", CheckCommandPart.COMPARE_CONTENT_AND_LAST_MODTIME.number);
double countOfFilesToCalculateHashSum = filesInDb.size() - filesToBeRemovedFromDb.size();
int processedCount = 0;
//// Update modified files with same last modification date
List<FsFile> filesWithBitRot = new ArrayList<>();
List<FsFile> filesToUpdateLastCheckDate = new ArrayList<>();
int contentAndModTimeWereChanged = 0;
ProgressTracker progressTracker = new ProgressTracker(filesInDb.size() - filesToBeRemovedFromDb.size());
for (FsFile fileInDb : filesInDb) {
String absolutePathOfFileInDb = fileInDb.getAbsolutePath();
if (filesToBeRemovedFromDb.contains(fileInDb)) {
//nothing to do
continue;
}
progressTracker.nextDone();
processedCount = processedCount + 1;
if (processedCount % 100 == 0) {
double progress = ((double) processedCount) / countOfFilesToCalculateHashSum * 100;
LOG.info("Update - Progress: " + processedCount + "/" + countOfFilesToCalculateHashSum + " " + String.format("%,.2f", progress) + "%");
LOG.info("Remains: " + Duration.of(progressTracker.getRemainingSecondsUntilEnd(), TimeUnit.SECOND).toHumanString());
}
File file = new File("./" + absolutePathOfFileInDb);
Date lastModified = new Date(file.lastModified());
com.robertvokac.powerframework.time.moment.LocalDateTime ldt = com.robertvokac.powerframework.time.moment.LocalDateTime.convertJavaUtilDateToPowerLocalDateTime(lastModified);
String calculatedHash = Utils.calculateSHA512Hash(file);
if (ldt.toString().equals(fileInDb.getLastModificationDate()) && !calculatedHash.equals(fileInDb.getHashSumValue())) {
filesWithBitRot.add(fileInDb);
fileInDb.setLastCheckDate(now.toString());
fileInDb.setLastCheckResult("KO");
bitBackupContext.getFileRepository().updateFile(fileInDb);
continue;
}
if (!ldt.toString().equals(fileInDb.getLastModificationDate())) {
fileInDb.setLastCheckDate(now.toString());
fileInDb.setLastModificationDate(ldt.toString());
fileInDb.setHashSumValue(calculatedHash);
fileInDb.setHashSumAlgorithm("SHA-512");
fileInDb.setSize(file.length());
fileInDb.setLastCheckResult("OK");
bitBackupContext.getFileRepository().updateFile(fileInDb);
//System.out.println(fileInDb.toString());
contentAndModTimeWereChanged++;
continue;
}
if (ldt.toString().equals(fileInDb.getLastModificationDate())) {
fileInDb.setLastCheckResult("OK");
if (fileInDb.getSize() == 0) {
fileInDb.setSize(file.length());
bitBackupContext.getFileRepository().updateFile(fileInDb);
} else {
filesToUpdateLastCheckDate.add(fileInDb);
}
continue;
}
}
LOG.info("Part {}: Updating files - " + (filesWithBitRot.isEmpty() ? "no" : "some") + " files with bit rots - content was changed and last modification is the same: {}",
CheckCommandPart.COMPARE_CONTENT_AND_LAST_MODTIME.number,
filesWithBitRot.size());
LOG.info("Part {}: Updating files - content and last modification date were changed: {}",
CheckCommandPart.COMPARE_CONTENT_AND_LAST_MODTIME.number,
contentAndModTimeWereChanged);
LOG.info("Part {}: Updating files - content and last modification date were not changed: {}",
CheckCommandPart.COMPARE_CONTENT_AND_LAST_MODTIME.number,
filesToUpdateLastCheckDate.size());
bitBackupContext.getFileRepository().updateLastCheckDate(now.toString(), filesToUpdateLastCheckDate);
return filesWithBitRot;
}
private void part9CreateReportCsvIfNeeded(BitBackupArgs bitBackupArgs, BitBackupFiles bitBackupFiles, List<FsFile> filesWithBitRot) {
LOG.info("** Part {}: Creating csv report, if needed", CheckCommandPart.CREATE_REPORT_CSV_IF_NEEDED.number);
if (!bitBackupArgs.hasArgument("report")) {
LOG.info(" Part {}: OK. Nothing to do. No option report was passed.", CheckCommandPart.CREATE_REPORT_CSV_IF_NEEDED.number);
return;
}
if (!bitBackupArgs.getArgument("report").equals("true")) {
LOG.info("Part {}: Nothing to do. Option report={}",
CheckCommandPart.CREATE_REPORT_CSV_IF_NEEDED.number,
bitBackupArgs.getArgument("report"));
return;
}
File bibReportCsv = bitBackupFiles.getBitBackupReportCsv();
if (bibReportCsv.exists()) {
Long nowLong = com.robertvokac.powerframework.time.moment.UniversalDateTime.now().toLong();
File backup = new File(bibReportCsv.getParentFile().getAbsolutePath() + "/" + nowLong + "." + bibReportCsv.getName());
bibReportCsv.renameTo(backup);
}
StringBuilder sb = new StringBuilder();
if (!filesWithBitRot.isEmpty()) {
sb.append("file;expected;calculated\n");
}
filesWithBitRot.stream().forEach(f
-> sb.append(f.getAbsolutePath())
.append(";")
.append(f.getHashSumValue())
.append(";")
.append(Utils.calculateSHA512Hash(new File("./" + f.getAbsolutePath())))
.append("\n")
);
Utils.writeTextToFile(sb.toString(), bibReportCsv);
LOG.info("Part {}: OK.",
CheckCommandPart.CREATE_REPORT_CSV_IF_NEEDED.number);
}
private void part10CalculateCurrentHashSumOfDbFile(BitBackupFiles bitBackupFiles) {
LOG.info("** Part {}: Calculating current hash sum of DB file", CheckCommandPart.CHECK_NEW_DB_CHECKSUM.number);
Utils.writeTextToFile(Utils.calculateSHA512Hash(bitBackupFiles.getBitBackupSQLite3File()), bitBackupFiles.getBitBackupSQLite3FileSha512());
}
}

View File

@ -0,0 +1,68 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.commands;
import com.robertvokac.bitbackup.core.Command;
import com.robertvokac.bitbackup.core.BitBackupArgs;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class HelpCommand implements Command {
public static final String NAME = "help";
public HelpCommand() {
}
@Override
public String getName() {
return NAME;
}
@Override
public String run(BitBackupArgs bitBackupArgs) {
String str = """
NAME
bitbackup - " Bit Backup"
SYNOPSIS
bitbackup [command] [options]
If no command is provided, then the default command check is used. This means, if you run "bitbackup", it is the same, as to run "bitbackup check".
DESCRIPTION
Detects bit rotten files in the given directory to keep your files forever.
COMMAND
check Generates the static website
OPTIONS
dir={working directory to be checked for bit rot}
Optional. Default=. (current working directory)
report=true or false
Optional. Default= false (nothing will be reported to file .bitbackupreport.csv).
help Display help information
version Display version information
""";
System.out.println(str);
return str;
}
}

View File

@ -0,0 +1,51 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.commands;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.robertvokac.bitbackup.core.Command;
import com.robertvokac.bitbackup.core.BitBackupArgs;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class VersionCommand implements Command {
public static final String NAME = "version";
private static final Logger LOG = LogManager.getLogger(VersionCommand.class);
public VersionCommand() {
}
@Override
public String getName() {
return NAME;
}
@Override
public String run(BitBackupArgs bitBackupArgs) {
String result = "Bit Backup 0.0.0-SNAPSHOT";
LOG.info(result);
return result;
}
}

View File

@ -0,0 +1,70 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import java.util.HashSet;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.robertvokac.bitbackup.commands.CheckCommand;
import com.robertvokac.bitbackup.commands.HelpCommand;
import com.robertvokac.bitbackup.commands.VersionCommand;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class BitBackup {
private static final Logger LOG = LogManager.getLogger(BitBackup.class);
private final Set<Command> commandImplementations;
public BitBackup() {
commandImplementations = new HashSet<>();
commandImplementations.add(new CheckCommand());
commandImplementations.add(new HelpCommand());
commandImplementations.add(new VersionCommand());
}
public void run(String[] args) {
run(new BitBackupArgs(args));
}
public void run(BitBackupArgs bitBackupArgs) {
String command = bitBackupArgs.getCommand();
Command foundCommand = null;
for(Command e:commandImplementations) {
if(e.getName().equals(command)) {
foundCommand = e;
break;
}
}
if(foundCommand == null) {
String msg = "Command \"" + command + "\" is not supported.";
LOG.error(msg);
new HelpCommand().run(bitBackupArgs);
throw new BitBackupException(msg);
}
foundCommand.run(bitBackupArgs);
}
}

View File

@ -0,0 +1,95 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class BitBackupArgs {
@Getter
private final String command;
private final Map<String, String> internalMap = new HashMap<>();
private static String[] convertToStringArray(String command, Map<String, String> map) {
String[] array = new String[1 + map.size()];
array[0] = command;
int i = 0;
for (String key : map.keySet()) {
array[++i] = key + "=" + map.get(key);
}
return array;
}
public BitBackupArgs(BitBackupCommand command, Map<String, String> map) {
this(convertToStringArray(command.name().toLowerCase(), map));
}
public BitBackupArgs(String command, Map<String, String> map) {
this(convertToStringArray(command, map));
}
public BitBackupArgs(String[] args) {
command = args.length == 0 ? "check" : args[0];
if (args.length > 1) {
for (String arg : args) {
if (arg == null) {
continue;
}
if (args[0].equals(arg)) {
continue;
}
String[] keyValue = arg.split("=", 2);
internalMap.put(keyValue[0], keyValue.length > 1 ? keyValue[1] : null);
}
for (String key : internalMap.keySet()) {
System.out.println("Found argument: " + key + "(=)" + internalMap.get(key));
}
}
}
public boolean hasArgument(String arg) {
return internalMap.containsKey(arg);
}
public void addArgument(String arg, String value) {
this.internalMap.put(arg, value);
}
public String getArgument(String arg) {
return internalMap.get(arg);
}
public boolean isVerboseLoggingEnabled() {
return hasArgument("verbose")&&getArgument("verbose").equals("true");
}
public boolean isBitBackupIndexEnabled() {
return hasArgument("bitbackupindex")&&getArgument("bitbackupindex").equals("true");
}
}

View File

@ -0,0 +1,29 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public enum BitBackupCommand {
CHECK, HELP, VERSION;
}

View File

@ -0,0 +1,50 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import lombok.Getter;
import com.robertvokac.bitbackup.persistence.api.ConnectionFactory;
import com.robertvokac.bitbackup.persistence.api.FileRepository;
import com.robertvokac.bitbackup.persistence.api.SystemItemRepository;
import com.robertvokac.bitbackup.persistence.impl.sqlite.FileRepositoryImplSqlite;
import com.robertvokac.bitbackup.persistence.impl.sqlite.SqliteConnectionFactory;
import com.robertvokac.bitbackup.persistence.impl.sqlite.SystemItemRepositoryImplSqlite;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class BitBackupContext {
private final String directoryWhereSqliteFileIs;
private ConnectionFactory connectionFactory;
@Getter
private final SystemItemRepository systemItemRepository;
@Getter
private final FileRepository fileRepository;
public BitBackupContext(String directoryWhereSqliteFileIs) {
this.directoryWhereSqliteFileIs = directoryWhereSqliteFileIs;
this.connectionFactory = new SqliteConnectionFactory(directoryWhereSqliteFileIs);
systemItemRepository = new SystemItemRepositoryImplSqlite((SqliteConnectionFactory) connectionFactory);
fileRepository = new FileRepositoryImplSqlite((SqliteConnectionFactory) connectionFactory);
}
}

View File

@ -0,0 +1,41 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
/**
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
* @since 0.0.0
*/
public class BitBackupException extends RuntimeException {
public BitBackupException(String msg) {
super(msg);
}
public BitBackupException(String msg, Exception e) {
super(msg, e);
}
public BitBackupException(Exception e) {
super(e);
}
}

View File

@ -0,0 +1,54 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import java.io.File;
import lombok.Data;
import lombok.Getter;
import com.robertvokac.bitbackup.commands.BitBackupIgnoreRegex;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
@Data
@Getter
public class BitBackupFiles {
private final File workingDir;
private final String workingDirAbsolutePath;
private final File bitBackupSQLite3File;
private final File bitBackupSQLite3FileSha512;
private final File bitBackupIgnore;
private final BitBackupIgnoreRegex bitBackupIgnoreRegex;
private final File bitBackupReportCsv;
private final File bitbackupindex;
public BitBackupFiles(BitBackupArgs bitInspectorArgs) {
workingDir = new File(bitInspectorArgs.hasArgument("dir") ? bitInspectorArgs.getArgument("dir") : ".");
workingDirAbsolutePath = workingDir.getAbsolutePath();
bitBackupSQLite3File = new File(workingDirAbsolutePath + "/.bitbackup.sqlite3");
bitBackupSQLite3FileSha512 = new File(workingDirAbsolutePath + "/.bitbackup.sqlite3.sha512");
bitBackupIgnore = new File(workingDirAbsolutePath + "/.bitbackupignore");
bitBackupIgnoreRegex = new BitBackupIgnoreRegex(bitBackupIgnore);
bitBackupReportCsv = new File(workingDirAbsolutePath + "/.bitbackupreport.csv");
bitbackupindex = new File(workingDirAbsolutePath + "/.bitbackupindex.csv");
}
}

View File

@ -0,0 +1,33 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public interface Command {
public String getName();
default String run(BitBackupArgs bitInspectorArgs) {
throw new BitBackupException("Not yet implemented.");
}
}

View File

@ -0,0 +1,33 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import java.text.SimpleDateFormat;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class Constants {
public static final SimpleDateFormat YYYYMMDDHHMMSSZ_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
}

View File

@ -0,0 +1,58 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.Getter;
/**
*
* @author robertvokac
*/
public class ListSet<T> implements Iterable<T> {
@Getter
private final List<T> list;
@Getter
private final Set<String> set;
public ListSet(List<T> list, Function<? super T, String> mapper) {
this.list = Collections.unmodifiableList(list);
this.set = Collections.unmodifiableSet(list.stream().map(mapper).collect(Collectors.toSet()));
}
public boolean doesSetContains(String s) {
return set.contains(s);
}
public int size() {
return list.size();
}
@Override
public Iterator<T> iterator() {
return list.iterator();
}
}

View File

@ -0,0 +1,36 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
/**
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
* @since 0.0.0
*/
public class Main {
public static void main(String[] args) {
System.out.println("Bir - Detects bit rotten files in the given directory to keep your files forever.\n");
BitBackup bitBackup = new BitBackup();
bitBackup.run(args);
}
}

View File

@ -0,0 +1,179 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.core;
import dev.mccue.guava.hash.Hashing;
import dev.mccue.guava.io.Files;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class Utils {
private static final String UNDERSCORE = "_";
private Utils() {
//Not meant to be instantiated.
}
public static String replaceUnderscoresBySpaces(String s) {
if (!s.contains(UNDERSCORE)) {
//nothing to do
return s;
}
return s.replace(UNDERSCORE, " ");
}
public static String makeFirstLetterUppercase(String s) {
if (Character.isLetter(s.charAt(0)) && Character.isLowerCase(s.charAt(0))) {
return Character.toUpperCase(s.charAt(0))
+ (s.length() == 1 ? "" : s.substring(1));
} else {
return s;
}
}
public static List<File> listAllFilesInDir(File dir) {
return listAllFilesInDir(dir, new ArrayList<>());
}
private static List<File> listAllFilesInDir(File dir, List<File> files) {
files.add(dir);
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
listAllFilesInDir(f, files);
} else {
files.add(f);
}
}
return files;
}
public static void copyFile(File originalFile, File copiedFile) throws BitBackupException {
Path originalPath = originalFile.toPath();
Path copied = new File(copiedFile, originalFile.getName()).toPath();
try {
java.nio.file.Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
ex.printStackTrace();
throw new BitBackupException("Copying file failed: " + originalFile.getAbsolutePath());
}
}
public static void writeTextToFile(String text, File file) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
} catch (IOException ex) {
ex.printStackTrace();
throw new BitBackupException("Writing to file failed: " + file.getName(), ex);
}
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(text);
printWriter.close();
}
public static String readTextFromFile(File file) {
if (!file.exists()) {
return "";
}
try {
return new String(java.nio.file.Files.readAllBytes(Paths.get(file.getAbsolutePath())));
} catch (IOException ex) {
throw new BitBackupException("Reading file failed: " + file.getAbsolutePath(), ex);
}
}
public static String readTextFromResourceFile(String fileName) {
try {
Class clazz = Main.class;
InputStream inputStream = clazz.getResourceAsStream(fileName);
return readFromInputStream(inputStream);
} catch (IOException ex) {
throw new BitBackupException("Reading file failed: " + fileName, ex);
}
}
public static String readFromInputStream(InputStream inputStream)
throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br
= new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
return resultStringBuilder.toString();
}
public static String calculateSHA512Hash(File file) {
try {
return Files.hash(file, Hashing.sha512()).toString();
} catch (IOException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
throw new BitBackupException(ex);
}
}
public static String calculateSHA256Hash(File file) {
if(file.isDirectory()) {return "";}
try {
return Files.hash(file, Hashing.sha256()).toString();
} catch (IOException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
throw new BitBackupException(ex);
}
}
public static String createJdbcUrl(String directoryWhereSqliteFileIs) {
return "jdbc:sqlite:" + directoryWhereSqliteFileIs + "/" + ".bitbackup.sqlite3?foreign_keys=on;";
}
public static String encodeBase64(String s) {
return Base64.getEncoder().encodeToString(s.getBytes());
}
public static String decodeBase64(String s) {
byte[] decodedBytes = Base64.getDecoder().decode(s);
return new String(decodedBytes);
}
}

View File

@ -0,0 +1,47 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
@Getter
@Setter
@AllArgsConstructor
@ToString
public class FsFile {
private final String id;
private String name;
private String absolutePath;
private String lastModificationDate;
private String lastCheckDate;
private String hashSumValue;
private String hashSumAlgorithm;
private long size;
private String lastCheckResult;
}

View File

@ -0,0 +1,39 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
@Getter
@Setter
@AllArgsConstructor
public class SystemItem {
private String key;
private String value;
}

View File

@ -0,0 +1,184 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.files;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import lombok.ToString;
import com.robertvokac.bitbackup.core.Utils;
/**
*
* @author robertvokac
*/
@ToString
public class FileEntry {
private String path;
private String fileName;
private FileType fileType;
private String linkTarget;
private int uid;
private int gid;
private String owner;
private String group;
//https://www.redhat.com/sysadmin/suid-sgid-sticky-bit
private UnixPermissions unixPermissions = new UnixPermissions();
//private String acl;
private long creationTime;
private long lastModTime;
private long lastChangeTime;
private long lastAccessTime;
private long size;
private String hashAlgorithm;
private String hashSum;
private Map<String, String> attrs = null;
public FileEntry(File file) throws IOException {
fileName = file.getName();
fileName = fileName.replace("\t", " ");
path = fileName.equals(SLASH) ? "" : file.getParentFile().getAbsolutePath();
final Path toPath = file.toPath();
//https://www.baeldung.com/java-nio2-file-attribute
BasicFileAttributeView basicFileAttributeView = Files.getFileAttributeView(toPath, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = basicFileAttributeView.readAttributes();
fileType = FileType.forFile(basicFileAttributes);
linkTarget = fileType == FileType.LINK ? Files.readSymbolicLink(toPath).toString() : "";
uid = (Integer) Files.getAttribute(toPath, "unix:uid");
gid = (Integer) Files.getAttribute(toPath, "unix:gid");
FileOwnerAttributeView ownerView = Files.getFileAttributeView(toPath, FileOwnerAttributeView.class);
UserPrincipal owner_ = ownerView.getOwner();
PosixFileAttributes posixFileAttributes = Files.readAttributes(toPath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
GroupPrincipal group_ = posixFileAttributes.group();
owner = owner_.getName();
group = group_.getName();
//https://stackoverflow.com/questions/13241967/change-file-owner-group-under-linux-with-java-nio-files
Set<PosixFilePermission> posixFilePermissions = posixFileAttributes.permissions();
unixPermissions.getUser().setRead(posixFilePermissions.contains(PosixFilePermission.OWNER_READ));
unixPermissions.getUser().setWrite(posixFilePermissions.contains(PosixFilePermission.OWNER_WRITE));
unixPermissions.getUser().setExecute(posixFilePermissions.contains(PosixFilePermission.OWNER_EXECUTE));
//
unixPermissions.getGroup().setRead(posixFilePermissions.contains(PosixFilePermission.GROUP_READ));
unixPermissions.getGroup().setWrite(posixFilePermissions.contains(PosixFilePermission.GROUP_WRITE));
unixPermissions.getGroup().setExecute(posixFilePermissions.contains(PosixFilePermission.GROUP_EXECUTE));
//
unixPermissions.getOthers().setRead(posixFilePermissions.contains(PosixFilePermission.OTHERS_READ));
unixPermissions.getOthers().setWrite(posixFilePermissions.contains(PosixFilePermission.OTHERS_WRITE));
unixPermissions.getOthers().setExecute(posixFilePermissions.contains(PosixFilePermission.OTHERS_EXECUTE));
//
FileTime created = basicFileAttributes.creationTime();
FileTime modified = basicFileAttributes.lastModifiedTime();
FileTime accessed = basicFileAttributes.lastAccessTime();
creationTime = created.to(TimeUnit.MILLISECONDS);
lastModTime = modified.to(TimeUnit.MILLISECONDS);
lastChangeTime = ((FileTime) Files.getAttribute(toPath, "unix:ctime")).toMillis();
lastAccessTime = accessed.to(TimeUnit.MILLISECONDS);
size = basicFileAttributes.size();
hashAlgorithm = SH_A256;
hashSum = Utils.calculateSHA256Hash(file);
UserDefinedFileAttributeView userDefView = Files.getFileAttributeView(
toPath, UserDefinedFileAttributeView.class);
List<String> attributeNames = userDefView.list();
for (String key : attributeNames) {
if (attrs == null) {
attrs = new HashMap<>();
}
ByteBuffer attributeValue = ByteBuffer.allocate(userDefView.size(key));
userDefView.read(key, attributeValue);
attributeValue.flip();
String value = Charset.defaultCharset().decode(attributeValue).toString();
attrs.put(key, value);
}
}
public String attrsAsBase64EncodedString() {
StringBuilder attrsSb = new StringBuilder();
Set<String> keys = attrs.keySet();
List<String> keysList = new ArrayList<>();
keys.stream().forEach(e -> keysList.add(e));
Collections.sort(keysList);
for (String key : keysList) {
String value = attrs.get(key);
attrsSb.append(key).append("=").append(value).append("\n");
}
return Utils.encodeBase64(attrsSb.toString());
}
private static final String SH_A256 = "SHA-256";
private static final String SLASH = "/";
public String toCsvLine() {
StringBuilder sb = new StringBuilder();
sb
.append(path).append('\t')
.append(fileName).append('\t')
.append(fileType.getCh()).append('\t')
.append(linkTarget).append('\t')
.append(uid).append('\t')
.append(gid).append('\t')
.append(owner).append('\t')
.append(group).append('\t')
.append(unixPermissions.toString()).append('\t')
.append(creationTime).append('\t')
.append(lastModTime).append('\t')
.append(lastChangeTime).append('\t')
.append(lastAccessTime).append('\t')
.append(size).append('\t')
.append(hashAlgorithm).append('\t')
.append(hashSum).append('\t')
.append(attrs == null ? "" : attrsAsBase64EncodedString());
return sb.toString();
}
public static void main(String[] args) throws IOException {
final FileEntry fileEntry = new FileEntry(new File("/home/robertvokac/Downloads/zim_0.75.1-1_all.deb"));
System.out.println(fileEntry.toCsvLine());
}
}

View File

@ -0,0 +1,51 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.files;
import java.nio.file.attribute.BasicFileAttributes;
import lombok.Getter;
/**
*
* @author robertvokac
*/
public enum FileType {
DIR("d"), REGULAR("-"), LINK("l"), OTHER("z");
@Getter
private String ch;
FileType(String ch) {
this.ch = ch;
}
static FileType forFile(BasicFileAttributes basicFileAttributes) {
if (basicFileAttributes.isDirectory()) {
return DIR;
}
if (basicFileAttributes.isRegularFile()) {
return REGULAR;
}
if (basicFileAttributes.isSymbolicLink()) {
return LINK;
}
else return OTHER;
}
}

View File

@ -0,0 +1,104 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.files;
import lombok.Getter;
import lombok.Setter;
import com.robertvokac.bitbackup.core.BitBackupException;
/**
*
* @author robertvokac
*/
@Setter
@Getter
public class UnixPermission {
private static final char R = 'r';
private static final char W = 'w';
private static final char X = 'x';
private static final char LOWER_S = 's';
private static final char UPPER_S = 'S';
private static final char LOWER_T = 't';
private static final char UPPER_T = 'T';
private static final char DASH = '-';
public UnixPermission(com.robertvokac.bitbackup.files.UnixPermissionType linuxPermissionType) {
this.unixPermissionType = linuxPermissionType;
}
private final UnixPermissionType unixPermissionType;
private boolean read;
private boolean write;
private boolean execute;
private boolean special;
public void setFromString(String s) {
if (s.length() != 3) {
throw new BitBackupException("Cannot parse UnixPermission, because the expected lenght is 9, but given is " + s.length());
}
char[] charArray = s.toCharArray();
final char ch1 = charArray[0];
final char ch2 = charArray[1];
final char ch3 = charArray[2];
switch(ch1) {
case R : read = true; break;
case DASH : read = false; break;
default: throw new BitBackupException("Cannot parse read UnixPermission from character: " + ch1);
}
switch(ch2) {
case W : write = true; break;
case DASH : write = false; break;
default: throw new BitBackupException("Cannot parse write UnixPermission from character: " + ch1);
}
switch(ch3) {
case X : execute = true; special = false; break;
case LOWER_S: if(unixPermissionType == UnixPermissionType.OTHERS) {throw new BitBackupException("Invalid letter " + ch3);} execute = true; special = true; break;
case UPPER_S: if(unixPermissionType == UnixPermissionType.OTHERS) {throw new BitBackupException("Invalid letter " + ch3);} execute = false; special = true; break;
case LOWER_T: if(unixPermissionType != UnixPermissionType.OTHERS) {throw new BitBackupException("Invalid letter " + ch3);} execute = true; special = true; break;
case UPPER_T: if(unixPermissionType != UnixPermissionType.OTHERS) {throw new BitBackupException("Invalid letter " + ch3);} execute = false; special = true; break;
case DASH : execute = false; special = false;break;
default: throw new BitBackupException("Cannot parse execute UnixPermission from character: " + ch1);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(read ? R : DASH);
sb.append(write ? W : DASH);
if (execute) {
if (special) {
sb.append(unixPermissionType == UnixPermissionType.OTHERS ? LOWER_T : LOWER_S);
} else {
sb.append(X);
}
} else {
if (special) {
sb.append(unixPermissionType == UnixPermissionType.OTHERS ? UPPER_T : UPPER_S);
} else {
sb.append(DASH);
}
}
return sb.toString();
}
}

View File

@ -0,0 +1,29 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.files;
/**
*
* @author robertvokac
*/
public enum UnixPermissionType {
USER, GROUP, OTHERS;
}

View File

@ -0,0 +1,77 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.files;
import lombok.Getter;
import com.robertvokac.bitbackup.core.BitBackupException;
/**
*
* @author robertvokac
*/
@Getter
public class UnixPermissions {
private UnixPermission user = new UnixPermission(UnixPermissionType.USER);
private UnixPermission group = new UnixPermission(UnixPermissionType.GROUP);
private UnixPermission others = new UnixPermission(UnixPermissionType.OTHERS);
public UnixPermissions() {
}
public UnixPermissions(String s) {
if (s.length() != 9) {
throw new BitBackupException("Cannot parse UnixPermissions, because the expected lenght is 9, but given is " + s.length());
}
user.setFromString(s.substring(0, 3));
group.setFromString(s.substring(3, 6));
others.setFromString(s.substring(6, 9));
}
public void setSUID(boolean b) {
user.setSpecial(b);
}
public void setSGID(boolean b) {
group.setSpecial(b);
}
public void setStickyBit(boolean b) {
others.setSpecial(b);
}
public boolean isSUID(boolean b) {
return user.isSpecial();
}
public boolean isSGID(boolean b) {
return group.isSpecial();
}
public boolean isStickyBit(boolean b) {
return others.isSpecial();
}
public String toString() {
return user.toString() + group.toString() + others.toString();
}
}

View File

@ -0,0 +1 @@
lombok.log.fieldName=LOG

View File

@ -0,0 +1,31 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.api;
import java.sql.Connection;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public interface ConnectionFactory {
Connection createConnection() throws ClassNotFoundException;
}

View File

@ -0,0 +1,37 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.api;
import java.util.List;
import com.robertvokac.bitbackup.entity.FsFile;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public interface FileRepository {
void create(List<FsFile> files);
List<FsFile> list();
void remove(FsFile file);
void updateFile(FsFile file);
void updateLastCheckDate(String lastCheckDate, List<FsFile> files);
}

View File

@ -0,0 +1,37 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.api;
import java.util.List;
import com.robertvokac.bitbackup.entity.SystemItem;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public interface SystemItemRepository {
String create(SystemItem systemItem);
List<SystemItem> list();
SystemItem read(String key);
void remove(String key);
void update(SystemItem systemItem);
}

View File

@ -0,0 +1,32 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class Constants {
private Constants() {
//Not meant to be instantiated.
}
}

View File

@ -0,0 +1,319 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.robertvokac.bitbackup.entity.FsFile;
import com.robertvokac.bitbackup.persistence.api.FileRepository;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class FileRepositoryImplSqlite implements FileRepository {
private SqliteConnectionFactory sqliteConnectionFactory;
public FileRepositoryImplSqlite(SqliteConnectionFactory sqliteConnectionFactory) {
this.sqliteConnectionFactory = sqliteConnectionFactory;
}
@Override
public void create(List<FsFile> files) {
if (files.isEmpty()) {
return;
}
if (files.size() > 100) {
List<FsFile> tmpList = new ArrayList<>();
for (int i = 0; i < files.size(); i++) {
FsFile e = files.get(i);
tmpList.add(e);
if (tmpList.size() >= 100) {
create(tmpList);
tmpList.clear();
}
}
if (!tmpList.isEmpty()) {
create(tmpList);
tmpList.clear();
}
return;
}
StringBuilder sb = new StringBuilder();
sb
.append("INSERT INTO ")
.append(FileTable.TABLE_NAME)
.append("(")
.append(FileTable.ID).append(",")
.append(FileTable.NAME).append(",")
.append(FileTable.ABSOLUTE_PATH).append(",")
.append(FileTable.LAST_MODIFICATION_DATE).append(",")
.append(FileTable.LAST_CHECK_DATE).append(",")
//
.append(FileTable.HASH_SUM_VALUE).append(",")
.append(FileTable.HASH_SUM_ALGORITHM).append(",")
.append(FileTable.SIZE).append(",")
.append(FileTable.LAST_CHECK_RESULT).append("");
sb.append(") VALUES ");
int index = 0;
for (FsFile f : files) {
sb.append(" (?,?,?,?,?, ?,?,?,?)");
boolean lastFile = index == (files.size() - 1);
if (!lastFile) {
sb.append(",");
}
index = index + 1;
}
String sql = sb.toString();
//System.err.println(sql);
try (
Connection connection = createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
int i = 0;
for (FsFile f : files) {
stmt.setString(++i, f.getId());
stmt.setString(++i, f.getName());
stmt.setString(++i, f.getAbsolutePath());
stmt.setString(++i, f.getLastModificationDate());
//
stmt.setString(++i, f.getLastCheckDate());
//
stmt.setString(++i, f.getHashSumValue());
stmt.setString(++i, f.getHashSumAlgorithm());
stmt.setLong(++i, f.getSize());
stmt.setString(++i, f.getLastCheckResult());
}
//
stmt.execute();
//System.out.println(stmt.toString());
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public List<FsFile> list() {
List<FsFile> result = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb
.append("SELECT * FROM ")
.append(FileTable.TABLE_NAME);
String sql = sb.toString();
// System.err.println(sql);
int i = 0;
ResultSet rs = null;
try (
Connection connection = createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
System.err.println(stmt.toString());
rs = stmt.executeQuery();
while (rs.next()) {
result.add(extractFileFromResultSet(rs));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
return result;
}
@Override
public void remove(FsFile file) {
StringBuilder sb = new StringBuilder();
sb
.append("DELETE FROM ")
.append(FileTable.TABLE_NAME);
sb.append(" WHERE ");
sb.append(FileTable.ID);
sb.append("=?");
String sql = sb.toString();
//System.err.println("SQL::" + sql);
int i = 0;
try (
Connection connection = createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
stmt.setString(++i, file.getId());
//System.err.println(stmt.toString());
stmt.execute();
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Connection createConnection() throws ClassNotFoundException {
return sqliteConnectionFactory.createConnection();
}
@Override
public void updateFile(FsFile file) {
StringBuilder sb = new StringBuilder();
sb
.append("UPDATE ")
.append(FileTable.TABLE_NAME)
.append(" SET ")
.append(FileTable.LAST_MODIFICATION_DATE).append("=?, ")
.append(FileTable.LAST_CHECK_DATE).append("=?, ")
.append(FileTable.HASH_SUM_VALUE).append("=?, ")
.append(FileTable.HASH_SUM_ALGORITHM).append("=?, ")
.append(FileTable.SIZE).append("=?, ")
.append(FileTable.LAST_CHECK_RESULT).append("=? ")
.append(" WHERE ").append(FileTable.ID).append("=?");
String sql = sb.toString();
//System.err.println(sql);
try (
Connection connection = createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
int i = 0;
stmt.setString(++i, file.getLastModificationDate());
stmt.setString(++i, file.getLastCheckDate());
stmt.setString(++i, file.getHashSumValue());
stmt.setString(++i, file.getHashSumAlgorithm());
stmt.setLong(++i, file.getSize());
stmt.setString(++i, file.getLastCheckResult());
stmt.setString(++i, file.getId());
int numberOfUpdatedRows = stmt.executeUpdate();
//System.out.println("numberOfUpdatedRows=" + numberOfUpdatedRows);
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
private FsFile extractFileFromResultSet(final ResultSet rs) throws SQLException {
return new FsFile(
rs.getString(FileTable.ID),
rs.getString(FileTable.NAME),
rs.getString(FileTable.ABSOLUTE_PATH),
rs.getString(FileTable.LAST_MODIFICATION_DATE),
rs.getString(FileTable.LAST_CHECK_DATE),
rs.getString(FileTable.HASH_SUM_VALUE),
rs.getString(FileTable.HASH_SUM_ALGORITHM),
rs.getLong(FileTable.SIZE),
rs.getString(FileTable.LAST_CHECK_RESULT)
);
}
@Override
public void updateLastCheckDate(String lastCheckDate, List<FsFile> files) {
if (files.isEmpty()) {
return;
}
if (files.size() > 100) {
List<FsFile> tmpList = new ArrayList<>();
for (int i = 0; i < files.size(); i++) {
FsFile e = files.get(i);
tmpList.add(e);
if (tmpList.size() >= 100) {
updateLastCheckDate(lastCheckDate, tmpList);
tmpList.clear();
}
}
if (!tmpList.isEmpty()) {
updateLastCheckDate(lastCheckDate, tmpList);
tmpList.clear();
}
return;
}
StringBuilder sb = new StringBuilder();
sb
.append("UPDATE ")
.append(FileTable.TABLE_NAME)
.append(" SET ")
.append(FileTable.LAST_CHECK_DATE).append("=?, ")
.append(FileTable.LAST_CHECK_RESULT).append("='OK' ")
.append(" WHERE ").append(FileTable.ID).append(" IN (");
int index = 0;
for (FsFile f : files) {
index = index + 1;
sb.append("?");
if (index < files.size()) {
sb.append(",");
}
}
sb.append(")");
String sql = sb.toString();
//System.err.println(sql);
try (
Connection connection = createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
int i = 0;
stmt.setString(++i, lastCheckDate);
for (FsFile f : files) {
stmt.setString(++i, f.getId());
}
int numberOfUpdatedRows = stmt.executeUpdate();
//System.out.println("numberOfUpdatedRows=" + numberOfUpdatedRows);
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FileRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

View File

@ -0,0 +1,48 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
@Getter
@Setter
@AllArgsConstructor
class FileTable {
public static final String TABLE_NAME = "FILE";
public static final String ID = "ID";
public static final String NAME = "NAME";
public static final String ABSOLUTE_PATH = "ABSOLUTE_PATH";
public static final String LAST_MODIFICATION_DATE = "LAST_MODIFICATION_DATE";
public static final String LAST_CHECK_DATE = "LAST_CHECK_DATE";
//
public static final String HASH_SUM_VALUE = "HASH_SUM_VALUE";
public static final String HASH_SUM_ALGORITHM = "HASH_SUM_ALGORITHM";
public static final String SIZE = "SIZE";
public static final String LAST_CHECK_RESULT = "LAST_CHECK_RESULT";
}

View File

@ -0,0 +1,54 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import com.robertvokac.bitbackup.persistence.api.ConnectionFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.robertvokac.bitbackup.core.Utils;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class SqliteConnectionFactory implements ConnectionFactory {
private final String jdbcUrl;
public SqliteConnectionFactory(String directoryWhereSqliteFileIs) {
this.jdbcUrl = Utils.createJdbcUrl(directoryWhereSqliteFileIs);
}
public Connection createConnection() throws ClassNotFoundException {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(jdbcUrl);
return conn;
} catch (SQLException ex) {
if (true) {
throw new RuntimeException(ex);
}
System.err.println(ex.getMessage());
return null;
}
}
}

View File

@ -0,0 +1,67 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import com.robertvokac.bitbackup.core.Utils;
import com.robertvokac.dbmigration.core.main.DBMigration;
import com.robertvokac.dbmigration.core.main.MigrationResult;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class SqliteDatabaseMigration {
private static SqliteDatabaseMigration INSTANCE;
private SqliteDatabaseMigration() {
//Not meant to be instantiated
}
public static SqliteDatabaseMigration getInstance() {
if (INSTANCE == null) {
INSTANCE = new SqliteDatabaseMigration();
}
return INSTANCE;
}
public MigrationResult migrate(String directoryWhereSqliteFileIs) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
throw new RuntimeException(ex);
}
String jdbcUrl = Utils.createJdbcUrl(directoryWhereSqliteFileIs);
System.err.println("jdbcUrl=" + jdbcUrl);
String clazz = this.getClass().getName();
DBMigration dbMigration = DBMigration
.configure()
.dataSource(jdbcUrl)
.installedBy("bitbackup-persistence-impl-sqlite")
.name("bitbackup")
.sqlDialect("sqlite", "com.robertvokac.dbmigration.core.persistence.impl.sqlite.DBMigrationPersistenceSqliteImpl")
.sqlMigrationsClass(clazz)
.load();
return dbMigration.migrate();
}
}

View File

@ -0,0 +1,171 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.robertvokac.bitbackup.entity.SystemItem;
import com.robertvokac.bitbackup.persistence.api.SystemItemRepository;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
public class SystemItemRepositoryImplSqlite implements SystemItemRepository {
public SystemItemRepositoryImplSqlite(SqliteConnectionFactory sqliteConnectionFactory) {
this.sqliteConnectionFactory = sqliteConnectionFactory;
}
private final SqliteConnectionFactory sqliteConnectionFactory;
@Override
public String create(SystemItem systemItem) {
StringBuilder sb = new StringBuilder();
sb
.append("INSERT INTO ")
.append(SystemItemTable.TABLE_NAME)
.append("(")
.append(SystemItemTable.KEY).append(",")
//
.append(SystemItemTable.VALUE);
sb.append(")")
.append(" VALUES (?,?)");
String sql = sb.toString();
System.err.println(sql);
try (
Connection connection = sqliteConnectionFactory.createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
int i = 0;
stmt.setString(++i, systemItem.getKey());
stmt.setString(++i, systemItem.getValue());
//
stmt.execute();
System.out.println(stmt.toString());
return systemItem.getKey();
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SystemItemRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
System.err.println("Error.");
return "";
}
@Override
public List<SystemItem> list() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
@Override
public SystemItem read(String key) {
if (key == null) {
throw new RuntimeException("key is null");
}
StringBuilder sb = new StringBuilder();
sb
.append("SELECT * FROM ")
.append(SystemItemTable.TABLE_NAME)
.append(" WHERE ")
.append(SystemItemTable.KEY)
.append("=?");
String sql = sb.toString();
int i = 0;
ResultSet rs = null;
try (
Connection connection = sqliteConnectionFactory.createConnection(); PreparedStatement stmt = connection.prepareStatement(sql);) {
stmt.setString(++i, key);
rs = stmt.executeQuery();
while (rs.next()) {
return extractSystemItemFromResultSet(rs);
}
return new SystemItem(key, null);
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SystemItemRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException ex) {
Logger.getLogger(SystemItemRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
@Override
public void remove(String key) {
if (key == null) {
throw new RuntimeException("key is null");
}
StringBuilder sb = new StringBuilder();
sb
.append("DELETE FROM ")
.append(SystemItemTable.TABLE_NAME)
.append(" WHERE ")
.append(SystemItemTable.KEY)
.append("=?");
String sql = sb.toString();
try (
Connection connection = sqliteConnectionFactory.createConnection(); PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, key);
stmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SystemItemRepositoryImplSqlite.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
@Override
public void update(SystemItem systemItem) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
private SystemItem extractSystemItemFromResultSet(final ResultSet rs) throws SQLException {
return new SystemItem(
rs.getString(SystemItemTable.KEY),
rs.getString(SystemItemTable.VALUE)
);
}
}

View File

@ -0,0 +1,39 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2023-2023 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.robertvokac.bitbackup.persistence.impl.sqlite;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author <a href="mailto:mail@robertvokac.com">Robert Vokac</a>
*/
@Getter
@Setter
@AllArgsConstructor
class SystemItemTable {
public static final String TABLE_NAME = "SYSTEM_ITEM";
public static final String KEY = "KEY";
public static final String VALUE = "VALUE";
}

30
src/main/java/module-info.java Executable file
View File

@ -0,0 +1,30 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// bit-backup: Tool detecting bit rots in files.
// Copyright (C) 2016-2022 the original author or authors.
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
module bitbackup {
requires org.apache.commons.io;
requires lombok;
requires org.apache.logging.log4j;
requires dbmigration.core;
requires java.sql;
requires powerframework.time;
requires powerframework.collections;
requires dev.mccue.guava.io;
}

View File

View File

@ -0,0 +1,14 @@
CREATE TABLE "FILE" (
"ID" TEXT,
"NAME" TEXT NOT NULL,
"ABSOLUTE_PATH" TEXT NOT NULL,
"LAST_MODIFICATION_DATE" TEXT NOT NULL,
"LAST_CHECK_DATE" TEXT NOT NULL,
"HASH_SUM_VALUE" TEXT NOT NULL,
"HASH_SUM_ALGORITHM" TEXT NOT NULL,
UNIQUE(ABSOLUTE_PATH),
PRIMARY KEY("ID")
);
CREATE UNIQUE INDEX IDX_FILE_ABSOLUTE_PATH
ON FILE (ABSOLUTE_PATH);

View File

@ -0,0 +1,6 @@
CREATE TABLE "SYSTEM_ITEM" (
"KEY" TEXT,
"VALUE" TEXT NOT NULL,
PRIMARY KEY("KEY")
)

View File

@ -0,0 +1,2 @@
ALTER TABLE "FILE" ADD COLUMN SIZE NUMBER

View File

@ -0,0 +1,2 @@
ALTER TABLE "FILE" ADD COLUMN LAST_CHECK_RESULT NUMBER

View File

@ -0,0 +1,5 @@
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
rootLogger=info, STDOUT