pax_global_header 0000666 0000000 0000000 00000000064 14341627633 0014523 g ustar 00root root 0000000 0000000 52 comment=48e7baa5d692c729174f0a73037b35c6abda9f0f
vospace-file-service-master/ 0000775 0000000 0000000 00000000000 14341627633 0016373 5 ustar 00root root 0000000 0000000 vospace-file-service-master/.gitignore 0000664 0000000 0000000 00000000656 14341627633 0020372 0 ustar 00root root 0000000 0000000 HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
nbactions.xml
### VS Code ###
.vscode/
/nb-configuration.xml vospace-file-service-master/.gitlab-ci.yml 0000664 0000000 0000000 00000002574 14341627633 0021037 0 ustar 00root root 0000000 0000000 stages:
- test
- dockerize
- publish
variables:
# to avoid "fatal: git fetch-pack: expected shallow list"
GIT_STRATEGY: clone
test:
stage: test
tags:
- docker
image: "git.ia2.inaf.it:5050/vospace/vospace-rest/vospace-test-env"
variables:
FILE_CATALOG_REPO_URL: "https://gitlab-ci-token:${CI_JOB_TOKEN}@www.ict.inaf.it/gitlab/vospace/vospace-file-catalog.git"
script:
- git clone ${FILE_CATALOG_REPO_URL}
- mvn clean test -Dinit_database_scripts_path=../../vospace-file-catalog
- awk -F"," '{ instructions += $4 + $5; covered += $5 } END { print "coverage=" 100*covered/instructions }' target/site/jacoco/jacoco.csv
coverage: '/coverage=\d+\.\d+/'
only:
- master
deploy:
stage: dockerize
tags:
- shell
only:
- master
script:
- docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
- docker build -t "${CI_REGISTRY_IMAGE}" .
- docker push "${CI_REGISTRY_IMAGE}"
upload_jar:
stage: publish
tags:
- shell
only:
- master
script:
# extract jar from Docker image
- docker run --rm --entrypoint cat "${CI_REGISTRY_IMAGE}" /vospace-file-service.jar > vospace-file-service.jar
- 'curl --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file vospace-file-service.jar "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/vospace-file-service/latest/vospace-file-service.jar"'
vospace-file-service-master/Dockerfile 0000664 0000000 0000000 00000000470 14341627633 0020366 0 ustar 00root root 0000000 0000000 FROM maven:3.6.3-openjdk-14
ADD pom.xml .
RUN mvn dependency:go-offline
ADD src /src
RUN mvn clean package -DskipTests -DfinalName=vospace-file-service
FROM openjdk:14-jdk-alpine
COPY --from=0 /target/vospace-file-service.jar /vospace-file-service.jar
ENTRYPOINT ["java","-jar","/vospace-file-service.jar"]
vospace-file-service-master/LICENSE 0000664 0000000 0000000 00000104515 14341627633 0017406 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
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
.
vospace-file-service-master/README.md 0000664 0000000 0000000 00000000561 14341627633 0017654 0 ustar 00root root 0000000 0000000 # File service for VOSpace
This service queries the same database used by VOSpace (`file_catalog`).
It provides functionalities for downloading and uploading files.
## Running with Docker
See `docker-env` file for configuration
docker run -it --env-file docker-env -v "/path/to/userspace:/tmp/fsdemo" -p 8080:8080 git.ia2.inaf.it:5050/ia2/vospace-file-service
vospace-file-service-master/docker-env 0000664 0000000 0000000 00000000426 14341627633 0020355 0 ustar 00root root 0000000 0000000 upload_location_id=3
file-catalog.datasource.jdbc-url=jdbc:postgresql://172.19.0.1:5432/vospace_testdb
file-catalog.datasource.username=postgres
file-catalog.datasource.password=
gms_base_url=https://sso.ia2.inaf.it/gms
jwks_uri=https://sso.ia2.inaf.it/rap-ia2/auth/oidc/jwks
vospace-file-service-master/pom.xml 0000664 0000000 0000000 00000006346 14341627633 0017721 0 ustar 00root root 0000000 0000000
4.0.0
it.inaf.ia2
vospace-parent
0.0.2-SNAPSHOT
it.inaf.ia2
vospace-file-service
0.0.2-SNAPSHOT
vospace-file-service
VOSpace File service
${project.artifactId}-${project.version}
../../../vospace-file-catalog
it.inaf.ia2
vospace-parent-classes
0.0.2-SNAPSHOT
org.kamranzafar
jtar
2.3
${finalName}
src/test/resources
true
test.properties
src/test/resources
false
**/*
test.properties
org.springframework.boot
spring-boot-maven-plugin
true
org.jacoco
jacoco-maven-plugin
prepare-agent
report
test
report
ia2-snapshots
IA2 snapshot repository
http://repo.ia2.inaf.it/maven/repository/snapshots
vospace-file-service-master/src/ 0000775 0000000 0000000 00000000000 14341627633 0017162 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/ 0000775 0000000 0000000 00000000000 14341627633 0020106 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/ 0000775 0000000 0000000 00000000000 14341627633 0021027 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/ 0000775 0000000 0000000 00000000000 14341627633 0021443 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ 0000775 0000000 0000000 00000000000 14341627633 0022360 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/ 0000775 0000000 0000000 00000000000 14341627633 0023033 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/ 0000775 0000000 0000000 00000000000 14341627633 0024657 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/CorsConfig.java 0000664 0000000 0000000 00000002123 14341627633 0027554 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Value("${cors.allowed.origin}")
private String corsAllowedOrigin;
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] allowedOrigins = corsAllowedOrigin.split(",");
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("*")
.allowCredentials(true);
}
};
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/FileServiceApplication.java 0000664 0000000 0000000 00000003515 14341627633 0032112 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer;
import it.inaf.ia2.aa.jwt.JwksClient;
import it.inaf.ia2.aa.jwt.TokenParser;
import it.inaf.ia2.transfer.auth.TokenFilter;
import java.net.URI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import org.springframework.context.annotation.Import;
import it.inaf.oats.vospace.parent.persistence.LinkedServiceDAO;
import it.inaf.ia2.aa.ServiceLocator;
import it.inaf.ia2.aa.ServletRapClient;
@SpringBootApplication
@Import(LinkedServiceDAO.class)
public class FileServiceApplication {
@Value("${jwks_uri}")
private String jwksUri;
public static void main(String[] args) {
SpringApplication.run(FileServiceApplication.class, args);
}
@Bean
public TokenParser tokenParser() {
JwksClient jwksClient = new JwksClient(URI.create(jwksUri));
return new TokenParser(jwksClient);
}
@Bean
public FilterRegistrationBean tokenFilterRegistration(TokenParser tokenParser) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new TokenFilter(tokenParser));
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public ServletRapClient servletRapClient() {
return (ServletRapClient) ServiceLocator.getInstance().getRapClient();
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/auth/ 0000775 0000000 0000000 00000000000 14341627633 0025620 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/auth/GmsClient.java 0000664 0000000 0000000 00000003635 14341627633 0030357 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.auth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class GmsClient {
private static final Logger LOG = LoggerFactory.getLogger(GmsClient.class);
@Value("${gms_base_url}")
private String gmsBaseUrl;
private final RestTemplate restTemplate;
@Autowired
public GmsClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Cacheable("gms_cache")
public boolean isMemberOf(String token, String group) {
LOG.trace("called isMemberOf for group " + group);
String url = gmsBaseUrl + "/vo/search/" + URLEncoder.encode(group, StandardCharsets.UTF_8);
String gmsResponse = restTemplate.exchange(url, HttpMethod.GET, getEntity(token), String.class).getBody();
if (gmsResponse == null) {
return false;
}
return group.equals(gmsResponse.replace("\n", ""));
}
private HttpEntity getEntity(String token) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
headers.add("Authorization", "Bearer " + token);
return new HttpEntity<>(null, headers);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/auth/TokenFilter.java 0000664 0000000 0000000 00000006467 14341627633 0030726 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.auth;
import it.inaf.ia2.aa.jwt.InvalidTokenException;
import it.inaf.ia2.aa.jwt.TokenParser;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TokenFilter implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(TokenFilter.class);
private final TokenParser tokenParser;
public TokenFilter(TokenParser tokenParser) {
this.tokenParser = tokenParser;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String token = getToken(request);
TokenPrincipal tokenPrincipal;
try {
tokenPrincipal = getTokenPrincipal(token);
} catch (InvalidTokenException ex) {
response.sendError(401, "Unauthorized: " + ex.getMessage());
return;
}
RequestWithPrincipal requestWrapper = new RequestWithPrincipal(request, tokenPrincipal);
chain.doFilter(requestWrapper, response);
}
private String getToken(HttpServletRequest request) {
String token = getTokenFromHeader(request);
if (token == null) {
// get token from query string
token = request.getParameter("token");
}
return token;
}
private String getTokenFromHeader(HttpServletRequest request) {
LOG.trace("Loading token from header");
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
if (authHeader.startsWith("Bearer")) {
return authHeader.substring("Bearer".length() + 1).trim();
} else {
LOG.warn("Detected non-Bearer Authorization header");
}
}
return null;
}
private TokenPrincipal getTokenPrincipal(String token) {
if (token == null) {
// anonymous
return new TokenPrincipal();
}
Map claims = tokenParser.getClaims(token);
String userId = (String) claims.get("sub");
if (userId == null) {
throw new InvalidTokenException("Missing sub claim");
}
return new TokenPrincipal(userId, token);
}
private static class RequestWithPrincipal extends HttpServletRequestWrapper {
private final TokenPrincipal tokenPrincipal;
public RequestWithPrincipal(HttpServletRequest request, TokenPrincipal tokenPrincipal) {
super(request);
this.tokenPrincipal = tokenPrincipal;
}
@Override
public Principal getUserPrincipal() {
return tokenPrincipal;
}
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/auth/TokenPrincipal.java 0000664 0000000 0000000 00000001225 14341627633 0031405 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.auth;
import java.security.Principal;
public class TokenPrincipal implements Principal {
private final String name;
private final String token;
public TokenPrincipal() {
this("anonymous", null);
}
public TokenPrincipal(String userId, String token) {
this.name = userId;
this.token = token;
}
@Override
public String getName() {
return name;
}
public String getToken() {
return token;
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/ 0000775 0000000 0000000 00000000000 14341627633 0027042 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/ArchiveFileController.java0000664 0000000 0000000 00000005375 14341627633 0034144 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.service.ArchiveJob;
import it.inaf.ia2.transfer.service.ArchiveJob.Type;
import it.inaf.ia2.transfer.service.ArchiveService;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArchiveFileController extends AuthenticatedFileController {
@Autowired
private ArchiveService archiveService;
@Autowired
private HttpServletRequest servletRequest;
@Autowired
private HttpServletResponse response;
@PostMapping(value = "/archive", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> createArchiveFile(@RequestBody ArchiveRequest archiveRequest) {
Type type = Type.valueOf(archiveRequest.getType());
ArchiveJob job = new ArchiveJob();
job.setPrincipal(getPrincipal());
job.setJobId(archiveRequest.getJobId());
job.setType(type);
job.setEntryDescriptors(archiveRequest.getEntryDescriptors());
CompletableFuture.runAsync(() -> {
handleFileJob(() -> archiveService.createArchive(job, servletRequest), job.getJobId());
});
HttpHeaders headers = new HttpHeaders();
headers.set("Location", request.getRequestURL() + "/" + archiveRequest.getJobId() + "." + type.getExtension());
return new ResponseEntity<>(headers, HttpStatus.SEE_OTHER);
}
@GetMapping(value = "/archive/{fileName}")
public void getArchiveFile(@PathVariable("fileName") String fileName) {
TokenPrincipal principal = getPrincipal();
File file = archiveService.getArchiveParentDir(principal).toPath().resolve(fileName).toFile();
FileResponseUtil.getFileResponse(response, file);
}
@Override
protected String getCustomAuthErrorMessage() {
return "Tar/Zip archive generation not allowed to anonymous users";
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/ArchiveRequest.java 0000664 0000000 0000000 00000001656 14341627633 0032647 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.oats.vospace.parent.exchange.ArchiveEntryDescriptor;
import java.util.List;
public class ArchiveRequest {
private String type;
private String jobId;
private List entryDescriptors;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public List getEntryDescriptors() {
return entryDescriptors;
}
public void setEntryDescriptors(List entryDescriptors) {
this.entryDescriptors = entryDescriptors;
}
}
AuthenticatedFileController.java 0000664 0000000 0000000 00000001370 14341627633 0035255 0 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
public abstract class AuthenticatedFileController extends FileController {
protected TokenPrincipal getPrincipal() {
TokenPrincipal principal = (TokenPrincipal) request.getUserPrincipal();
if ("anonymous".equals(principal.getName())) {
throw new PermissionDeniedException(this.getCustomAuthErrorMessage());
}
return principal;
}
protected abstract String getCustomAuthErrorMessage();
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/CopyController.java 0000664 0000000 0000000 00000005050 14341627633 0032663 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.FileDAO;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import it.inaf.ia2.transfer.service.FileCopyService;
import it.inaf.oats.vospace.exception.InvalidArgumentException;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
@RestController
public class CopyController extends AuthenticatedFileController {
private static final Logger LOG = LoggerFactory.getLogger(CopyController.class);
@Autowired
private FileCopyService copyService;
@Autowired
private FileDAO fileDao;
@PostMapping(value = "/copy", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> copyFiles(@RequestBody CopyRequest copyRequest) {
String jobId = copyRequest.getJobId();
if (jobId == null) {
throw new InvalidArgumentException("Job Id cannot be null");
} else if (!jobDAO.isJobExisting(jobId)) {
throw new InvalidArgumentException("Job " + jobId + " not found");
}
LOG.debug("copyFiles called from jobId {}", jobId);
TokenPrincipal principal = getPrincipal();
// need to make a completable future start
CompletableFuture.runAsync(() -> {
handleFileJob(() -> {
try {
copyService.copyFiles(copyRequest.getSourceRootVosPath(),
copyRequest.getDestinationRootVosPath(), copyRequest.getJobId(),
principal);
} finally {
// TODO: cleanup code to remove unpopulated nodes in case
// of failure?
fileDao.releaseBusyNodesByJobId(jobId);
}
}, jobId);
});
return ResponseEntity.ok(
copyRequest.getJobId() + " copy task accepted by File Service"
);
}
@Override
protected String getCustomAuthErrorMessage() {
return "File Copy not allowed to anonymous users";
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/CopyRequest.java 0000664 0000000 0000000 00000001623 14341627633 0032172 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
public class CopyRequest {
private String jobId;
private String sourceRootVosPath;
private String destinationRootVosPath;
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getSourceRootVosPath() {
return sourceRootVosPath;
}
public void setSourceRootVosPath(String sourceRootVosPath) {
this.sourceRootVosPath = sourceRootVosPath;
}
public String getDestinationRootVosPath() {
return destinationRootVosPath;
}
public void setDestinationRootVosPath(String destinationRootVosPath) {
this.destinationRootVosPath = destinationRootVosPath;
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/ErrorController.java 0000664 0000000 0000000 00000001177 14341627633 0033050 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-rest
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.oats.vospace.exception.DefaultErrorController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ErrorController extends DefaultErrorController {
@Autowired
public ErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/FileController.java 0000664 0000000 0000000 00000004023 14341627633 0032627 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.VoSpaceErrorSummarizableException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class FileController {
private static final Logger LOG = LoggerFactory.getLogger(FileController.class);
@Autowired
protected HttpServletRequest request;
@Autowired
protected JobDAO jobDAO;
public String getPath() {
String uri = request.getRequestURI().substring(request.getContextPath().length());
String[] parts = uri.split("/");
return String.join("/", Arrays.stream(parts)
.map(p -> URLDecoder.decode(p, StandardCharsets.UTF_8))
.collect(Collectors.toList()));
}
public void handleFileJob(Runnable action, String jobId) {
try {
action.run();
if (jobId != null) {
jobDAO.updateJobPhase(ExecutionPhase.COMPLETED, jobId);
}
} catch (Throwable t) {
VoSpaceErrorSummarizableException jobException;
if (t instanceof VoSpaceErrorSummarizableException) {
jobException = (VoSpaceErrorSummarizableException) t;
} else {
LOG.error("Unexpected error happened", t);
jobException = new InternalFaultException("Unexpected error happened");
}
if (jobId != null) {
jobDAO.setJobError(jobId, jobException);
}
throw t;
}
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/FileResponseUtil.java 0000664 0000000 0000000 00000004226 14341627633 0033145 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.NodeNotFoundException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FileResponseUtil {
private static final Logger LOG = LoggerFactory.getLogger(FileResponseUtil.class);
public static void getFileResponse(HttpServletResponse response, File file) {
getFileResponse(response, file, null);
}
public static void getFileResponse(HttpServletResponse response, File file, String vosPath) {
String fileName = vosPath == null ? file.getName() : vosPath.substring(vosPath.lastIndexOf("/") + 1);
if (!file.exists()) {
LOG.error("File not found: " + file.getAbsolutePath());
throw new NodeNotFoundException(vosPath == null ? file.getAbsolutePath() : vosPath);
}
if (!file.canRead()) {
LOG.error("File not readable: " + file.getAbsolutePath());
throw new InternalFaultException("File " + file.getName() + " is not readable");
}
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setCharacterEncoding("UTF-8");
byte[] bytes = new byte[1024];
try ( OutputStream out = response.getOutputStream(); InputStream is = new FileInputStream(file)) {
int read;
while ((read = is.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/GetFileController.java 0000664 0000000 0000000 00000005024 14341627633 0033271 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.ia2.transfer.service.AuthorizationService;
import it.inaf.oats.vospace.exception.InvalidArgumentException;
import it.inaf.oats.vospace.exception.NodeNotFoundException;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
import java.io.File;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GetFileController extends FileController {
private static final Logger LOG = LoggerFactory.getLogger(GetFileController.class);
@Autowired
private FileDAO fileDAO;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private HttpServletResponse response;
@GetMapping("/**")
public void getFile(@RequestParam(value = "jobId", required = false) String jobId) {
String path = getPath();
LOG.debug("getFile called for path {}", path);
if (jobId == null) {
LOG.debug("getFile called for path {}", path);
} else {
LOG.debug("getFile called for path {} with jobId {}", path, jobId);
if (!jobDAO.isJobExisting(jobId)) {
throw new InvalidArgumentException("Job " + jobId + " not found");
}
}
handleFileJob(() -> {
Optional optFileInfo = fileDAO.getFileInfo(path);
if (optFileInfo.isPresent()) {
FileInfo fileInfo = optFileInfo.get();
if (!authorizationService.isDownloadable(fileInfo, (TokenPrincipal) request.getUserPrincipal())) {
throw PermissionDeniedException.forPath(path);
}
File file = new File(fileInfo.getFilePath());
FileResponseUtil.getFileResponse(response, file, path);
} else {
throw new NodeNotFoundException(path);
}
}, jobId);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/controller/PutFileController.java 0000664 0000000 0000000 00000007776 14341627633 0033342 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.service.PutFileService;
import it.inaf.oats.vospace.exception.InvalidArgumentException;
import it.inaf.oats.vospace.exception.NodeNotFoundException;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.http.HttpHeaders;
@RestController
public class PutFileController extends FileController {
private static final Logger LOG = LoggerFactory.getLogger(PutFileController.class);
@Autowired
private FileDAO fileDAO;
@Autowired
private PutFileService putFileService;
@PutMapping("/**")
public void putFile(@RequestHeader(value = HttpHeaders.CONTENT_ENCODING, required = false) String contentEncoding,
@RequestParam(value = "file", required = false) MultipartFile file,
@RequestParam(value = "jobId", required = false) String jobId,
HttpServletRequest request) throws IOException, NoSuchAlgorithmException {
String path = getPath();
if (jobId == null) {
LOG.debug("putFile called for path {}", path);
} else {
LOG.debug("putFile called for path {} with jobId {}", path, jobId);
if (!jobDAO.isJobExisting(jobId)) {
throw new InvalidArgumentException("Job " + jobId + " not found");
}
}
handleFileJob(() -> {
int nodes = fileDAO.setBusy(path, jobId);
if (nodes == 1) {
try {
FileInfo fileInfo
= fileDAO.getFileInfo(path).orElseThrow(
// This can happen only if some code ignores busy state
// and deletes the node
() -> {
throw new NodeNotFoundException(path);
});
String parentPath = FileInfo.getVosParentPath(fileInfo);
Long remainingQuota = fileDAO.getRemainingQuota(parentPath);
// if MultipartFile provides file size it is possible to check
// quota limit before reading the stream
if (remainingQuota != null && file != null && file.getSize() > remainingQuota) {
throw new QuotaExceededException("Path: " + fileInfo.getVirtualPath());
}
if (file != null) {
fileInfo.setContentType(file.getContentType());
}
fileInfo.setContentEncoding(contentEncoding);
try (InputStream in = file != null ? file.getInputStream() : request.getInputStream()) {
putFileService.storeFileFromInputStream(fileInfo, in, remainingQuota);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
} finally {
fileDAO.setBusy(path, null);
}
} else {
throw new NodeNotFoundException(path);
}
}, jobId);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/ 0000775 0000000 0000000 00000000000 14341627633 0027203 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/DataSourcesConfig.java 0000664 0000000 0000000 00000001276 14341627633 0033417 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DataSourcesConfig {
@Bean
@ConfigurationProperties(prefix = "file-catalog.datasource")
public DataSource fileCatalogDataSource() {
return DataSourceBuilder.create().build();
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/FileDAO.java 0000664 0000000 0000000 00000031464 14341627633 0031261 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import java.nio.file.Path;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class FileDAO {
private static final Logger LOG = LoggerFactory.getLogger(FileDAO.class);
@Value("${upload_location_id}")
private int uploadLocationId;
private final JdbcTemplate jdbcTemplate;
@Autowired
public FileDAO(DataSource fileCatalogDatasource) {
this.jdbcTemplate = new JdbcTemplate(fileCatalogDatasource);
}
public Optional getFileInfo(String virtualPath) {
String sql = "SELECT n.node_id, is_public, group_read, group_write, creator_id, async_trans,\n"
+ "content_type, content_encoding, content_length, content_md5, name, n.location_id,\n"
+ "accept_views, provide_views, l.location_type,\n"
+ "(SELECT user_name FROM users WHERE user_id = creator_id) AS username, n.job_id,\n"
+ "base_path, ? AS vos_path, false AS is_directory,\n"
+ "n.type = 'link' AS is_link, n.target,\n"
+ "fs_path \n"
+ "FROM node n\n"
+ "JOIN location l ON (n.location_id IS NOT NULL AND n.location_id = l.location_id) OR (n.location_id IS NULL AND l.location_id = ?)\n"
+ "LEFT JOIN storage s ON s.storage_id = l.storage_dest_id\n"
+ "WHERE n.node_id = id_from_vos_path(?)";
FileInfo fileInfo = jdbcTemplate.query(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, virtualPath);
ps.setInt(2, uploadLocationId);
ps.setString(3, virtualPath);
return ps;
}, rs -> {
if (rs.next()) {
return getFileInfo(rs);
}
return null;
});
return Optional.ofNullable(fileInfo);
}
private List toList(Array array) throws SQLException {
if (array == null) {
return new ArrayList<>();
}
return Arrays.asList((String[]) array.getArray());
}
public int setBusy(String vosPath, String jobId) {
String sql = "UPDATE node SET job_id = ? WHERE node_id = id_from_vos_path(?)";
int nodes = jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
if (jobId == null) {
ps.setNull(1, Types.VARCHAR);
} else {
ps.setString(1, jobId);
}
ps.setString(2, vosPath);
return ps;
});
if (nodes > 1) {
// This should never happen thanks to database constraints
throw new IllegalStateException("More than one node at path: " + vosPath);
}
return nodes;
}
public void setOsName(int nodeId, String newName) {
String sql = "UPDATE node SET os_name = ? WHERE node_id = ?";
jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, newName);
ps.setInt(2, nodeId);
return ps;
});
}
public void updateFileAttributes(int nodeId,
String fsPath,
String contentType,
String contentEncoding,
Long contentLength,
String contentMd5) {
String sql = "UPDATE node SET fs_path = ?, content_type = ?, content_encoding = ?, content_length = ?, content_md5 = ?, location_id = ? "
+ "WHERE node_id = ?";
jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
int i = 0;
ps.setString(++i, fsPath);
ps.setString(++i, contentType);
ps.setString(++i, contentEncoding);
ps.setLong(++i, contentLength);
ps.setString(++i, contentMd5);
ps.setInt(++i, uploadLocationId);
ps.setInt(++i, nodeId);
return ps;
});
}
public Long getRemainingQuota(String parentVosPath) {
String sql = "WITH quota_info AS (\n"
+ " SELECT p.quota, get_vos_path(p.node_id) AS parent_vos_path\n"
+ " FROM node p\n"
+ " JOIN node n ON p.path @> n.path\n"
+ " WHERE n.node_id = id_from_vos_path(?) AND p.quota IS NOT NULL\n"
+ " ORDER BY nlevel(p.path) DESC LIMIT 1\n"
+ ")\n"
+ "SELECT AVG(qi.quota)::bigint - SUM(c.content_length) AS remaining_quota\n"
+ "FROM node c\n"
+ "JOIN node n ON n.path @> c.path\n"
+ "JOIN quota_info qi ON n.node_id = id_from_vos_path(qi.parent_vos_path)\n"
+ "WHERE c.type <> 'container'";
return jdbcTemplate.query(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, parentVosPath);
return ps;
}, rs -> {
if (rs.next()) {
long remainingQuota = rs.getLong(1);
if (!rs.wasNull()) {
return remainingQuota;
}
}
LOG.warn("Quota not defined for path {}", parentVosPath);
return null;
});
}
// TODO: set maximum list size or use stream to avoid memory issues
public List getArchiveFileInfos(List vosPaths) {
if (vosPaths.isEmpty()) {
throw new IllegalArgumentException("Received empty list of paths");
}
String sql = "SELECT n.node_id, n.is_public, n.group_read, n.group_write, n.creator_id, n.async_trans, n.fs_path,\n"
+ "n.content_type, n.content_encoding, n.content_length, n.content_md5,\n"
+ "n.accept_views, n.provide_views, l.location_type,\n"
+ "(SELECT user_name FROM users WHERE user_id = n.creator_id) AS username,\n"
+ "base_path, get_vos_path(n.node_id) AS vos_path,\n"
+ "n.type = 'container' AS is_directory, n.name, n.location_id, n.job_id,\n"
+ "n.type = 'link' AS is_link, n.target, l.location_type\n"
+ "FROM node n\n"
+ "JOIN node p ON p.path @> n.path\n"
+ "LEFT JOIN location l ON l.location_id = n.location_id\n"
+ "LEFT JOIN storage s ON s.storage_id = l.storage_dest_id\n"
+ "WHERE " + String.join(" OR ", Collections.nCopies(vosPaths.size(), "p.node_id = id_from_vos_path(?)"))
+ "\nORDER BY vos_path ASC";
return jdbcTemplate.query(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
int i = 0;
for (String vosPath : vosPaths) {
ps.setString(++i, vosPath);
}
return ps;
}, rs -> {
List fileInfos = new ArrayList<>();
while (rs.next()) {
fileInfos.add(getFileInfo(rs));
}
return fileInfos;
});
}
// TODO: same problem as get archive file infos
public List getBranchFileInfos(String rootVosPath, String jobId) {
String sql = "SELECT n.node_id, n.is_public, n.group_read, n.group_write, n.creator_id, n.async_trans, n.fs_path,\n"
+ "n.content_type, n.content_encoding, n.content_length, n.content_md5,\n"
+ "n.accept_views, n.provide_views, l.location_type,\n"
+ "(SELECT user_name FROM users WHERE user_id = n.creator_id) AS username,\n"
+ "base_path, get_vos_path(n.node_id) AS vos_path,\n"
+ "n.type = 'container' AS is_directory, n.name, n.location_id, n.job_id,\n"
+ "n.type = 'link' AS is_link, n.target, l.location_type\n"
+ "FROM node n\n"
+ "JOIN node p ON p.path @> n.path\n"
+ "LEFT JOIN location l ON l.location_id = n.location_id\n"
+ "LEFT JOIN storage s ON s.storage_id = l.storage_dest_id\n"
+ "WHERE (p.node_id = id_from_vos_path(?) AND n.job_id = ?)\n"
+ "ORDER BY vos_path ASC\n";
return jdbcTemplate.query(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, rootVosPath);
ps.setString(2, jobId);
return ps;
}, rs -> {
List fileInfos = new ArrayList<>();
while (rs.next()) {
fileInfos.add(getFileInfo(rs));
}
return fileInfos;
});
}
public void setBranchLocationId(String rootVosPath, String jobId, int locationId) {
String cte = "SELECT n.node_id AS id\n"
+ "FROM node n\n"
+ "JOIN node p ON p.path @> n.path\n"
+ "WHERE (p.node_id = id_from_vos_path(?) AND n.job_id = ?)\n";
String update = "UPDATE node\n"
+ " SET location_id = ?\n"
+ "FROM cte\n"
+ "WHERE node_id = cte.id\n";
String sql = "WITH cte AS (\n"
+ cte
+ ")\n"
+ update;
jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, rootVosPath);
ps.setString(2, jobId);
ps.setInt(3, locationId);
return ps;
});
}
// !! duplicate code from NodeDAO
public void releaseBusyNodesByJobId(String jobId) {
String sql = "UPDATE node SET job_id = NULL WHERE job_id = ?";
jdbcTemplate.update(conn -> {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, jobId);
return ps;
});
}
private FileInfo getFileInfo(ResultSet rs) throws SQLException {
FileInfo fi = new FileInfo();
fi.setNodeId(rs.getInt("node_id"));
fi.setPublic(rs.getBoolean("is_public"));
fi.setGroupRead(toList(rs.getArray("group_read")));
fi.setGroupWrite(toList(rs.getArray("group_write")));
fi.setOwnerId(rs.getString("creator_id"));
fi.setAsyncTrans(rs.getBoolean("async_trans"));
fi.setAcceptViews(toList(rs.getArray("accept_views")));
fi.setProvideViews(toList(rs.getArray("provide_views")));
fi.setVirtualPath(rs.getString("vos_path"));
fi.setVirtualName(rs.getString("name"));
fi.setContentEncoding(rs.getString("content_encoding"));
long contentLength = rs.getLong("content_length");
if (!rs.wasNull()) {
fi.setContentLength(contentLength);
}
fi.setContentMd5(rs.getString("content_md5"));
fi.setContentType(rs.getString("content_type"));
fi.setDirectory(rs.getBoolean("is_directory"));
if(rs.getBoolean("is_link")){
fi.setLink(true);
fi.setTarget(rs.getString("target"));
} else {
fi.setLink(false);
}
fi.setJobId(rs.getString("job_id"));
int locationId = rs.getInt("location_id");
if (!rs.wasNull()) {
fi.setLocationId(locationId);
fi.setLocationType(rs.getString("location_type"));
}
this.fillActualBasePath(fi, rs);
this.fillFsPath(fi, rs);
return fi;
}
private void fillActualBasePath(FileInfo fi, ResultSet rs) throws SQLException {
String basePath = rs.getString("base_path");
if (basePath == null) {
return;
}
Path completeBasePath = Path.of(basePath);
boolean asyncLocation = "async".equals(rs.getString("location_type"));
if (asyncLocation) {
String username = rs.getString("username");
completeBasePath = completeBasePath.resolve(username).resolve("vospace_retrieve");
}
fi.setActualBasePath(completeBasePath.toString());
}
private void fillFsPath(FileInfo fi, ResultSet rs) throws SQLException {
String fsPath = rs.getString("fs_path");
if (fsPath == null) {
return;
}
if (fsPath.startsWith("/")) {
fsPath = fsPath.substring(1);
}
Path completeFsPath = Path.of(fsPath);
fi.setFsPath(completeFsPath.toString());
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/JobDAO.java 0000664 0000000 0000000 00000005101 14341627633 0031101 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import it.inaf.oats.vospace.exception.VoSpaceErrorSummarizableException;
import java.sql.Types;
import javax.sql.DataSource;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class JobDAO {
private final JdbcTemplate jdbcTemplate;
@Autowired
public JobDAO(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public boolean isJobExisting(String jobId) {
String sql = "SELECT * FROM job WHERE job_id = ?";
boolean result = jdbcTemplate.query(sql,
ps -> {
ps.setString(1, jobId);
}, rs -> {
return rs.next();
});
return result;
}
public void updateJobPhase(ExecutionPhase phase, String jobId) {
String sql = "UPDATE job SET phase = ? WHERE job_id = ?";
jdbcTemplate.update(sql, ps -> {
ps.setObject(1, phase, Types.OTHER);
ps.setString(2, jobId);
});
}
public ExecutionPhase getJobPhase(String jobId) {
String sql = "SELECT phase FROM job WHERE job_id = ?";
ExecutionPhase result = jdbcTemplate.query(sql,
ps -> {
ps.setString(1, jobId);
}, rs -> {
if (rs.next()) {
return ExecutionPhase.fromValue(rs.getString("phase"));
} else {
return null;
}
});
return result;
}
public void setJobError(String jobId, VoSpaceErrorSummarizableException jobError) {
String sql = "UPDATE job SET phase = ?, error_message = ?, error_type = ?,\n"
+ "error_has_detail = ?, error_detail = ?, end_time = NOW()\n"
+ "WHERE job_id = ?";
jdbcTemplate.update(sql, ps -> {
int i = 0;
ps.setObject(++i, ExecutionPhase.ERROR, Types.OTHER);
ps.setString(++i, jobError.getMessage());
ps.setObject(++i, jobError.getFault().getType().value(), Types.OTHER);
ps.setBoolean(++i, jobError.getDetailMessage() != null);
ps.setString(++i, jobError.getDetailMessage());
ps.setString(++i, jobId);
});
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/model/ 0000775 0000000 0000000 00000000000 14341627633 0030303 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/persistence/model/FileInfo.java 0000664 0000000 0000000 00000012153 14341627633 0032643 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence.model;
import java.nio.file.Path;
import java.util.List;
public class FileInfo {
private int nodeId;
private String virtualPath;
private String virtualName;
private String fsPath;
// actualBasePath differs from base path in db due to some location type
// dependent manipulations (performed by FileDAO)
private String actualBasePath;
private boolean isPublic;
private boolean directory;
private boolean link;
private String target;
private List groupRead;
private List groupWrite;
private String ownerId;
private boolean asyncTrans;
private List acceptViews;
private List provideViews;
private String contentType;
private String contentEncoding;
private Long contentLength;
private String contentMd5;
private Integer locationId;
private String locationType;
private String jobId;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public int getNodeId() {
return nodeId;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentEncoding() {
return contentEncoding;
}
public void setContentEncoding(String contentEncoding) {
this.contentEncoding = contentEncoding;
}
public Long getContentLength() {
return contentLength;
}
public void setContentLength(Long contentLength) {
this.contentLength = contentLength;
}
public String getContentMd5() {
return contentMd5;
}
public void setContentMd5(String contentMd5) {
this.contentMd5 = contentMd5;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public String getVirtualPath() {
return virtualPath;
}
public void setVirtualPath(String virtualPath) {
this.virtualPath = virtualPath;
}
public String getVirtualName() {
return virtualName;
}
public void setVirtualName(String virtualName) {
this.virtualName = virtualName;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean isPublic) {
this.isPublic = isPublic;
}
public boolean isDirectory() {
return directory;
}
public void setDirectory(boolean directory) {
this.directory = directory;
}
public boolean isLink() {
return link;
}
public void setLink(boolean link) {
this.link = link;
}
public List getGroupRead() {
return groupRead;
}
public void setGroupRead(List groupRead) {
this.groupRead = groupRead;
}
public List getGroupWrite() {
return groupWrite;
}
public void setGroupWrite(List groupWrite) {
this.groupWrite = groupWrite;
}
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public boolean isAsyncTrans() {
return asyncTrans;
}
public void setAsyncTrans(boolean asyncTrans) {
this.asyncTrans = asyncTrans;
}
public List getAcceptViews() {
return acceptViews;
}
public void setAcceptViews(List acceptViews) {
this.acceptViews = acceptViews;
}
public List getProvideViews() {
return provideViews;
}
public void setProvideViews(List provideViews) {
this.provideViews = provideViews;
}
public Integer getLocationId() {
return locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
public String getLocationType() {
return locationType;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getFsPath() {
return fsPath;
}
public void setFsPath(String fsPath) {
this.fsPath = fsPath;
}
public String getActualBasePath() {
return actualBasePath;
}
public void setActualBasePath(String actualBasePath) {
this.actualBasePath = actualBasePath;
}
// This function returns the full path of this file on storage
public String getFilePath() {
if (this.actualBasePath == null || this.fsPath == null) {
return null;
} else {
return Path.of(this.actualBasePath).resolve(this.fsPath).toString();
}
}
public static String getVosParentPath(FileInfo fileInfo) {
return fileInfo.getVirtualPath().substring(0, fileInfo.getVirtualPath().lastIndexOf("/"));
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/ 0000775 0000000 0000000 00000000000 14341627633 0026317 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/ArchiveJob.java 0000664 0000000 0000000 00000003120 14341627633 0031172 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.oats.vospace.parent.exchange.ArchiveEntryDescriptor;
import java.util.List;
public class ArchiveJob {
public static enum Type {
TAR,
ZIP;
public String getExtension() {
switch (this) {
case TAR:
return "tar";
case ZIP:
return "zip";
default:
throw new IllegalArgumentException("Extension not defined for type " + this);
}
}
}
private List entryDescriptors;
private TokenPrincipal tokenPrincipal;
private String jobId;
private Type type;
public List getEntryDescriptors() {
return entryDescriptors;
}
public void setEntryDescriptors(List entryDescriptors) {
this.entryDescriptors = entryDescriptors;
}
public TokenPrincipal getPrincipal() {
return tokenPrincipal;
}
public void setPrincipal(TokenPrincipal tokenPrincipal) {
this.tokenPrincipal = tokenPrincipal;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/ArchiveService.java 0000664 0000000 0000000 00000037531 14341627633 0032075 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.aa.ServletRapClient;
import it.inaf.ia2.rap.client.call.TokenExchangeRequest;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.oats.vospace.datamodel.NodeUtils;
import it.inaf.oats.vospace.exception.InternalFaultException;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import it.inaf.oats.vospace.parent.exchange.ArchiveEntryDescriptor;
import it.inaf.oats.vospace.parent.persistence.LinkedServiceDAO;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.kamranzafar.jtar.TarEntry;
import org.kamranzafar.jtar.TarOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.unit.DataSize;
import org.springframework.web.client.RestTemplate;
@Service
public class ArchiveService {
private static final Logger LOG = LoggerFactory.getLogger(ArchiveService.class);
@Autowired
private FileDAO fileDAO;
@Autowired
private LinkedServiceDAO linkedServiceDAO;
@Autowired
private JobDAO jobDAO;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private ServletRapClient rapClient;
// Directory containing temporary files generated by jobs.
@Value("${generated.dir}")
private String generatedDirString;
private File generatedDir;
// Maximum size of the working directory for each registered user
@Value("${generated.dir.max-size}")
private DataSize generatedDirMaxSize;
@PostConstruct
public void init() {
this.generatedDir = new File(generatedDirString);
if (!this.generatedDir.exists()) {
if (!this.generatedDir.mkdirs()) {
throw new IllegalStateException("Unable to create directory " + this.generatedDir.getAbsolutePath());
}
}
}
public void createArchive(ArchiveJob job, HttpServletRequest servletRequest) {
jobDAO.updateJobPhase(ExecutionPhase.EXECUTING, job.getJobId());
LOG.trace("Started archive job " + job.getJobId());
try {
// TODO: check total size limit
File archiveFile = getArchiveFile(job);
List entryDescriptors = job.getEntryDescriptors();
// support directory used to generate folder inside tar files (path is redefined each time by TarEntry class)
File supportDir = Files.createTempDirectory("dir").toFile();
try (ArchiveHandler handler = getArchiveHandler(archiveFile, job.getType())) {
fillArchive(entryDescriptors, supportDir,
job.getPrincipal(), servletRequest, handler);
} finally {
FileSystemUtils.deleteRecursively(supportDir);
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private void fillArchive(
List entryDescriptors,
File supportDir, TokenPrincipal tokenPrincipal,
HttpServletRequest servletRequest, ArchiveHandler handler) throws IOException {
List noTargetEntryDescriptors
= entryDescriptors.stream().filter(ed -> !ed.isPointingToAnotherNode())
.collect(Collectors.toList());
// Start with archive entry descriptors which don't point to another node
List vosPaths = noTargetEntryDescriptors.stream()
.map(ed -> ed.getVosPath())
.collect(Collectors.toList());
String commonParent = getCommonParent(entryDescriptors);
if (!vosPaths.isEmpty()) {
for (FileInfo fileInfo : fileDAO.getArchiveFileInfos(vosPaths)) {
String relPath = fileInfo.getVirtualPath().substring(commonParent.length());
this.insertEntryIntoArchive(fileInfo, supportDir, relPath, tokenPrincipal, servletRequest, handler);
}
}
List pointingEntryDescriptors
= entryDescriptors.stream().filter(ed -> ed.isPointingToAnotherNode())
.collect(Collectors.toList());
// Now archive entry descriptors pointing to another node
List targetNodesVosPaths = pointingEntryDescriptors.stream()
.map(ed -> ed.getTargetNodeVosPath())
.collect(Collectors.toList());
if (!targetNodesVosPaths.isEmpty()) {
for (FileInfo fileInfo : fileDAO.getArchiveFileInfos(targetNodesVosPaths)) {
// relPaths is calculated from base node
String targetNodeVosPath = fileInfo.getVirtualPath();
List linkVosPaths = pointingEntryDescriptors.stream()
.filter(ed -> ed.getTargetNodeVosPath().equals(targetNodeVosPath))
.map(ed -> ed.getVosPath())
.collect(Collectors.toList());
for (String vosPath : linkVosPaths) {
String relPath = vosPath.substring(commonParent.length());
this.insertEntryIntoArchive(fileInfo, supportDir, relPath, tokenPrincipal, servletRequest, handler);
}
}
}
}
private void insertEntryIntoArchive(
FileInfo fileInfo, File supportDir, String relPath,
TokenPrincipal tokenPrincipal, HttpServletRequest servletRequest, ArchiveHandler handler)
throws IOException {
if (fileInfo.isDirectory()) {
handler.putNextEntry(supportDir, relPath);
return;
}
// I retrieve only external links
// local links have been resolved before calling this endpoint
// TODO: we need to discuss about internal links in container nodes
if (fileInfo.isLink()) {
String target = fileInfo.getTarget();
if (!target.startsWith("vos://")) {
downloadExternalLinkIntoArchive(fileInfo, relPath,
tokenPrincipal, handler, servletRequest);
}
return;
}
writeFileIntoArchive(fileInfo, relPath, tokenPrincipal, handler);
}
private File getArchiveFile(ArchiveJob job) throws IOException {
File parentDir = getArchiveParentDir(job.getPrincipal());
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
LOG.error("Unable to create directory " + parentDir.getAbsolutePath());
throw new InternalFaultException("Unable to create temporary directory for job");
}
}
checkQuotaLimit(parentDir);
File archiveFile = parentDir.toPath().resolve(job.getJobId() + "." + job.getType().getExtension()).toFile();
if (!archiveFile.createNewFile()) {
LOG.error("Unable to create file " + archiveFile.getAbsolutePath());
throw new InternalFaultException("Unable to create archive file");
}
return archiveFile;
}
/**
* If used working space exceeds quota limit throws an
* InsufficientStorageException.
*/
private void checkQuotaLimit(File parentDir) throws IOException {
long usedSpace = Files.walk(parentDir.toPath()).mapToLong(p -> p.toFile().length()).sum();
if (usedSpace > generatedDirMaxSize.toBytes()) {
throw new QuotaExceededException("Archive size limit exceeded.");
}
}
public File getArchiveParentDir(Principal principal) {
return generatedDir.toPath().resolve(principal.getName()).toFile();
}
private String getCommonParent(List entryDescriptors) {
if(entryDescriptors.isEmpty()) {
throw new IllegalArgumentException("Empty descriptors list");
} else if(entryDescriptors.size() == 1) {
return NodeUtils.getParentPath(entryDescriptors.get(0).getVosPath());
}
// Get list of parent paths
List vosParentPaths = entryDescriptors.stream().map(
ed -> NodeUtils.getParentPath(ed.getVosPath()).split("/"))
.collect(Collectors.toList());
// Get minimum size of split vosParentPaths arrays
int minSize = vosParentPaths.stream()
.mapToInt(v->v.length).min().orElseThrow();
switch(minSize) {
case 0:
return "/";
case 1:
// this should never happen
throw new IllegalArgumentException("Invalid vosPath");
}
StringBuilder sb = new StringBuilder();
for(int i = 1; i < minSize; i++) {
List elements = new ArrayList<>();
for(String[] s : vosParentPaths) {
elements.add(s[i]);
}
String sample = elements.get(0);
if(elements.stream().allMatch(e->e.equals(sample)))
sb.append("/").append(sample);
}
return sb.toString();
}
private abstract class ArchiveHandler implements AutoCloseable {
private final O os;
private final File parentDir;
ArchiveHandler(O os, File parentDir) {
this.os = os;
this.parentDir = parentDir;
}
public abstract E getEntry(File file, String path);
protected abstract void putNextEntry(E entry) throws IOException;
public final void putNextEntry(File file, String path) throws IOException {
putNextEntry(getEntry(file, path));
checkQuotaLimit(parentDir);
}
public final O getOutputStream() {
return os;
}
@Override
public void close() throws IOException {
os.close();
}
}
private class TarArchiveHandler extends ArchiveHandler {
TarArchiveHandler(File archiveFile) throws IOException {
super(new TarOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile))), archiveFile.getParentFile());
}
@Override
public TarEntry getEntry(File file, String path) {
return new TarEntry(file, path);
}
@Override
public void putNextEntry(TarEntry entry) throws IOException {
getOutputStream().putNextEntry(entry);
}
}
private class ZipArchiveHandler extends ArchiveHandler {
ZipArchiveHandler(File archiveFile) throws IOException {
super(new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile))), archiveFile.getParentFile());
}
@Override
public ZipEntry getEntry(File file, String path) {
if (file.isDirectory()) {
// ZipEntry assumes that paths ending with / are folders
path += "/";
}
return new ZipEntry(path);
}
@Override
public void putNextEntry(ZipEntry entry) throws IOException {
getOutputStream().putNextEntry(entry);
}
}
private ArchiveHandler getArchiveHandler(File archiveFile, ArchiveJob.Type type) throws IOException {
switch (type) {
case TAR:
return new TarArchiveHandler(archiveFile);
case ZIP:
return new ZipArchiveHandler(archiveFile);
default:
throw new UnsupportedOperationException("Type " + type + " not supported yet");
}
}
private void downloadFromUrlIntoArchive(String url, String relPath, TokenPrincipal tokenPrincipal, ArchiveHandler handler) {
LOG.trace("Downloading file from " + url);
restTemplate.execute(url, HttpMethod.GET, req -> {
HttpHeaders headers = req.getHeaders();
if (tokenPrincipal.getToken() != null) {
headers.setBearerAuth(tokenPrincipal.getToken());
}
}, res -> {
File tmpFile = Files.createTempFile("download", null).toFile();
try (FileOutputStream os = new FileOutputStream(tmpFile)) {
res.getBody().transferTo(os);
handler.putNextEntry(tmpFile, relPath);
try (FileInputStream is = new FileInputStream(tmpFile)) {
is.transferTo(handler.getOutputStream());
}
} finally {
tmpFile.delete();
}
return null;
}, new Object[]{});
}
private void downloadExternalLinkIntoArchive(
FileInfo fileInfo, String relPath, TokenPrincipal tokenPrincipal,
ArchiveHandler handler, HttpServletRequest servletRequest) {
String url = fileInfo.getTarget();
if (url == null || url.isBlank()) {
LOG.error("Target URL of link at path: {} is null or blank", fileInfo.getVirtualPath());
throw new InternalFaultException("Target URL of link at path: "
+ fileInfo.getVirtualPath() + " is null or blank");
}
// Append token if url is recognized
if (linkedServiceDAO.isLinkedServiceUrl(url)) {
url += "?token=" + getEndpointToken(tokenPrincipal, url, servletRequest);
}
downloadFromUrlIntoArchive(url, relPath, tokenPrincipal, handler);
}
private void writeFileIntoArchive(FileInfo fileInfo, String relPath, TokenPrincipal tokenPrincipal, ArchiveHandler handler) throws IOException {
if (!authorizationService.isDownloadable(fileInfo, tokenPrincipal)) {
throw PermissionDeniedException.forPath(fileInfo.getVirtualPath());
}
File file = new File(fileInfo.getFilePath());
LOG.trace("Adding file " + file.getAbsolutePath() + " to tar archive");
try (InputStream is = new FileInputStream(file)) {
handler.putNextEntry(file, relPath);
is.transferTo(handler.getOutputStream());
}
}
private String getEndpointToken(TokenPrincipal tokenPrincipal,
String endpoint, HttpServletRequest servletRequest) {
String token = tokenPrincipal.getToken();
if (token == null) {
throw new PermissionDeniedException("Token is null");
}
TokenExchangeRequest exchangeRequest = new TokenExchangeRequest()
.setSubjectToken(token)
.setResource(endpoint);
// TODO: add audience and scope
return rapClient.exchangeToken(exchangeRequest, servletRequest);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/AuthorizationService.java 0000664 0000000 0000000 00000002304 14341627633 0033342 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.GmsClient;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AuthorizationService {
@Autowired
private GmsClient gmsClient;
public boolean isDownloadable(FileInfo fileInfo, TokenPrincipal principal) {
if (fileInfo.isPublic()) {
return true;
}
String token = principal.getToken();
if (token == null) {
return false;
}
if (principal.getName().equals(fileInfo.getOwnerId())) {
return true;
}
// TODO: configure cache
if (fileInfo.getGroupRead() == null) {
return false;
}
for (String group : fileInfo.getGroupRead()) {
if (gmsClient.isMemberOf(token, group)) {
return true;
}
}
return false;
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/FileCopyService.java 0000664 0000000 0000000 00000013663 14341627633 0032226 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.oats.vospace.exception.NodeNotFoundException;
import it.inaf.oats.vospace.exception.PermissionDeniedException;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import java.io.File;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class FileCopyService {
private static final Logger LOG = LoggerFactory.getLogger(FileCopyService.class);
@Autowired
private FileDAO fileDAO;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private PutFileService putFileService;
@Value("${upload_location_id}")
private int uploadLocationId;
public void copyFiles(String sourceRootVosPath,
String destinationRootVosPath, String jobId, TokenPrincipal principal) {
LOG.trace("copyFiles called for source {}, destination {}, from jobId \"{}\"",
sourceRootVosPath, destinationRootVosPath, jobId);
// We use jobId to identify nodes created by the REST part of CopyNode
// We expect them to be locked
List sources
= fileDAO.getBranchFileInfos(sourceRootVosPath, jobId);
LOG.debug("found {} sources", sources.size());
if (sources.isEmpty()) {
throw new NodeNotFoundException(sourceRootVosPath);
}
// Set location of destinations to this file service update location
// before retrieving file infos
fileDAO.setBranchLocationId(destinationRootVosPath, jobId, uploadLocationId);
List destinations
= fileDAO.getBranchFileInfos(destinationRootVosPath, jobId);
LOG.debug("found {} destinations", destinations.size());
if (destinations.isEmpty()) {
throw new NodeNotFoundException(destinationRootVosPath);
}
if (sources.size() != destinations.size()) {
throw new IllegalStateException("Sources and destinations list have different sizes");
}
// Create destination directories on disk
//this.makeDirectoryStructure(destinations);
this.fillDestinations(sources,
destinations,
sourceRootVosPath,
destinationRootVosPath,
principal);
}
private void fillDestinations(List sourcesFileInfos,
List destinationFileInfos,
String sourceRootVosPath,
String destinationRootVosPath,
TokenPrincipal principal) {
for (FileInfo destinationFileInfo : destinationFileInfos) {
LOG.trace("Processing {} destination", destinationFileInfo.getVirtualPath());
// Cycle on files only
if (!destinationFileInfo.isDirectory() && !destinationFileInfo.isLink()) {
// Calculate source file vos path
String correspondingSourceVosPath
= this.getCorrespondingSourceVosPath(sourceRootVosPath,
destinationRootVosPath,
destinationFileInfo.getVirtualPath());
// Get source fileInfo corresponding to this destination
Optional sourceOpt = this.findFileInfoByVosPath(sourcesFileInfos,
correspondingSourceVosPath);
FileInfo sourceFileInfo = sourceOpt
.orElseThrow(() -> new IllegalStateException("Can't find file info for: "
+ correspondingSourceVosPath + " in source files list"));
// Get remaining quota for precheck
String parentPath = FileInfo.getVosParentPath(destinationFileInfo);
Long remainingQuota = fileDAO.getRemainingQuota(parentPath);
// Compare to source fileInfo content length
if (remainingQuota != null) {
Long sourceSize = sourceFileInfo.getContentLength();
if (sourceSize != null && remainingQuota < sourceSize) {
throw new QuotaExceededException("Path: " + destinationFileInfo.getVirtualPath());
}
}
this.copyLocalFile(sourceFileInfo, destinationFileInfo, principal, remainingQuota);
}
}
}
private String getCorrespondingSourceVosPath(String sourceRootVosPath,
String destinationRootVosPath,
String destinationVosPath) {
return sourceRootVosPath
+ destinationVosPath.substring(destinationRootVosPath.length());
}
private Optional findFileInfoByVosPath(List list, String vosPath) {
return list.stream().filter(i -> i.getVirtualPath().equals(vosPath)).findFirst();
}
private void copyLocalFile(FileInfo sourceFileInfo,
FileInfo destinationFileInfo, TokenPrincipal tokenPrincipal, Long remainingQuota) {
// Check permission
if (!authorizationService.isDownloadable(sourceFileInfo, tokenPrincipal)) {
throw PermissionDeniedException.forPath(sourceFileInfo.getVirtualPath());
}
File file = new File(sourceFileInfo.getFilePath());
LOG.trace("Copying file: {} to {}", file.getAbsolutePath(), destinationFileInfo.getFilePath());
putFileService.copyLocalFile(sourceFileInfo, destinationFileInfo, remainingQuota);
}
}
vospace-file-service-master/src/main/java/it/inaf/ia2/transfer/service/PutFileService.java 0000664 0000000 0000000 00000024306 14341627633 0032060 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.oats.vospace.exception.InvalidArgumentException;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.DatatypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class PutFileService {
private static final Logger LOG = LoggerFactory.getLogger(PutFileService.class);
@Autowired
private FileDAO fileDAO;
public synchronized void makeFoldersPath(File file) {
/**
* This method must be synchronized, to avoid concurrency issues when
* multiple files are uploaded to a new folder in parallel.
*/
if (!file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalStateException("Unable to create parent folder: " + file.getParentFile().getAbsolutePath());
}
}
}
public void copyLocalFile(FileInfo sourceFileInfo, FileInfo destinationFileInfo, Long remainingQuota) {
File destinationFile = this.prepareDestination(destinationFileInfo);
File sourceFile = new File(sourceFileInfo.getFilePath());
try {
Files.copy(sourceFile.toPath(), destinationFile.toPath());
this.finalizeFile(sourceFileInfo, destinationFileInfo, destinationFile, remainingQuota);
} catch (IOException e) {
destinationFile.delete();
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public void storeFileFromInputStream(FileInfo destinationFileInfo,
InputStream is, Long remainingQuota) {
this.storeFileFromInputStream(null, destinationFileInfo, is, remainingQuota);
}
public void storeFileFromInputStream(FileInfo sourceFileInfo, FileInfo destinationFileInfo,
InputStream is, Long remainingQuota) {
File destinationFile = this.prepareDestination(destinationFileInfo);
try {
Files.copy(is, destinationFile.toPath());
this.finalizeFile(sourceFileInfo, destinationFileInfo, destinationFile, remainingQuota);
} catch (IOException e) {
destinationFile.delete();
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
destinationFile.delete();
throw new RuntimeException(e);
}
}
private File prepareDestination(FileInfo destinationFileInfo) {
// TODO: this reproduces past behaviour, we need to confirm
// basePath null case and if we want to lock the node after
// the first upload (fsPath not null)
if(destinationFileInfo.getActualBasePath() != null) {
if(destinationFileInfo.getFsPath() != null) {
LOG.error("Node {} fsPath is not null: {}. Overwriting forbidden.",
destinationFileInfo.getVirtualPath(),
destinationFileInfo.getFsPath());
throw new InvalidArgumentException("Node " +
destinationFileInfo.getVirtualPath() +
" is already populated. Overwriting forbidden.");
}
destinationFileInfo.setFsPath(this.generateFsPath().toString());
}
File file = new File(destinationFileInfo.getFilePath());
makeFoldersPath(file);
// This is EXTREMELY unlikely to happen, but we want to be safe here
if(file.exists()) {
throw new IllegalStateException("Unexpected collision for generated file path: "
+ file.getPath());
}
return file;
}
private Long checkQuota(File destinationFile, Long remainingQuota) throws IOException {
Long fileSize = Files.size(destinationFile.toPath());
// Quota limit is checked again to handle cases where MultipartFile is not used
if (remainingQuota != null && fileSize > remainingQuota) {
destinationFile.delete();
throw new QuotaExceededException("Path: " + destinationFile.toPath().toString());
}
return fileSize;
}
private void finalizeFile(FileInfo sourceFileInfo, FileInfo destinationFileInfo,
File destinationFile, Long remainingQuota) throws IOException, NoSuchAlgorithmException {
Long fileSize = this.checkQuota(destinationFile, remainingQuota);
if (destinationFileInfo.getContentType() == null) {
destinationFileInfo.setContentType(Files.probeContentType(destinationFile.toPath()));
}
String md5Checksum = makeMD5Checksum(destinationFile);
// TODO: discuss if mismatches lead to taking actions
if (sourceFileInfo != null) {
if (!Objects.equals(sourceFileInfo.getContentLength(), fileSize)) {
LOG.warn("Destination file {} size mismatch with source", destinationFile.toPath().toString());
}
if (sourceFileInfo.getContentType() != null
&& !sourceFileInfo.getContentType().equals(destinationFileInfo.getContentType())) {
LOG.warn("Destination file {} content type mismatch with source {} {}", destinationFile.toPath().toString(),
destinationFileInfo.getContentType(), sourceFileInfo.getContentType());
}
if (sourceFileInfo.getContentMd5() != null
&& !sourceFileInfo.getContentMd5().equals(md5Checksum)) {
LOG.warn("Destination file {} md5 mismatch with source {} {}", destinationFile.toPath().toString(),
destinationFileInfo.getContentMd5(), sourceFileInfo.getContentMd5());
}
}
fileDAO.updateFileAttributes(destinationFileInfo.getNodeId(),
destinationFileInfo.getFsPath(),
destinationFileInfo.getContentType(),
destinationFileInfo.getContentEncoding(),
fileSize,
md5Checksum);
}
/**
* Handles duplicate file uploads generating a new non existent path. This
* is necessary in some edge cases, like when a file has been renamed in
* VOSpace only but the original file on disk still has the old name or if a
* file has been marked for deletion and a file with the same name is
* uploaded before the cleanup.
*/
private File getEmptyFile(File file, int index) {
if (file.exists()) {
String fileName = file.getName();
String nameWithoutExtension;
String extension = null;
if (fileName.contains(".")) {
nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf("."));
extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
} else {
nameWithoutExtension = fileName;
}
Pattern pattern = Pattern.compile("(.*?)-(\\d+)");
Matcher matcher = pattern.matcher(nameWithoutExtension);
if (matcher.matches()) {
nameWithoutExtension = matcher.group(1);
int fileIndex = Integer.parseInt(matcher.group(2));
index = fileIndex + 1;
}
String newName = nameWithoutExtension + "-" + index;
if (extension != null) {
newName += "." + extension;
}
File newFile = file.toPath().getParent().resolve(newName).toFile();
return getEmptyFile(newFile, index + 1);
}
return file;
}
private String makeMD5Checksum(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
// We can't update the MessageDigest object in a single step using
// Files.readAllBytes because we want to handle also big files and that
// method loads all the content in memory (OutOfMemoryError has been
// noticed for files bigger than 1GB). So multiple updates using
// FileChannel and ByteBuffer are used
try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ)) {
// creating buffer (by default it is in write mode). FileChannel will write into buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead;
while ((bytesRead = channel.read(buffer)) != -1) {
if (bytesRead > 0) {
// switch from write to read mode
buffer.flip();
md.update(buffer);
}
// using rewind the buffer can be filled again
buffer.rewind();
}
}
byte[] digest = md.digest();
String checksum = DatatypeConverter.printHexBinary(digest);
return checksum;
}
private Path generateFsPath() {
// Generate date and time part
LocalDateTime now = LocalDateTime.now();
Path fsPath = Path.of(Integer.toString(now.getYear()))
.resolve(Integer.toString(now.getMonthValue()))
.resolve(Integer.toString(now.getDayOfMonth()));
// Generate uuid for filename
UUID uuid = UUID.randomUUID();
fsPath = fsPath.resolve(uuid.toString());
return fsPath;
}
}
vospace-file-service-master/src/main/resources/ 0000775 0000000 0000000 00000000000 14341627633 0022120 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/main/resources/application.properties 0000664 0000000 0000000 00000001073 14341627633 0026542 0 ustar 00root root 0000000 0000000 server.port=8087
server.servlet.context-path=/
file-catalog.datasource.jdbc-url=jdbc:postgresql://127.0.0.1:5432/vospace_testdb
file-catalog.datasource.username=postgres
file-catalog.datasource.password=
generated.dir=/tmp/vospace/gen
generated.dir.max-size=10GB
gms_base_url=https://sso.ia2.inaf.it/gms
jwks_uri=https://sso.ia2.inaf.it/rap-ia2/auth/oidc/jwks
upload_location_id=3
cors.allowed.origin=http://localhost:8080,http://localhost:8085
spring.servlet.multipart.max-file-size=10GB
spring.servlet.multipart.max-request-size=10GB
logging.level.it.inaf=TRACE
vospace-file-service-master/src/main/resources/auth.properties 0000664 0000000 0000000 00000000225 14341627633 0025176 0 ustar 00root root 0000000 0000000 rap_uri=https://sso.ia2.inaf.it/rap-ia2
gms_uri=https://sso.ia2.inaf.it/gms/
groups_autoload=true
client_id=vospace_test
client_secret=***REMOVED***
vospace-file-service-master/src/test/ 0000775 0000000 0000000 00000000000 14341627633 0020141 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/ 0000775 0000000 0000000 00000000000 14341627633 0021062 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/ 0000775 0000000 0000000 00000000000 14341627633 0021476 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ 0000775 0000000 0000000 00000000000 14341627633 0022413 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/ 0000775 0000000 0000000 00000000000 14341627633 0023066 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/ 0000775 0000000 0000000 00000000000 14341627633 0024712 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/FileServiceApplicationTests.java 0000664 0000000 0000000 00000000572 14341627633 0033170 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FileServiceApplicationTests {
@Test
void contextLoads() {
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/auth/ 0000775 0000000 0000000 00000000000 14341627633 0025653 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/auth/GmsClientTest.java 0000664 0000000 0000000 00000003204 14341627633 0031242 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.auth;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
@ExtendWith(MockitoExtension.class)
public class GmsClientTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private GmsClient gmsClient;
@Test
public void testIsMemberOf() {
mockGmsResponse("group1\n");
assertTrue(gmsClient.isMemberOf("", "group1"));
}
@Test
public void testIsNotMemberOf() {
mockGmsResponse("");
assertFalse(gmsClient.isMemberOf("", "group1"));
}
private void mockGmsResponse(String body) {
ResponseEntity mockedResponse = mock(ResponseEntity.class);
when(mockedResponse.getBody()).thenReturn(body);
when(restTemplate.exchange(any(String.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))).thenReturn(mockedResponse);
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/controller/ 0000775 0000000 0000000 00000000000 14341627633 0027075 5 ustar 00root root 0000000 0000000 ArchiveFileControllerTest.java 0000664 0000000 0000000 00000011251 14341627633 0034746 0 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/controller /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.service.ArchiveJob;
import it.inaf.ia2.transfer.service.ArchiveService;
import it.inaf.oats.vospace.parent.exchange.ArchiveEntryDescriptor;
import java.io.File;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.util.FileSystemUtils;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
public class ArchiveFileControllerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@MockBean
private ArchiveService archiveService;
@Autowired
private MockMvc mockMvc;
@Test
public void testCreateTarArchive() throws Exception {
ArchiveRequest request = new ArchiveRequest();
request.setJobId("123");
request.setType("TAR");
request.setEntryDescriptors(List.of(this.getArchiveEntryDescriptor("/path/to/file1"),
this.getArchiveEntryDescriptor("/path/to/file2")));
mockMvc.perform(post("/archive")
.principal(fakePrincipal("user1"))
.contentType(MediaType.APPLICATION_JSON)
.content(MAPPER.writeValueAsString(request)))
.andDo(print())
.andExpect(status().is3xxRedirection());
verify(archiveService, times(1)).createArchive(argThat(job -> {
assertEquals("123", job.getJobId());
assertEquals(ArchiveJob.Type.TAR, job.getType());
assertEquals("user1", job.getPrincipal().getName());
assertEquals(2, job.getEntryDescriptors().size());
return true;
}), any());
}
@Test
public void testGetArchive() throws Exception {
File tmpDir = Files.createTempDirectory("tmp").toFile();
try {
tmpDir.toPath().resolve("123.zip").toFile().createNewFile();
when(archiveService.getArchiveParentDir(any())).thenReturn(tmpDir);
mockMvc.perform(get("/archive/123.zip")
.principal(fakePrincipal("user1")))
.andDo(print())
.andExpect(status().isOk());
} finally {
FileSystemUtils.deleteRecursively(tmpDir);
}
}
//@Test
public void testAnonymousCantCreateArchive() throws Exception {
ArchiveRequest request = new ArchiveRequest();
request.setJobId("123");
request.setType("ZIP");
request.setEntryDescriptors(List.of(this.getArchiveEntryDescriptor("/ignore")));
mockMvc.perform(post("/archive")
.principal(fakePrincipal("anonymous"))
.contentType(MediaType.APPLICATION_JSON)
.content(MAPPER.writeValueAsString(request)))
.andDo(print())
.andExpect(status().isForbidden());
}
public void testAnonymousCantGetArchive() throws Exception {
mockMvc.perform(get("/archive/123.zip")
.principal(fakePrincipal("anonymous")))
.andDo(print())
.andExpect(status().isForbidden());
}
private TokenPrincipal fakePrincipal(String name) {
TokenPrincipal principal = mock(TokenPrincipal.class);
when(principal.getName()).thenReturn(name);
return principal;
}
private ArchiveEntryDescriptor getArchiveEntryDescriptor(String vosPath) {
return new ArchiveEntryDescriptor(vosPath);
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/controller/CopyControllerTest.java 0000664 0000000 0000000 00000007001 14341627633 0033554 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.ia2.transfer.service.FileCopyService;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
public class CopyControllerTest {
@MockBean
private JobDAO jobDao;
@Autowired
private MockMvc mockMvc;
private static String jobId;
private static String sourceVosRootPath;
private static String destVosRootPath;
private static String filename;
private static final ObjectMapper MAPPER = new ObjectMapper();
@BeforeAll
public static void setUp() {
jobId = "pippo_copy";
filename = "file.txt";
sourceVosRootPath = "/source/" + filename;
destVosRootPath = "/destination/" + filename;
}
@Test
public void testCopyControllerNoJobMatching() throws Exception {
CopyRequest copyRequest = this.getCopyRequest(jobId,
sourceVosRootPath, destVosRootPath);
when(jobDao.isJobExisting(eq(jobId))).thenReturn(false);
mockMvc.perform(post("/copy")
.principal(fakePrincipal("user_copy"))
.contentType(MediaType.APPLICATION_JSON)
.content(MAPPER.writeValueAsString(copyRequest)))
.andDo(print())
.andExpect(status().is4xxClientError());
}
@Test
public void testCopyControllerAnonymousForbidden() throws Exception {
CopyRequest copyRequest = this.getCopyRequest(jobId,
sourceVosRootPath, destVosRootPath);
when(jobDao.isJobExisting(eq(jobId))).thenReturn(true);
mockMvc.perform(post("/copy")
.principal(fakePrincipal("anonymous"))
.contentType(MediaType.APPLICATION_JSON)
.content(MAPPER.writeValueAsString(copyRequest)))
.andDo(print())
.andExpect(status().is4xxClientError());
}
private CopyRequest getCopyRequest(String jobId,
String sourceRootVosPath, String destinationRootVosPath) {
CopyRequest result = new CopyRequest();
result.setJobId(jobId);
result.setSourceRootVosPath(sourceRootVosPath);
result.setDestinationRootVosPath(destinationRootVosPath);
return result;
}
private TokenPrincipal fakePrincipal(String name) {
TokenPrincipal principal = mock(TokenPrincipal.class);
when(principal.getName()).thenReturn(name);
return principal;
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/controller/GetFileControllerTest.java0000664 0000000 0000000 00000020340 14341627633 0034162 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.ia2.aa.jwt.TokenParser;
import it.inaf.ia2.transfer.auth.GmsClient;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.oats.vospace.exception.VoSpaceErrorSummarizableException;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.assertj.core.util.Files;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class GetFileControllerTest {
@MockBean
private TokenParser tokenParser;
@MockBean
private GmsClient gmsClient;
@MockBean
private FileDAO fileDao;
@MockBean
private JobDAO jobDAO;
@Autowired
private MockMvc mockMvc;
private File tempFile;
@BeforeEach
public void init() {
tempFile = Files.newTemporaryFile();
}
@AfterEach
public void cleanup() {
tempFile.delete();
}
@Test
public void getPublicFile() throws Exception {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(tempFile.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setPublic(true);
when(fileDao.getFileInfo(eq("/path/to/myfile"))).thenReturn(Optional.of(fileInfo));
mockMvc.perform(get("/path/to/myfile"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testContextPathIsRemoved() throws Exception {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(tempFile.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setPublic(true);
when(fileDao.getFileInfo(eq("/path/to/myfile"))).thenReturn(Optional.of(fileInfo));
mockMvc.perform(get("/context/path/to/myfile").contextPath("/context"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testFileNotFoundInDb() throws Exception {
mockMvc.perform(get("/path/to/myfile"))
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
public void testFileNotFoundOnDisk() throws Exception {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath("/this/doesnt/exist");
fileInfo.setPublic(true);
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
mockMvc.perform(get("/myfile"))
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
public void getPrivateFileTokenInHeader() throws Exception {
prepareMocksForPrivateFile();
mockMvc.perform(get("/path/to/myfile")
.header("Authorization", "Bearer: "))
.andDo(print())
.andExpect(status().isOk());
verify(gmsClient).isMemberOf(eq(""), eq("group1"));
}
@Test
public void getPrivateFileTokenInQueryString() throws Exception {
prepareMocksForPrivateFile();
mockMvc.perform(get("/path/to/myfile?token="))
.andDo(print())
.andExpect(status().isOk());
verify(gmsClient).isMemberOf(eq(""), eq("group1"));
}
@Test
public void getPrivateFileByOwnerId() throws Exception {
Map claims = new HashMap<>();
claims.put("sub", "123");
when(tokenParser.getClaims(any())).thenReturn(claims);
FileInfo fileInfo = new FileInfo();
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(tempFile.getAbsolutePath());
fileInfo.setOwnerId("123");
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
mockMvc.perform(get("/path/to/myfile")
.header("Authorization", "Bearer: "))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testPrivateFileNullToken() throws Exception {
FileInfo fileInfo = new FileInfo();
fileInfo.setVirtualPath("/path/to/myfile");
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
mockMvc.perform(get("/path/to/myfile"))
.andDo(print())
.andExpect(status().isForbidden());
}
@Test
public void testGetFileWithJobId() throws Exception {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(tempFile.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setPublic(true);
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
when(jobDAO.isJobExisting(eq("abcdef"))).thenReturn(true);
mockMvc.perform(get("/path/to/myfile")
.param("jobId", "abcdef"))
.andDo(print())
.andExpect(status().isOk());
verify(jobDAO, times(1)).updateJobPhase(eq(ExecutionPhase.COMPLETED), eq("abcdef"));
}
@Test
public void testGetFileWithInvalidJobId() throws Exception {
mockMvc.perform(get("/path/to/myfile")
.param("jobId", "abcdef"))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void testGetFileNotReadable() throws Exception {
File unreadableFile = Files.newTemporaryFile();
try {
unreadableFile.setReadable(false);
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(unreadableFile.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setPublic(true);
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
Exception ex = mockMvc.perform(get("/path/to/myfile"))
.andDo(print())
.andReturn().getResolvedException();
assertTrue(ex instanceof VoSpaceErrorSummarizableException);
VoSpaceErrorSummarizableException jobEx = (VoSpaceErrorSummarizableException) ex;
assertTrue(jobEx.getDetailMessage().contains("not readable"), jobEx.getDetailMessage());
} catch (Throwable t) {
throw t;
} finally {
assertTrue(unreadableFile.delete());
}
}
private void prepareMocksForPrivateFile() {
Map claims = new HashMap<>();
claims.put("sub", "123");
when(tokenParser.getClaims(any())).thenReturn(claims);
when(gmsClient.isMemberOf(any(), any())).thenReturn(true);
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(tempFile.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/myfile");
fileInfo.setGroupRead(Collections.singletonList("group1"));
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/controller/PutFileControllerTest.java0000664 0000000 0000000 00000024245 14341627633 0034223 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.controller;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;
import java.util.UUID;
import javax.servlet.ServletInputStream;
import net.ivoa.xml.uws.v1.ExecutionPhase;
import org.assertj.core.util.Files;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import org.mockito.Mockito;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.util.FileSystemUtils;
@SpringBootTest
@AutoConfigureMockMvc
public class PutFileControllerTest {
@MockBean
private FileDAO fileDao;
@MockBean
private JobDAO jobDAO;
@Autowired
private MockMvc mockMvc;
private static File temporaryDirectory;
@BeforeAll
public static void setUp() {
temporaryDirectory = Files.newTemporaryFolder();
}
@AfterAll
public static void tearDown() {
FileSystemUtils.deleteRecursively(temporaryDirectory);
}
@Test
public void putGenericFile() throws Exception {
when(fileDao.getRemainingQuota(any())).thenReturn(null);
String randomFileName = UUID.randomUUID().toString();
FileInfo fileInfo = createBaseFileInfo(randomFileName);
MockMultipartFile fakeFile = new MockMultipartFile("file", "test.txt", "text/plain", "content".getBytes());
mockMvc.perform(putMultipart("/path/to/test.txt")
.file(fakeFile))
.andDo(print())
.andExpect(status().isOk());
File file = Path.of(fileInfo.getFilePath()).toFile();
assertTrue(file.exists());
assertEquals("content", Files.contentOf(file, StandardCharsets.UTF_8));
verify(fileDao, times(1)).updateFileAttributes(anyInt(), any(), eq("text/plain"), any(), eq(7l), eq("9A0364B9E99BB480DD25E1F0284C8555"));
assertTrue(file.delete());
}
@Test
public void putGenericFileOverwriteDenied() throws Exception {
when(fileDao.getRemainingQuota(any())).thenReturn(null);
String randomFileName = UUID.randomUUID().toString();
FileInfo fileInfo = createBaseFileInfo(randomFileName);
fileInfo.setFsPath("year/month/date/UUID-whatever");
MockMultipartFile fakeFile = new MockMultipartFile("file", "test.txt", "text/plain", "content".getBytes());
mockMvc.perform(putMultipart("/path/to/test.txt")
.file(fakeFile))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void putGenericFileWithJobId() throws Exception {
when(fileDao.getRemainingQuota(any())).thenReturn(null);
when(jobDAO.isJobExisting("pippo10")).thenReturn(false);
when(jobDAO.isJobExisting("pippo5")).thenReturn(true);
String randomFileName = UUID.randomUUID().toString();
FileInfo fileInfo = createBaseFileInfo(randomFileName);
MockMultipartFile fakeFile = new MockMultipartFile("file", "test.txt", "text/plain", "content".getBytes());
// Try with invalid jobid
mockMvc.perform(putMultipart("/path/to/test.txt")
.file(fakeFile).param("jobId", "pippo10"))
.andDo(print())
.andExpect(status().is4xxClientError());
verify(jobDAO, times(1)).isJobExisting(eq("pippo10"));
// Retry with valid jobid
mockMvc.perform(putMultipart("/path/to/test.txt")
.file(fakeFile).param("jobId", "pippo5"))
.andDo(print())
.andExpect(status().is2xxSuccessful());
verify(jobDAO, times(1)).isJobExisting(eq("pippo5"));
verify(jobDAO, times(1)).updateJobPhase(eq(ExecutionPhase.COMPLETED), any());
File file = Path.of(fileInfo.getFilePath()).toFile();
assertTrue(file.exists());
assertEquals("content", Files.contentOf(file, StandardCharsets.UTF_8));
assertTrue(file.delete());
}
@Test
public void testPutFileWithoutNodeInDatabase() throws Exception {
MockMultipartFile fakeFile = new MockMultipartFile("file", "foo.txt", "text/plain", "content".getBytes());
mockMvc.perform(putMultipart("/path/to/foo.txt")
.file(fakeFile))
.andDo(print())
.andExpect(status().isNotFound());
}
@Test
public void testPutWithInputStream() throws Exception {
createBaseFileInfo();
mockMvc.perform(put("/path/to/stream.txt"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testJobError() throws Exception {
createBaseFileInfo();
when(jobDAO.isJobExisting(eq("abcdef"))).thenReturn(true);
MockHttpServletRequestBuilder errorBuilder = put("/path/to/error");
errorBuilder.with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
MockHttpServletRequest spyRequest = spy(request);
when(spyRequest.getInputStream()).thenThrow(new RuntimeException());
return spyRequest;
}
});
try {
mockMvc.perform(errorBuilder
.param("jobId", "abcdef"));
} catch (Exception ex) {
}
verify(jobDAO, times(1)).setJobError(eq("abcdef"), any());
}
@Test
public void testQuotaExceededMultipart() throws Exception {
when(fileDao.getRemainingQuota(eq("/path/to"))).thenReturn(0l);
createBaseFileInfo();
MockMultipartFile fakeFile = new MockMultipartFile("file", "test.txt", null, "content".getBytes());
Exception ex = mockMvc.perform(putMultipart("/path/to/test.txt")
.file(fakeFile))
.andDo(print())
.andExpect(status().is5xxServerError())
.andReturn().getResolvedException();
verify(fileDao, times(1)).getRemainingQuota(eq("/path/to"));
assertTrue(ex instanceof QuotaExceededException);
}
@Test
public void testQuotaExceededStream() throws Exception {
when(fileDao.getRemainingQuota(eq("/path/to"))).thenReturn(0l);
createBaseFileInfo();
MockHttpServletRequestBuilder streamBuilder = put("/path/to/test.txt");
streamBuilder.with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
MockHttpServletRequest spyRequest = spy(request);
ByteArrayInputStream bais = new ByteArrayInputStream("some data".getBytes());
ServletInputStream sis = mock(ServletInputStream.class);
try {
when(sis.transferTo(any())).thenAnswer(i -> bais.transferTo(i.getArgument(0)));
} catch (IOException ex) {
}
Mockito.doReturn(sis).when(spyRequest).getInputStream();
return spyRequest;
}
});
Exception ex = mockMvc.perform(streamBuilder)
.andDo(print())
.andExpect(status().is5xxServerError())
.andReturn().getResolvedException();
verify(fileDao, times(1)).getRemainingQuota(eq("/path/to"));
assertTrue(ex instanceof QuotaExceededException);
}
private FileInfo createBaseFileInfo() {
String randomFileName = UUID.randomUUID().toString();
return createBaseFileInfo(randomFileName);
}
private FileInfo createBaseFileInfo(String fileName) {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath(temporaryDirectory.getAbsolutePath());
fileInfo.setVirtualPath("/path/to/" + fileName);
fileInfo.setPublic(false);
when(fileDao.getFileInfo(any())).thenReturn(Optional.of(fileInfo));
when(fileDao.setBusy(any(), any())).thenReturn(1);
return fileInfo;
}
private MockMultipartHttpServletRequestBuilder putMultipart(String uri) {
MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart(uri);
builder.with(new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setMethod("PUT");
return request;
}
});
return builder;
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/persistence/ 0000775 0000000 0000000 00000000000 14341627633 0027236 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/persistence/DataSourceConfig.java 0000664 0000000 0000000 00000014231 14341627633 0033262 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import com.opentable.db.postgres.embedded.EmbeddedPostgres;
import com.opentable.db.postgres.embedded.PgBinaryResolver;
import com.opentable.db.postgres.embedded.UncompressBundleDirectoryResolver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
/**
* Generates a DataSource that can be used for testing DAO classes. It loads an
* embedded Postgres database and fills it using the data from
* vospace-transfer-service repository (folder must exists; it location can be
* configured using the init_database_scripts_path in test.properties).
*/
@TestConfiguration
public class DataSourceConfig {
@Value("${init_database_scripts_path}")
private String scriptPath;
/**
* Using the prototype scope we are generating a different database in each
* test.
*/
@Bean
@Scope("prototype")
@Primary
public DataSource dataSource() throws Exception {
DataSource embeddedPostgresDS = EmbeddedPostgres.builder()
.setPgDirectoryResolver(new UncompressBundleDirectoryResolver(new CustomPostgresBinaryResolver()))
.start().getPostgresDatabase();
initDatabase(embeddedPostgresDS);
return embeddedPostgresDS;
}
private class CustomPostgresBinaryResolver implements PgBinaryResolver {
/**
* Loads specific embedded Postgres version.
*/
@Override
public InputStream getPgBinary(String system, String architecture) throws IOException {
ClassPathResource resource = new ClassPathResource(String.format("postgres-%s-%s.txz", system.toLowerCase(), architecture));
return resource.getInputStream();
}
}
/**
* Loads SQL scripts for database initialization from
* vospace-transfer-service repo directory.
*/
private void initDatabase(DataSource dataSource) throws Exception {
try ( Connection conn = dataSource.getConnection()) {
File currentDir = new File(DataSourceConfig.class.getClassLoader().getResource(".").getFile());
File scriptDir = currentDir.toPath().resolve(scriptPath).toFile().getCanonicalFile();
assertTrue(scriptDir.exists(), "DAO tests require " + scriptDir.getAbsolutePath() + " to exists.\n"
+ "Please clone the repository from https://www.ict.inaf.it/gitlab/vospace/vospace-file-catalog.git");
// load all sql files in vospace-file-catalog repo
File[] repoScripts = scriptDir.listFiles(f -> f.getName().endsWith(".sql"));
Arrays.sort(repoScripts); // sort alphabetically
// add test-data.sql
List scripts = new ArrayList<>(Arrays.asList(repoScripts));
scripts.add(new ClassPathResource("test-data.sql").getFile());
for (File script : scripts) {
String scriptContent = Files.readString(script.toPath());
for (String sql : splitScript(scriptContent)) {
executeSql(conn, replaceDollarQuoting(sql));
}
}
}
}
/**
* Spring ScriptUtils is not able to correctly split the SQL statements if a
* function definition contains semicolon characters, so this method is used
* instead of it.
*/
private List splitScript(String script) {
List parts = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean insideFunc = false;
for (int i = 0; i < script.length(); i++) {
char c = script.charAt(i);
sb.append(c);
if (insideFunc) {
if (i > 6 && "$func$".equals(script.substring(i - 6, i))) {
insideFunc = false;
}
} else {
if (i > 6 && "$func$".equals(script.substring(i - 6, i))) {
insideFunc = true;
} else if (c == ';') {
parts.add(sb.toString());
sb = new StringBuilder();
}
}
}
return parts;
}
private void executeSql(Connection conn, String sqlStatement) throws SQLException {
try ( Statement stat = conn.createStatement()) {
stat.execute(sqlStatement);
}
}
/**
* It seems that dollar quoting (used in UDF) is broken in JDBC. Replacing
* it with single quotes solves the problem. We replace the quoting here
* instead of inside the original files because dollar quoting provides a
* better visibility.
*/
private String replaceDollarQuoting(String scriptContent) {
if (scriptContent.contains("$func$")) {
String func = extractFunctionDefinition(scriptContent);
String originalFunction = "$func$" + func + "$func$";
String newFunction = "'" + func.replaceAll("'", "''") + "'";
scriptContent = scriptContent.replace(originalFunction, newFunction);
}
return scriptContent;
}
private String extractFunctionDefinition(String scriptContent) {
Pattern pattern = Pattern.compile("\\$func\\$(.*?)\\$func\\$", Pattern.DOTALL);
Matcher matcher = pattern.matcher(scriptContent);
if (matcher.find()) {
return matcher.group(1);
}
throw new IllegalArgumentException(scriptContent + " doesn't contain $func$");
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/persistence/FileDAOTest.java 0000664 0000000 0000000 00000012500 14341627633 0032142 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.sql.DataSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.util.ReflectionTestUtils;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@TestPropertySource(locations = "classpath:test.properties")
public class FileDAOTest {
@Autowired
private DataSource dataSource;
@Value("${upload_location_id}")
private int uploadLocationId;
private FileDAO dao;
@BeforeEach
public void init() {
dao = new FileDAO(dataSource);
ReflectionTestUtils.setField(dao, "uploadLocationId", uploadLocationId);
}
@Test
public void testGetBranchFileInfo() {
List fi = dao.getBranchFileInfos("/test100", "pippo");
assertEquals(3, fi.size());
List fi2 = dao.getBranchFileInfos("/test100/test1001.txt", "pippo");
assertEquals(1, fi2.size());
}
@Test
public void testSetBranchLocationId() {
dao.setBranchLocationId("/test100", "pippo", 3);
List fi = dao.getBranchFileInfos("/test100", "pippo");
assertEquals(3, fi.size());
fi.forEach(f -> {
assertEquals(3, f.getLocationId());
});
}
@Test
public void testGetFileInfo() {
Optional optFileInfo = dao.getFileInfo("/test1/file1.txt");
assertTrue(optFileInfo.isPresent());
FileInfo fileInfo = optFileInfo.get();
// TODO: refactor test
//assertEquals("/home/username1/vospace_retrieve/file1.txt", fileInfo.getOsPath());
}
@Test
public void testGetUnexistingFile() {
assertTrue(dao.getFileInfo("/doesnt/exist").isEmpty());
}
@Test
public void testGetArchiveFileInfos() {
List fileInfos = dao.getArchiveFileInfos(Arrays.asList("/public/file1", "/public/file2", "/public/subdir1"));
assertEquals(5, fileInfos.size());
assertEquals("/home/vospace/upload/2021/9/30/file1-UUID", fileInfos.get(0).getFilePath());
assertEquals("/home/vospace/upload/2021/9/30/file2-UUID", fileInfos.get(1).getFilePath());
assertEquals("user", fileInfos.get(1).getLocationType());
assertTrue(fileInfos.get(2).isDirectory());
assertNull(fileInfos.get(2).getLocationType());
assertEquals("/home/username1/vospace_retrieve/2021/9/30/file3-UUID", fileInfos.get(3).getFilePath());
assertEquals("/home/username1/vospace_retrieve/2021/9/30/file4-UUID", fileInfos.get(4).getFilePath());
assertEquals("async", fileInfos.get(4).getLocationType());
}
@Test
public void testGetRemainingQuota() {
assertEquals(600000l, dao.getRemainingQuota("/test_quota"));
assertEquals(200000l, dao.getRemainingQuota("/test_quota/subdir"));
}
@Test
public void testGetNoQuota() {
assertNull(dao.getRemainingQuota("/"));
}
@Test
public void testSetBusy() {
FileInfo fileInfo = dao.getFileInfo("/public/file1").get();
assertNull(fileInfo.getJobId());
dao.setBusy(fileInfo.getVirtualPath(), "pippo1");
assertEquals("pippo1", dao.getFileInfo("/public/file1").get().getJobId());
dao.setBusy(fileInfo.getVirtualPath(), null);
assertNull(dao.getFileInfo("/public/file1").get().getJobId());
}
@Test
public void testReleaseNodesByJobId() {
List fi = dao.getBranchFileInfos("/test100", "pippo");
assertEquals(3, fi.size());
dao.releaseBusyNodesByJobId("pippo");
fi = dao.getBranchFileInfos("/test100", "pippo");
assertEquals(0, fi.size());
}
@Test
public void testUpdateFileAttributes() {
FileInfo fileInfo = dao.getFileInfo("/public/file1").get();
assertNull(fileInfo.getContentLength());
assertNull(fileInfo.getContentType());
assertNull(fileInfo.getContentEncoding());
assertNull(fileInfo.getContentMd5());
assertEquals("2021/9/30/file1-UUID", fileInfo.getFsPath());
dao.updateFileAttributes(fileInfo.getNodeId(), "/2021/09/24/UIID-1", "text/plain", "UTF-8", 50000l, "");
fileInfo = dao.getFileInfo("/public/file1").get();
assertEquals(50000l, fileInfo.getContentLength());
assertEquals("2021/09/24/UIID-1", fileInfo.getFsPath());
assertEquals("text/plain", fileInfo.getContentType());
assertEquals("UTF-8", fileInfo.getContentEncoding());
assertEquals("", fileInfo.getContentMd5());
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/persistence/JobDAOTest.java 0000664 0000000 0000000 00000003713 14341627633 0032003 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.persistence;
import it.inaf.oats.vospace.exception.InternalFaultException;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import net.ivoa.xml.uws.v1.ExecutionPhase;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {DataSourceConfig.class})
@TestPropertySource(locations = "classpath:test.properties")
public class JobDAOTest {
@Autowired
private DataSource dataSource;
private JobDAO dao;
@BeforeEach
public void init() {
dao = new JobDAO(dataSource);
}
@Test
public void testJobPhase() {
assertTrue(dao.isJobExisting("pippo5"));
assertFalse(dao.isJobExisting("pippo22"));
ExecutionPhase phase = dao.getJobPhase("pippo5");
assertEquals(ExecutionPhase.EXECUTING, phase);
dao.updateJobPhase(ExecutionPhase.COMPLETED, "pippo5");
phase = dao.getJobPhase("pippo5");
assertEquals(ExecutionPhase.COMPLETED, phase);
}
@Test
public void testSetJobError() {
assertEquals(ExecutionPhase.QUEUED, dao.getJobPhase("pippo3"));
InternalFaultException jobError = new InternalFaultException("Error detail");
dao.setJobError("pippo3", jobError);
assertEquals(ExecutionPhase.ERROR, dao.getJobPhase("pippo3"));
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/service/ 0000775 0000000 0000000 00000000000 14341627633 0026352 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/service/ArchiveServiceTest.java 0000664 0000000 0000000 00000025567 14341627633 0032776 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.oats.vospace.exception.QuotaExceededException;
import it.inaf.oats.vospace.parent.exchange.ArchiveEntryDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.kamranzafar.jtar.TarEntry;
import org.kamranzafar.jtar.TarInputStream;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.client.RestTemplate;
@SpringBootTest
@ContextConfiguration(initializers = ArchiveServiceTest.TestPropertiesInitializer.class)
public class ArchiveServiceTest {
@MockBean
private JobDAO jobDAO;
@MockBean
private FileDAO fileDAO;
@MockBean
private RestTemplate restTemplate;
@MockBean
private AuthorizationService authorizationService;
@Autowired
private ArchiveService archiveService;
private static File tmpDir;
@BeforeAll
public static void setUpClass() throws Exception {
tmpDir = Files.createTempDirectory("generated").toFile();
}
@AfterAll
public static void tearDownClass() throws Exception {
FileSystemUtils.deleteRecursively(tmpDir);
}
@Test
public void testTarGeneration() throws Exception {
testArchiveGeneration(ArchiveJob.Type.TAR, "tar", is -> new TestArchiveHandler(new TarInputStream(is)) {
@Override
TarEntry getNextEntry() throws IOException {
return getInputStream().getNextEntry();
}
@Override
String getName(TarEntry entry) {
return entry.getName();
}
@Override
boolean isDirectory(TarEntry entry) {
return entry.isDirectory();
}
});
}
@Test
public void testZipGeneration() throws Exception {
testArchiveGeneration(ArchiveJob.Type.ZIP, "zip", is -> new TestArchiveHandler(new ZipInputStream(is)) {
@Override
ZipEntry getNextEntry() throws IOException {
return getInputStream().getNextEntry();
}
@Override
String getName(ZipEntry entry) {
return entry.getName();
}
@Override
boolean isDirectory(ZipEntry entry) {
return entry.isDirectory();
}
});
}
@Test
public void testArchiveQuotaExceeded() throws Exception {
ArchiveJob job = new ArchiveJob();
job.setPrincipal(new TokenPrincipal("user2", "token2"));
job.setJobId("job2");
job.setType(ArchiveJob.Type.ZIP);
job.setEntryDescriptors(List.of(this.getArchiveEntryDescriptor("/ignore")));
HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
when(servletRequest.getUserPrincipal()).thenReturn(job.getPrincipal());
File user2Dir = tmpDir.toPath().resolve("user2").toFile();
user2Dir.mkdir();
File fillQuotaFile = user2Dir.toPath().resolve("fillQuotaFile").toFile();
// create a file bigger than test quota limit (20 KB)
try (FileInputStream fis = new FileInputStream("/dev/zero");
FileOutputStream fos = new FileOutputStream(fillQuotaFile)) {
byte[] junk = fis.readNBytes(20 * 1024);
fos.write(junk);
}
Assertions.assertThrows(QuotaExceededException.class, () -> {
archiveService.createArchive(job, servletRequest);
});
}
private static abstract class TestArchiveHandler {
private final I is;
TestArchiveHandler(I is) {
this.is = is;
}
I getInputStream() {
return is;
}
abstract E getNextEntry() throws IOException;
abstract String getName(E entry);
abstract boolean isDirectory(E entry);
}
private void testArchiveGeneration(ArchiveJob.Type type, String extension, Function> testArchiveGetter) throws Exception {
String parent = "/path/to";
File tmpParent = tmpDir.toPath().resolve("test1").toFile();
File file1 = createFile(tmpParent, "2021/10/1/UUID-file1");
File file2 = createFile(tmpParent, "2021/10/1/UUID-file2");
File file3 = createFile(tmpParent, "2021/10/1/UUID-file3");
File file4 = createFile(tmpParent, "2021/10/1/UUID-file4");
File file5 = createFile(tmpParent, "2021/10/1/UUID-file5");
File file6 = createFile(tmpParent, "2021/10/1/UUID-file6");
ArchiveJob job = new ArchiveJob();
job.setPrincipal(new TokenPrincipal("user1", "token1"));
job.setJobId("abcdef");
job.setType(type);
job.setEntryDescriptors(List.of(
this.getArchiveEntryDescriptor(parent + "/dir1"),
this.getArchiveEntryDescriptor(parent + "/dir2"),
this.getArchiveEntryDescriptor(parent + "/file6")
));
HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
when(servletRequest.getUserPrincipal()).thenReturn(job.getPrincipal());
when(authorizationService.isDownloadable(any(), any())).thenReturn(true);
List fileInfos = new ArrayList<>();
addFileInfo(fileInfos, parent + "/file6", file6);
addDirInfo(fileInfos, parent + "/dir1");
addDirInfo(fileInfos, parent + "/dir1/a");
addDirInfo(fileInfos, parent + "/dir1/a/b");
addFileInfo(fileInfos, parent + "/dir1/a/b/file1", file1);
addFileInfo(fileInfos, parent + "/dir1/a/b/file2", file2);
addDirInfo(fileInfos, parent + "/dir2");
addDirInfo(fileInfos, parent + "/dir2/c");
addFileInfo(fileInfos, parent + "/dir2/c/file3", file3);
addFileInfo(fileInfos, parent + "/dir2/c/file4", file4);
addDirInfo(fileInfos, parent + "/dir2/c/d");
addFileInfo(fileInfos, parent + "/dir2/c/d/file5", file5);
when(fileDAO.getArchiveFileInfos(any())).thenReturn(fileInfos);
archiveService.createArchive(job, servletRequest);
File result = tmpDir.toPath().resolve("user1").resolve("abcdef." + extension).toFile();
assertTrue(result.exists());
// verify result structure
List expectedSequence = Arrays.asList("file6", "dir1/", "dir1/a/", "dir1/a/b/",
"dir1/a/b/file1", "dir1/a/b/file2", "dir2/", "dir2/c/", "dir2/c/file3", "dir2/c/file4",
"dir2/c/d/", "dir2/c/d/file5");
int i = 0;
TestArchiveHandler testArchiveHandler = testArchiveGetter.apply(new FileInputStream(result));
try (InputStream is = testArchiveHandler.getInputStream()) {
E entry;
while ((entry = testArchiveHandler.getNextEntry()) != null) {
assertFalse(i >= expectedSequence.size(), "Found more entries than in expected sequence");
assertEquals(type.equals(ArchiveJob.Type.ZIP) ?
"/" + expectedSequence.get(i) : expectedSequence.get(i),
testArchiveHandler.getName(entry));
if (!testArchiveHandler.isDirectory(entry)) {
assertEquals("some data", new String(is.readAllBytes()));
}
i++;
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
assertFalse(i < expectedSequence.size(), "Found less entries than in expected sequence");
}
private FileInfo addFileInfo(List fileInfos, String vosPath, File file) {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(file.getAbsolutePath());
fileInfo.setVirtualPath(vosPath);
fileInfo.setVirtualName(vosPath.substring(vosPath.lastIndexOf("/") + 1));
fileInfos.add(fileInfo);
return fileInfo;
}
private FileInfo addDirInfo(List fileInfos, String vosPath) {
FileInfo fileInfo = new FileInfo();
fileInfo.setVirtualPath(vosPath);
fileInfo.setDirectory(true);
fileInfos.add(fileInfo);
return fileInfo;
}
private File createFile(File parent, String path) throws Exception {
File file = parent.toPath().resolve(path).toFile();
file.getParentFile().mkdirs();
file.createNewFile();
Files.write(file.toPath(), "some data".getBytes());
return file;
}
private ArchiveEntryDescriptor getArchiveEntryDescriptor(String vosPath) {
return new ArchiveEntryDescriptor(vosPath);
}
/**
* @TestPropertySource annotation can't be used in this test because we need
* to set the generated.dir property dynamically (since the test directory
* is generated by the @BeforeAll method), so this inner class is used to
* perform test property initialization.
*/
static class TestPropertiesInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertyValues.of("generated.dir=" + tmpDir.getAbsolutePath(),
"generated.dir.max-size=20KB", "upload_location_id=3")
.applyTo(configurableApplicationContext.getEnvironment());
}
}
}
vospace-file-service-master/src/test/java/it/inaf/ia2/transfer/service/CopyServiceTest.java 0000664 0000000 0000000 00000012337 14341627633 0032316 0 ustar 00root root 0000000 0000000 /*
* This file is part of vospace-file-service
* Copyright (C) 2021 Istituto Nazionale di Astrofisica
* SPDX-License-Identifier: GPL-3.0-or-later
*/
package it.inaf.ia2.transfer.service;
import it.inaf.ia2.transfer.auth.TokenPrincipal;
import it.inaf.ia2.transfer.persistence.model.FileInfo;
import it.inaf.ia2.transfer.persistence.FileDAO;
import it.inaf.ia2.transfer.persistence.JobDAO;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.assertj.core.util.Files;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.FileSystemUtils;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
public class CopyServiceTest {
@MockBean
private FileDAO fileDao;
@MockBean
private JobDAO jobDao;
@Autowired
private MockMvc mockMvc;
@Autowired
private FileCopyService fileCopyService;
private static File sourceDirectory;
private static File destinationDirectory;
private static File sourceFile;
private static String jobId;
private static String sourceVosRootPath;
private static String destVosRootPath;
private static String filename;
private static String userId;
@BeforeAll
public static void setUp() {
jobId = "pippo_copy";
userId = "user_copy";
filename = "file.txt";
sourceVosRootPath = "/source/" + filename;
destVosRootPath = "/destination/" + filename;
}
@BeforeEach
public void setUpPerTest() throws Exception {
sourceDirectory = Files.newTemporaryFolder();
destinationDirectory = Files.newTemporaryFolder();
sourceFile = this.createFile(sourceDirectory, filename);
}
@AfterEach
public void tearDown() {
FileSystemUtils.deleteRecursively(sourceDirectory);
FileSystemUtils.deleteRecursively(destinationDirectory);
}
@Test
public void testCopyService() throws Exception {
when(fileDao.getBranchFileInfos(eq(sourceVosRootPath), eq(jobId)))
.thenReturn(
List.of(this.createBaseFileInfo(
filename, sourceDirectory, sourceVosRootPath)));
FileInfo destinationFileInfo = this.createBaseDestinationFileInfo(
filename, destinationDirectory, destVosRootPath);
when(fileDao.getBranchFileInfos(eq(destVosRootPath), eq(jobId)))
.thenReturn(List.of(destinationFileInfo));
when(fileDao.getRemainingQuota(any())).thenReturn(null);
assertTrue(sourceFile.exists());
fileCopyService.copyFiles(
sourceVosRootPath, destVosRootPath, jobId, fakePrincipal(userId));
assertTrue(sourceFile.exists());
File destinationFile = Path.of(destinationFileInfo.getFilePath()).toFile();
assertTrue(destinationFile.exists());
assertTrue(FileUtils.contentEquals(sourceFile, destinationFile));
}
private FileInfo createBaseFileInfo(String fileName, File directory, String vosPath) {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath("/");
fileInfo.setFsPath(getTestFilePath(fileName, directory));
fileInfo.setVirtualPath(vosPath);
fileInfo.setPublic(false);
fileInfo.setOwnerId(userId);
return fileInfo;
}
private FileInfo createBaseDestinationFileInfo(String fileName, File directory, String vosPath) {
FileInfo fileInfo = new FileInfo();
fileInfo.setActualBasePath(directory.getAbsolutePath());
fileInfo.setVirtualPath(vosPath);
fileInfo.setPublic(false);
fileInfo.setOwnerId(userId);
return fileInfo;
}
private String getTestFilePath(String fileName, File directory) {
return directory.toPath().resolve(fileName).toFile().getAbsolutePath();
}
private File createFile(File parent, String filename) throws Exception {
parent.mkdir();
File file = parent.toPath().resolve(filename).toFile();
file.createNewFile();
java.nio.file.Files.write(file.toPath(), "content_of_file".getBytes());
return file;
}
private TokenPrincipal fakePrincipal(String name) {
TokenPrincipal principal = mock(TokenPrincipal.class);
when(principal.getName()).thenReturn(name);
when(principal.getToken()).thenReturn("any_token_not_null");
return principal;
}
}
vospace-file-service-master/src/test/resources/ 0000775 0000000 0000000 00000000000 14341627633 0022153 5 ustar 00root root 0000000 0000000 vospace-file-service-master/src/test/resources/test-data.sql 0000664 0000000 0000000 00000010574 14341627633 0024571 0 ustar 00root root 0000000 0000000 INSERT INTO storage (storage_type, base_path, hostname) VALUES ('cold', '/ia2_tape/users', 'tape-server');
INSERT INTO storage (storage_type, base_path, hostname) VALUES ('hot', '/mnt/hot_storage/users', 'server');
INSERT INTO storage (storage_type, base_path, hostname) VALUES ('local', '/home', 'localhost');
INSERT INTO storage (storage_type, base_path, hostname) VALUES ('local', '/home/vospace/upload', 'localhost');
INSERT INTO location (location_type, storage_src_id, storage_dest_id) VALUES ('async', 1, 3);
INSERT INTO location (location_type, storage_src_id, storage_dest_id) VALUES ('async', 2, 3);
INSERT INTO location (location_type, storage_src_id, storage_dest_id) VALUES ('user', 4, 4);
DELETE FROM node;
ALTER SEQUENCE node_node_id_seq RESTART WITH 1;
DELETE FROM users;
INSERT INTO users (user_id, user_name, e_mail) VALUES ('user1', 'username1', 'ia2@inaf.it');
INSERT INTO node (parent_path, name, type, creator_id) VALUES (NULL, '', 'container', '0');
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write) VALUES ('', 'test1', 'container', 'user1', '{"group1","group2"}','{"group2"}'); -- /test1
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, location_id) VALUES ('2', 'file1.txt', 'data', 'user1', '{"group1","group2"}','{"group2"}', 1); -- /test1/file1.txt
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, location_id) VALUES ('2', 'file2.txt', 'data', 'user1', '{"group1","group2"}','{"group2"}', 1); -- /test1/file2.txt
-- test data for tar/zip archive
INSERT INTO node (parent_path, name, fs_path, type, creator_id, location_id, is_public) VALUES
('', 'public', NULL, 'container', 'user1', NULL, true),
('5', 'file1', '2021/9/30/file1-UUID', 'data', 'user1', 3, true),
('5', 'file2', '2021/9/30/file2-UUID', 'data', 'user1', 3, true),
('5', 'subdir1', NULL, 'container', 'user1', NULL, true),
('5.8', 'file3', '2021/9/30/file3-UUID', 'data', 'user1', 1, true),
('5.8', 'file4', '2021/9/30/file4-UUID', 'data', 'user1', 1, true);
INSERT INTO node (parent_path, name, type, creator_id, content_length, quota) VALUES
('', 'test_quota', 'container', 'user1', 0, 900000),
('11', 'subdir', 'container', 'user1', 0, 500000),
('11.12', 'file1', 'data', 'user1', 100000, 500000),
('11.12', 'file2', 'data', 'user1', 200000, 500000);
-- test data for get branch file info
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, job_id) VALUES ('', 'test100', 'container', 'user1', '{"group1","group2"}','{"group2"}', 'pippo'); -- /test100
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, job_id) VALUES ('15', 'test1001.txt', 'data', 'user1', '{"group1","group2"}','{"group2"}', 'pippo'); -- /test100
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, job_id) VALUES ('15', 'test1002.txt', 'data', 'user1', '{"group1","group2"}','{"group2"}', 'pippo'); -- /test100
INSERT INTO node (parent_path, name, type, creator_id, group_read, group_write, job_id) VALUES ('15', 'test1003.txt', 'data', 'user1', '{"group1","group2"}','{"group2"}', NULL); -- /test100
DELETE FROM job;
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo1', 'user1', 'pullFromVoSpace', 'ARCHIVED', NULL, NULL, '2011-06-22 19:10:25', NULL, NULL);
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo2', 'user1', 'pullToVoSpace', 'PENDING', NULL, NULL, '2012-06-22 19:10:25', NULL, NULL);
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo3', 'user1', 'pullFromVoSpace', 'QUEUED', NULL, NULL, '2013-06-22 19:10:25', NULL, NULL);
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo4', 'user2', 'copyNode', 'PENDING', NULL, NULL, '2014-06-22 19:10:25', NULL, NULL);
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo5', 'user1', 'pushToVoSpace', 'EXECUTING', NULL, NULL, '2015-06-22 19:10:25', NULL, NULL);
INSERT INTO job (job_id, owner_id, job_type, phase, start_time, end_time, creation_time, job_info, results) VALUES ('pippo6', 'user2', 'pullFromVoSpace', 'PENDING', NULL, NULL, '2015-06-22 19:10:25', NULL, NULL);
vospace-file-service-master/src/test/resources/test.properties 0000664 0000000 0000000 00000000257 14341627633 0025254 0 ustar 00root root 0000000 0000000 # File catalog repository directory (filled by pom.xml, overridable passing environment variable)
init_database_scripts_path=@init_database_scripts_path@
upload_location_id=3